code_generator.cc revision 015c7e63604c038e866d7af3850c557403cddc8b
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "code_generator.h" 18 19#include "code_generator_arm.h" 20#include "code_generator_arm64.h" 21#include "code_generator_x86.h" 22#include "code_generator_x86_64.h" 23#include "compiled_method.h" 24#include "dex/verified_method.h" 25#include "driver/dex_compilation_unit.h" 26#include "gc_map_builder.h" 27#include "leb128.h" 28#include "mapping_table.h" 29#include "mirror/array-inl.h" 30#include "mirror/object_array-inl.h" 31#include "mirror/object_reference.h" 32#include "ssa_liveness_analysis.h" 33#include "utils/assembler.h" 34#include "verifier/dex_gc_map.h" 35#include "vmap_table.h" 36 37namespace art { 38 39// Return whether a location is consistent with a type. 40static bool CheckType(Primitive::Type type, Location location) { 41 if (location.IsFpuRegister() 42 || (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresFpuRegister))) { 43 return (type == Primitive::kPrimFloat) || (type == Primitive::kPrimDouble); 44 } else if (location.IsRegister() || 45 (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresRegister))) { 46 return Primitive::IsIntegralType(type) || (type == Primitive::kPrimNot); 47 } else if (location.IsRegisterPair()) { 48 return type == Primitive::kPrimLong; 49 } else if (location.IsFpuRegisterPair()) { 50 return type == Primitive::kPrimDouble; 51 } else if (location.IsStackSlot()) { 52 return (Primitive::IsIntegralType(type) && type != Primitive::kPrimLong) 53 || (type == Primitive::kPrimFloat) 54 || (type == Primitive::kPrimNot); 55 } else if (location.IsDoubleStackSlot()) { 56 return (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble); 57 } else if (location.IsConstant()) { 58 if (location.GetConstant()->IsIntConstant()) { 59 return Primitive::IsIntegralType(type) && (type != Primitive::kPrimLong); 60 } else if (location.GetConstant()->IsNullConstant()) { 61 return type == Primitive::kPrimNot; 62 } else if (location.GetConstant()->IsLongConstant()) { 63 return type == Primitive::kPrimLong; 64 } else if (location.GetConstant()->IsFloatConstant()) { 65 return type == Primitive::kPrimFloat; 66 } else { 67 return location.GetConstant()->IsDoubleConstant() 68 && (type == Primitive::kPrimDouble); 69 } 70 } else { 71 return location.IsInvalid() || (location.GetPolicy() == Location::kAny); 72 } 73} 74 75// Check that a location summary is consistent with an instruction. 76static bool CheckTypeConsistency(HInstruction* instruction) { 77 LocationSummary* locations = instruction->GetLocations(); 78 if (locations == nullptr) { 79 return true; 80 } 81 82 if (locations->Out().IsUnallocated() 83 && (locations->Out().GetPolicy() == Location::kSameAsFirstInput)) { 84 DCHECK(CheckType(instruction->GetType(), locations->InAt(0))) 85 << instruction->GetType() 86 << " " << locations->InAt(0); 87 } else { 88 DCHECK(CheckType(instruction->GetType(), locations->Out())) 89 << instruction->GetType() 90 << " " << locations->Out(); 91 } 92 93 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) { 94 DCHECK(CheckType(instruction->InputAt(i)->GetType(), locations->InAt(i))) 95 << instruction->InputAt(i)->GetType() 96 << " " << locations->InAt(i); 97 } 98 99 HEnvironment* environment = instruction->GetEnvironment(); 100 for (size_t i = 0; i < instruction->EnvironmentSize(); ++i) { 101 if (environment->GetInstructionAt(i) != nullptr) { 102 Primitive::Type type = environment->GetInstructionAt(i)->GetType(); 103 DCHECK(CheckType(type, environment->GetLocationAt(i))) 104 << type << " " << environment->GetLocationAt(i); 105 } else { 106 DCHECK(environment->GetLocationAt(i).IsInvalid()) 107 << environment->GetLocationAt(i); 108 } 109 } 110 return true; 111} 112 113size_t CodeGenerator::GetCacheOffset(uint32_t index) { 114 return mirror::ObjectArray<mirror::Object>::OffsetOfElement(index).SizeValue(); 115} 116 117size_t CodeGenerator::GetCachePointerOffset(uint32_t index) { 118 auto pointer_size = InstructionSetPointerSize(GetInstructionSet()); 119 return mirror::Array::DataOffset(pointer_size).Uint32Value() + pointer_size * index; 120} 121 122void CodeGenerator::CompileBaseline(CodeAllocator* allocator, bool is_leaf) { 123 Initialize(); 124 if (!is_leaf) { 125 MarkNotLeaf(); 126 } 127 const bool is_64_bit = Is64BitInstructionSet(GetInstructionSet()); 128 InitializeCodeGeneration(GetGraph()->GetNumberOfLocalVRegs() 129 + GetGraph()->GetTemporariesVRegSlots() 130 + 1 /* filler */, 131 0, /* the baseline compiler does not have live registers at slow path */ 132 0, /* the baseline compiler does not have live registers at slow path */ 133 GetGraph()->GetMaximumNumberOfOutVRegs() 134 + (is_64_bit ? 2 : 1) /* current method */, 135 GetGraph()->GetBlocks()); 136 CompileInternal(allocator, /* is_baseline */ true); 137} 138 139bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const { 140 DCHECK_EQ(block_order_->Get(current_block_index_), current); 141 return GetNextBlockToEmit() == FirstNonEmptyBlock(next); 142} 143 144HBasicBlock* CodeGenerator::GetNextBlockToEmit() const { 145 for (size_t i = current_block_index_ + 1; i < block_order_->Size(); ++i) { 146 HBasicBlock* block = block_order_->Get(i); 147 if (!block->IsSingleGoto()) { 148 return block; 149 } 150 } 151 return nullptr; 152} 153 154HBasicBlock* CodeGenerator::FirstNonEmptyBlock(HBasicBlock* block) const { 155 while (block->IsSingleGoto()) { 156 block = block->GetSuccessors().Get(0); 157 } 158 return block; 159} 160 161void CodeGenerator::CompileInternal(CodeAllocator* allocator, bool is_baseline) { 162 is_baseline_ = is_baseline; 163 HGraphVisitor* instruction_visitor = GetInstructionVisitor(); 164 DCHECK_EQ(current_block_index_, 0u); 165 GenerateFrameEntry(); 166 DCHECK_EQ(GetAssembler()->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size_)); 167 for (size_t e = block_order_->Size(); current_block_index_ < e; ++current_block_index_) { 168 HBasicBlock* block = block_order_->Get(current_block_index_); 169 // Don't generate code for an empty block. Its predecessors will branch to its successor 170 // directly. Also, the label of that block will not be emitted, so this helps catch 171 // errors where we reference that label. 172 if (block->IsSingleGoto()) continue; 173 Bind(block); 174 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) { 175 HInstruction* current = it.Current(); 176 if (is_baseline) { 177 InitLocationsBaseline(current); 178 } 179 DCHECK(CheckTypeConsistency(current)); 180 current->Accept(instruction_visitor); 181 } 182 } 183 184 // Generate the slow paths. 185 for (size_t i = 0, e = slow_paths_.Size(); i < e; ++i) { 186 slow_paths_.Get(i)->EmitNativeCode(this); 187 } 188 189 // Finalize instructions in assember; 190 Finalize(allocator); 191} 192 193void CodeGenerator::CompileOptimized(CodeAllocator* allocator) { 194 // The register allocator already called `InitializeCodeGeneration`, 195 // where the frame size has been computed. 196 DCHECK(block_order_ != nullptr); 197 Initialize(); 198 CompileInternal(allocator, /* is_baseline */ false); 199} 200 201void CodeGenerator::Finalize(CodeAllocator* allocator) { 202 size_t code_size = GetAssembler()->CodeSize(); 203 uint8_t* buffer = allocator->Allocate(code_size); 204 205 MemoryRegion code(buffer, code_size); 206 GetAssembler()->FinalizeInstructions(code); 207} 208 209size_t CodeGenerator::FindFreeEntry(bool* array, size_t length) { 210 for (size_t i = 0; i < length; ++i) { 211 if (!array[i]) { 212 array[i] = true; 213 return i; 214 } 215 } 216 LOG(FATAL) << "Could not find a register in baseline register allocator"; 217 UNREACHABLE(); 218} 219 220size_t CodeGenerator::FindTwoFreeConsecutiveAlignedEntries(bool* array, size_t length) { 221 for (size_t i = 0; i < length - 1; i += 2) { 222 if (!array[i] && !array[i + 1]) { 223 array[i] = true; 224 array[i + 1] = true; 225 return i; 226 } 227 } 228 LOG(FATAL) << "Could not find a register in baseline register allocator"; 229 UNREACHABLE(); 230} 231 232void CodeGenerator::InitializeCodeGeneration(size_t number_of_spill_slots, 233 size_t maximum_number_of_live_core_registers, 234 size_t maximum_number_of_live_fp_registers, 235 size_t number_of_out_slots, 236 const GrowableArray<HBasicBlock*>& block_order) { 237 block_order_ = &block_order; 238 DCHECK(block_order_->Get(0) == GetGraph()->GetEntryBlock()); 239 ComputeSpillMask(); 240 first_register_slot_in_slow_path_ = (number_of_out_slots + number_of_spill_slots) * kVRegSize; 241 242 if (number_of_spill_slots == 0 243 && !HasAllocatedCalleeSaveRegisters() 244 && IsLeafMethod() 245 && !RequiresCurrentMethod()) { 246 DCHECK_EQ(maximum_number_of_live_core_registers, 0u); 247 DCHECK_EQ(maximum_number_of_live_fp_registers, 0u); 248 SetFrameSize(CallPushesPC() ? GetWordSize() : 0); 249 } else { 250 SetFrameSize(RoundUp( 251 number_of_spill_slots * kVRegSize 252 + number_of_out_slots * kVRegSize 253 + maximum_number_of_live_core_registers * GetWordSize() 254 + maximum_number_of_live_fp_registers * GetFloatingPointSpillSlotSize() 255 + FrameEntrySpillSize(), 256 kStackAlignment)); 257 } 258} 259 260Location CodeGenerator::GetTemporaryLocation(HTemporary* temp) const { 261 uint16_t number_of_locals = GetGraph()->GetNumberOfLocalVRegs(); 262 // The type of the previous instruction tells us if we need a single or double stack slot. 263 Primitive::Type type = temp->GetType(); 264 int32_t temp_size = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble) ? 2 : 1; 265 // Use the temporary region (right below the dex registers). 266 int32_t slot = GetFrameSize() - FrameEntrySpillSize() 267 - kVRegSize // filler 268 - (number_of_locals * kVRegSize) 269 - ((temp_size + temp->GetIndex()) * kVRegSize); 270 return temp_size == 2 ? Location::DoubleStackSlot(slot) : Location::StackSlot(slot); 271} 272 273int32_t CodeGenerator::GetStackSlot(HLocal* local) const { 274 uint16_t reg_number = local->GetRegNumber(); 275 uint16_t number_of_locals = GetGraph()->GetNumberOfLocalVRegs(); 276 if (reg_number >= number_of_locals) { 277 // Local is a parameter of the method. It is stored in the caller's frame. 278 // TODO: Share this logic with StackVisitor::GetVRegOffsetFromQuickCode. 279 return GetFrameSize() + InstructionSetPointerSize(GetInstructionSet()) // ART method 280 + (reg_number - number_of_locals) * kVRegSize; 281 } else { 282 // Local is a temporary in this method. It is stored in this method's frame. 283 return GetFrameSize() - FrameEntrySpillSize() 284 - kVRegSize // filler. 285 - (number_of_locals * kVRegSize) 286 + (reg_number * kVRegSize); 287 } 288} 289 290void CodeGenerator::CreateCommonInvokeLocationSummary( 291 HInvoke* invoke, InvokeDexCallingConventionVisitor* visitor) { 292 ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetArena(); 293 LocationSummary* locations = new (allocator) LocationSummary(invoke, LocationSummary::kCall); 294 295 for (size_t i = 0; i < invoke->GetNumberOfArguments(); i++) { 296 HInstruction* input = invoke->InputAt(i); 297 locations->SetInAt(i, visitor->GetNextLocation(input->GetType())); 298 } 299 300 locations->SetOut(visitor->GetReturnLocation(invoke->GetType())); 301 302 if (invoke->IsInvokeStaticOrDirect()) { 303 HInvokeStaticOrDirect* call = invoke->AsInvokeStaticOrDirect(); 304 if (call->IsStringInit()) { 305 locations->AddTemp(visitor->GetMethodLocation()); 306 } else if (call->IsRecursive()) { 307 locations->SetInAt(call->GetCurrentMethodInputIndex(), visitor->GetMethodLocation()); 308 } else { 309 locations->AddTemp(visitor->GetMethodLocation()); 310 locations->SetInAt(call->GetCurrentMethodInputIndex(), Location::RequiresRegister()); 311 } 312 } else { 313 locations->AddTemp(visitor->GetMethodLocation()); 314 } 315} 316 317void CodeGenerator::BlockIfInRegister(Location location, bool is_out) const { 318 // The DCHECKS below check that a register is not specified twice in 319 // the summary. The out location can overlap with an input, so we need 320 // to special case it. 321 if (location.IsRegister()) { 322 DCHECK(is_out || !blocked_core_registers_[location.reg()]); 323 blocked_core_registers_[location.reg()] = true; 324 } else if (location.IsFpuRegister()) { 325 DCHECK(is_out || !blocked_fpu_registers_[location.reg()]); 326 blocked_fpu_registers_[location.reg()] = true; 327 } else if (location.IsFpuRegisterPair()) { 328 DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()]); 329 blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()] = true; 330 DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()]); 331 blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()] = true; 332 } else if (location.IsRegisterPair()) { 333 DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairLow<int>()]); 334 blocked_core_registers_[location.AsRegisterPairLow<int>()] = true; 335 DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairHigh<int>()]); 336 blocked_core_registers_[location.AsRegisterPairHigh<int>()] = true; 337 } 338} 339 340void CodeGenerator::AllocateRegistersLocally(HInstruction* instruction) const { 341 LocationSummary* locations = instruction->GetLocations(); 342 if (locations == nullptr) return; 343 344 for (size_t i = 0, e = GetNumberOfCoreRegisters(); i < e; ++i) { 345 blocked_core_registers_[i] = false; 346 } 347 348 for (size_t i = 0, e = GetNumberOfFloatingPointRegisters(); i < e; ++i) { 349 blocked_fpu_registers_[i] = false; 350 } 351 352 for (size_t i = 0, e = number_of_register_pairs_; i < e; ++i) { 353 blocked_register_pairs_[i] = false; 354 } 355 356 // Mark all fixed input, temp and output registers as used. 357 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) { 358 BlockIfInRegister(locations->InAt(i)); 359 } 360 361 for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) { 362 Location loc = locations->GetTemp(i); 363 BlockIfInRegister(loc); 364 } 365 Location result_location = locations->Out(); 366 if (locations->OutputCanOverlapWithInputs()) { 367 BlockIfInRegister(result_location, /* is_out */ true); 368 } 369 370 SetupBlockedRegisters(/* is_baseline */ true); 371 372 // Allocate all unallocated input locations. 373 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) { 374 Location loc = locations->InAt(i); 375 HInstruction* input = instruction->InputAt(i); 376 if (loc.IsUnallocated()) { 377 if ((loc.GetPolicy() == Location::kRequiresRegister) 378 || (loc.GetPolicy() == Location::kRequiresFpuRegister)) { 379 loc = AllocateFreeRegister(input->GetType()); 380 } else { 381 DCHECK_EQ(loc.GetPolicy(), Location::kAny); 382 HLoadLocal* load = input->AsLoadLocal(); 383 if (load != nullptr) { 384 loc = GetStackLocation(load); 385 } else { 386 loc = AllocateFreeRegister(input->GetType()); 387 } 388 } 389 locations->SetInAt(i, loc); 390 } 391 } 392 393 // Allocate all unallocated temp locations. 394 for (size_t i = 0, e = locations->GetTempCount(); i < e; ++i) { 395 Location loc = locations->GetTemp(i); 396 if (loc.IsUnallocated()) { 397 switch (loc.GetPolicy()) { 398 case Location::kRequiresRegister: 399 // Allocate a core register (large enough to fit a 32-bit integer). 400 loc = AllocateFreeRegister(Primitive::kPrimInt); 401 break; 402 403 case Location::kRequiresFpuRegister: 404 // Allocate a core register (large enough to fit a 64-bit double). 405 loc = AllocateFreeRegister(Primitive::kPrimDouble); 406 break; 407 408 default: 409 LOG(FATAL) << "Unexpected policy for temporary location " 410 << loc.GetPolicy(); 411 } 412 locations->SetTempAt(i, loc); 413 } 414 } 415 if (result_location.IsUnallocated()) { 416 switch (result_location.GetPolicy()) { 417 case Location::kAny: 418 case Location::kRequiresRegister: 419 case Location::kRequiresFpuRegister: 420 result_location = AllocateFreeRegister(instruction->GetType()); 421 break; 422 case Location::kSameAsFirstInput: 423 result_location = locations->InAt(0); 424 break; 425 } 426 locations->UpdateOut(result_location); 427 } 428} 429 430void CodeGenerator::InitLocationsBaseline(HInstruction* instruction) { 431 AllocateLocations(instruction); 432 if (instruction->GetLocations() == nullptr) { 433 if (instruction->IsTemporary()) { 434 HInstruction* previous = instruction->GetPrevious(); 435 Location temp_location = GetTemporaryLocation(instruction->AsTemporary()); 436 Move(previous, temp_location, instruction); 437 } 438 return; 439 } 440 AllocateRegistersLocally(instruction); 441 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) { 442 Location location = instruction->GetLocations()->InAt(i); 443 HInstruction* input = instruction->InputAt(i); 444 if (location.IsValid()) { 445 // Move the input to the desired location. 446 if (input->GetNext()->IsTemporary()) { 447 // If the input was stored in a temporary, use that temporary to 448 // perform the move. 449 Move(input->GetNext(), location, instruction); 450 } else { 451 Move(input, location, instruction); 452 } 453 } 454 } 455} 456 457void CodeGenerator::AllocateLocations(HInstruction* instruction) { 458 instruction->Accept(GetLocationBuilder()); 459 DCHECK(CheckTypeConsistency(instruction)); 460 LocationSummary* locations = instruction->GetLocations(); 461 if (!instruction->IsSuspendCheckEntry()) { 462 if (locations != nullptr && locations->CanCall()) { 463 MarkNotLeaf(); 464 } 465 if (instruction->NeedsCurrentMethod()) { 466 SetRequiresCurrentMethod(); 467 } 468 } 469} 470 471CodeGenerator* CodeGenerator::Create(HGraph* graph, 472 InstructionSet instruction_set, 473 const InstructionSetFeatures& isa_features, 474 const CompilerOptions& compiler_options) { 475 switch (instruction_set) { 476 case kArm: 477 case kThumb2: { 478 return new arm::CodeGeneratorARM(graph, 479 *isa_features.AsArmInstructionSetFeatures(), 480 compiler_options); 481 } 482 case kArm64: { 483 return new arm64::CodeGeneratorARM64(graph, 484 *isa_features.AsArm64InstructionSetFeatures(), 485 compiler_options); 486 } 487 case kMips: 488 return nullptr; 489 case kX86: { 490 return new x86::CodeGeneratorX86(graph, 491 *isa_features.AsX86InstructionSetFeatures(), 492 compiler_options); 493 } 494 case kX86_64: { 495 return new x86_64::CodeGeneratorX86_64(graph, 496 *isa_features.AsX86_64InstructionSetFeatures(), 497 compiler_options); 498 } 499 default: 500 return nullptr; 501 } 502} 503 504void CodeGenerator::BuildNativeGCMap( 505 std::vector<uint8_t>* data, const DexCompilationUnit& dex_compilation_unit) const { 506 const std::vector<uint8_t>& gc_map_raw = 507 dex_compilation_unit.GetVerifiedMethod()->GetDexGcMap(); 508 verifier::DexPcToReferenceMap dex_gc_map(&(gc_map_raw)[0]); 509 510 uint32_t max_native_offset = stack_map_stream_.ComputeMaxNativePcOffset(); 511 512 size_t num_stack_maps = stack_map_stream_.GetNumberOfStackMaps(); 513 GcMapBuilder builder(data, num_stack_maps, max_native_offset, dex_gc_map.RegWidth()); 514 for (size_t i = 0; i != num_stack_maps; ++i) { 515 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i); 516 uint32_t native_offset = stack_map_entry.native_pc_offset; 517 uint32_t dex_pc = stack_map_entry.dex_pc; 518 const uint8_t* references = dex_gc_map.FindBitMap(dex_pc, false); 519 CHECK(references != nullptr) << "Missing ref for dex pc 0x" << std::hex << dex_pc; 520 builder.AddEntry(native_offset, references); 521 } 522} 523 524void CodeGenerator::BuildSourceMap(DefaultSrcMap* src_map) const { 525 for (size_t i = 0, num = stack_map_stream_.GetNumberOfStackMaps(); i != num; ++i) { 526 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i); 527 uint32_t pc2dex_offset = stack_map_entry.native_pc_offset; 528 int32_t pc2dex_dalvik_offset = stack_map_entry.dex_pc; 529 src_map->push_back(SrcMapElem({pc2dex_offset, pc2dex_dalvik_offset})); 530 } 531} 532 533void CodeGenerator::BuildMappingTable(std::vector<uint8_t>* data) const { 534 uint32_t pc2dex_data_size = 0u; 535 uint32_t pc2dex_entries = stack_map_stream_.GetNumberOfStackMaps(); 536 uint32_t pc2dex_offset = 0u; 537 int32_t pc2dex_dalvik_offset = 0; 538 uint32_t dex2pc_data_size = 0u; 539 uint32_t dex2pc_entries = 0u; 540 uint32_t dex2pc_offset = 0u; 541 int32_t dex2pc_dalvik_offset = 0; 542 543 for (size_t i = 0; i < pc2dex_entries; i++) { 544 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i); 545 pc2dex_data_size += UnsignedLeb128Size(stack_map_entry.native_pc_offset - pc2dex_offset); 546 pc2dex_data_size += SignedLeb128Size(stack_map_entry.dex_pc - pc2dex_dalvik_offset); 547 pc2dex_offset = stack_map_entry.native_pc_offset; 548 pc2dex_dalvik_offset = stack_map_entry.dex_pc; 549 } 550 551 // Walk over the blocks and find which ones correspond to catch block entries. 552 for (size_t i = 0; i < graph_->GetBlocks().Size(); ++i) { 553 HBasicBlock* block = graph_->GetBlocks().Get(i); 554 if (block->IsCatchBlock()) { 555 intptr_t native_pc = GetAddressOf(block); 556 ++dex2pc_entries; 557 dex2pc_data_size += UnsignedLeb128Size(native_pc - dex2pc_offset); 558 dex2pc_data_size += SignedLeb128Size(block->GetDexPc() - dex2pc_dalvik_offset); 559 dex2pc_offset = native_pc; 560 dex2pc_dalvik_offset = block->GetDexPc(); 561 } 562 } 563 564 uint32_t total_entries = pc2dex_entries + dex2pc_entries; 565 uint32_t hdr_data_size = UnsignedLeb128Size(total_entries) + UnsignedLeb128Size(pc2dex_entries); 566 uint32_t data_size = hdr_data_size + pc2dex_data_size + dex2pc_data_size; 567 data->resize(data_size); 568 569 uint8_t* data_ptr = &(*data)[0]; 570 uint8_t* write_pos = data_ptr; 571 572 write_pos = EncodeUnsignedLeb128(write_pos, total_entries); 573 write_pos = EncodeUnsignedLeb128(write_pos, pc2dex_entries); 574 DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size); 575 uint8_t* write_pos2 = write_pos + pc2dex_data_size; 576 577 pc2dex_offset = 0u; 578 pc2dex_dalvik_offset = 0u; 579 dex2pc_offset = 0u; 580 dex2pc_dalvik_offset = 0u; 581 582 for (size_t i = 0; i < pc2dex_entries; i++) { 583 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i); 584 DCHECK(pc2dex_offset <= stack_map_entry.native_pc_offset); 585 write_pos = EncodeUnsignedLeb128(write_pos, stack_map_entry.native_pc_offset - pc2dex_offset); 586 write_pos = EncodeSignedLeb128(write_pos, stack_map_entry.dex_pc - pc2dex_dalvik_offset); 587 pc2dex_offset = stack_map_entry.native_pc_offset; 588 pc2dex_dalvik_offset = stack_map_entry.dex_pc; 589 } 590 591 for (size_t i = 0; i < graph_->GetBlocks().Size(); ++i) { 592 HBasicBlock* block = graph_->GetBlocks().Get(i); 593 if (block->IsCatchBlock()) { 594 intptr_t native_pc = GetAddressOf(block); 595 write_pos2 = EncodeUnsignedLeb128(write_pos2, native_pc - dex2pc_offset); 596 write_pos2 = EncodeSignedLeb128(write_pos2, block->GetDexPc() - dex2pc_dalvik_offset); 597 dex2pc_offset = native_pc; 598 dex2pc_dalvik_offset = block->GetDexPc(); 599 } 600 } 601 602 603 DCHECK_EQ(static_cast<size_t>(write_pos - data_ptr), hdr_data_size + pc2dex_data_size); 604 DCHECK_EQ(static_cast<size_t>(write_pos2 - data_ptr), data_size); 605 606 if (kIsDebugBuild) { 607 // Verify the encoded table holds the expected data. 608 MappingTable table(data_ptr); 609 CHECK_EQ(table.TotalSize(), total_entries); 610 CHECK_EQ(table.PcToDexSize(), pc2dex_entries); 611 auto it = table.PcToDexBegin(); 612 auto it2 = table.DexToPcBegin(); 613 for (size_t i = 0; i < pc2dex_entries; i++) { 614 const StackMapStream::StackMapEntry& stack_map_entry = stack_map_stream_.GetStackMap(i); 615 CHECK_EQ(stack_map_entry.native_pc_offset, it.NativePcOffset()); 616 CHECK_EQ(stack_map_entry.dex_pc, it.DexPc()); 617 ++it; 618 } 619 for (size_t i = 0; i < graph_->GetBlocks().Size(); ++i) { 620 HBasicBlock* block = graph_->GetBlocks().Get(i); 621 if (block->IsCatchBlock()) { 622 CHECK_EQ(GetAddressOf(block), it2.NativePcOffset()); 623 CHECK_EQ(block->GetDexPc(), it2.DexPc()); 624 ++it2; 625 } 626 } 627 CHECK(it == table.PcToDexEnd()); 628 CHECK(it2 == table.DexToPcEnd()); 629 } 630} 631 632void CodeGenerator::BuildVMapTable(std::vector<uint8_t>* data) const { 633 Leb128EncodingVector vmap_encoder; 634 // We currently don't use callee-saved registers. 635 size_t size = 0 + 1 /* marker */ + 0; 636 vmap_encoder.Reserve(size + 1u); // All values are likely to be one byte in ULEB128 (<128). 637 vmap_encoder.PushBackUnsigned(size); 638 vmap_encoder.PushBackUnsigned(VmapTable::kAdjustedFpMarker); 639 640 *data = vmap_encoder.GetData(); 641} 642 643void CodeGenerator::BuildStackMaps(std::vector<uint8_t>* data) { 644 uint32_t size = stack_map_stream_.PrepareForFillIn(); 645 data->resize(size); 646 MemoryRegion region(data->data(), size); 647 stack_map_stream_.FillIn(region); 648} 649 650void CodeGenerator::RecordPcInfo(HInstruction* instruction, 651 uint32_t dex_pc, 652 SlowPathCode* slow_path) { 653 if (instruction != nullptr) { 654 // The code generated for some type conversions may call the 655 // runtime, thus normally requiring a subsequent call to this 656 // method. However, the method verifier does not produce PC 657 // information for certain instructions, which are considered "atomic" 658 // (they cannot join a GC). 659 // Therefore we do not currently record PC information for such 660 // instructions. As this may change later, we added this special 661 // case so that code generators may nevertheless call 662 // CodeGenerator::RecordPcInfo without triggering an error in 663 // CodeGenerator::BuildNativeGCMap ("Missing ref for dex pc 0x") 664 // thereafter. 665 if (instruction->IsTypeConversion()) { 666 return; 667 } 668 if (instruction->IsRem()) { 669 Primitive::Type type = instruction->AsRem()->GetResultType(); 670 if ((type == Primitive::kPrimFloat) || (type == Primitive::kPrimDouble)) { 671 return; 672 } 673 } 674 } 675 676 uint32_t outer_dex_pc = dex_pc; 677 uint32_t outer_environment_size = 0; 678 uint32_t inlining_depth = 0; 679 if (instruction != nullptr) { 680 for (HEnvironment* environment = instruction->GetEnvironment(); 681 environment != nullptr; 682 environment = environment->GetParent()) { 683 outer_dex_pc = environment->GetDexPc(); 684 outer_environment_size = environment->Size(); 685 if (environment != instruction->GetEnvironment()) { 686 inlining_depth++; 687 } 688 } 689 } 690 691 // Collect PC infos for the mapping table. 692 uint32_t native_pc = GetAssembler()->CodeSize(); 693 694 if (instruction == nullptr) { 695 // For stack overflow checks. 696 stack_map_stream_.BeginStackMapEntry(outer_dex_pc, native_pc, 0, 0, 0, 0); 697 stack_map_stream_.EndStackMapEntry(); 698 return; 699 } 700 LocationSummary* locations = instruction->GetLocations(); 701 702 uint32_t register_mask = locations->GetRegisterMask(); 703 if (locations->OnlyCallsOnSlowPath()) { 704 // In case of slow path, we currently set the location of caller-save registers 705 // to register (instead of their stack location when pushed before the slow-path 706 // call). Therefore register_mask contains both callee-save and caller-save 707 // registers that hold objects. We must remove the caller-save from the mask, since 708 // they will be overwritten by the callee. 709 register_mask &= core_callee_save_mask_; 710 } 711 // The register mask must be a subset of callee-save registers. 712 DCHECK_EQ(register_mask & core_callee_save_mask_, register_mask); 713 stack_map_stream_.BeginStackMapEntry(outer_dex_pc, 714 native_pc, 715 register_mask, 716 locations->GetStackMask(), 717 outer_environment_size, 718 inlining_depth); 719 720 EmitEnvironment(instruction->GetEnvironment(), slow_path); 721 stack_map_stream_.EndStackMapEntry(); 722} 723 724void CodeGenerator::EmitEnvironment(HEnvironment* environment, SlowPathCode* slow_path) { 725 if (environment == nullptr) return; 726 727 if (environment->GetParent() != nullptr) { 728 // We emit the parent environment first. 729 EmitEnvironment(environment->GetParent(), slow_path); 730 stack_map_stream_.BeginInlineInfoEntry(environment->GetMethodIdx(), 731 environment->GetDexPc(), 732 environment->GetInvokeType(), 733 environment->Size()); 734 } 735 736 // Walk over the environment, and record the location of dex registers. 737 for (size_t i = 0, environment_size = environment->Size(); i < environment_size; ++i) { 738 HInstruction* current = environment->GetInstructionAt(i); 739 if (current == nullptr) { 740 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0); 741 continue; 742 } 743 744 Location location = environment->GetLocationAt(i); 745 switch (location.GetKind()) { 746 case Location::kConstant: { 747 DCHECK_EQ(current, location.GetConstant()); 748 if (current->IsLongConstant()) { 749 int64_t value = current->AsLongConstant()->GetValue(); 750 stack_map_stream_.AddDexRegisterEntry( 751 DexRegisterLocation::Kind::kConstant, Low32Bits(value)); 752 stack_map_stream_.AddDexRegisterEntry( 753 DexRegisterLocation::Kind::kConstant, High32Bits(value)); 754 ++i; 755 DCHECK_LT(i, environment_size); 756 } else if (current->IsDoubleConstant()) { 757 int64_t value = bit_cast<int64_t, double>(current->AsDoubleConstant()->GetValue()); 758 stack_map_stream_.AddDexRegisterEntry( 759 DexRegisterLocation::Kind::kConstant, Low32Bits(value)); 760 stack_map_stream_.AddDexRegisterEntry( 761 DexRegisterLocation::Kind::kConstant, High32Bits(value)); 762 ++i; 763 DCHECK_LT(i, environment_size); 764 } else if (current->IsIntConstant()) { 765 int32_t value = current->AsIntConstant()->GetValue(); 766 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kConstant, value); 767 } else if (current->IsNullConstant()) { 768 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kConstant, 0); 769 } else { 770 DCHECK(current->IsFloatConstant()) << current->DebugName(); 771 int32_t value = bit_cast<int32_t, float>(current->AsFloatConstant()->GetValue()); 772 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kConstant, value); 773 } 774 break; 775 } 776 777 case Location::kStackSlot: { 778 stack_map_stream_.AddDexRegisterEntry( 779 DexRegisterLocation::Kind::kInStack, location.GetStackIndex()); 780 break; 781 } 782 783 case Location::kDoubleStackSlot: { 784 stack_map_stream_.AddDexRegisterEntry( 785 DexRegisterLocation::Kind::kInStack, location.GetStackIndex()); 786 stack_map_stream_.AddDexRegisterEntry( 787 DexRegisterLocation::Kind::kInStack, location.GetHighStackIndex(kVRegSize)); 788 ++i; 789 DCHECK_LT(i, environment_size); 790 break; 791 } 792 793 case Location::kRegister : { 794 int id = location.reg(); 795 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(id)) { 796 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(id); 797 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset); 798 if (current->GetType() == Primitive::kPrimLong) { 799 stack_map_stream_.AddDexRegisterEntry( 800 DexRegisterLocation::Kind::kInStack, offset + kVRegSize); 801 ++i; 802 DCHECK_LT(i, environment_size); 803 } 804 } else { 805 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, id); 806 if (current->GetType() == Primitive::kPrimLong) { 807 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, id); 808 ++i; 809 DCHECK_LT(i, environment_size); 810 } 811 } 812 break; 813 } 814 815 case Location::kFpuRegister : { 816 int id = location.reg(); 817 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(id)) { 818 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(id); 819 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset); 820 if (current->GetType() == Primitive::kPrimDouble) { 821 stack_map_stream_.AddDexRegisterEntry( 822 DexRegisterLocation::Kind::kInStack, offset + kVRegSize); 823 ++i; 824 DCHECK_LT(i, environment_size); 825 } 826 } else { 827 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, id); 828 if (current->GetType() == Primitive::kPrimDouble) { 829 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, id); 830 ++i; 831 DCHECK_LT(i, environment_size); 832 } 833 } 834 break; 835 } 836 837 case Location::kFpuRegisterPair : { 838 int low = location.low(); 839 int high = location.high(); 840 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(low)) { 841 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(low); 842 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset); 843 } else { 844 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, low); 845 } 846 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(high)) { 847 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(high); 848 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset); 849 ++i; 850 } else { 851 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInFpuRegister, high); 852 ++i; 853 } 854 DCHECK_LT(i, environment_size); 855 break; 856 } 857 858 case Location::kRegisterPair : { 859 int low = location.low(); 860 int high = location.high(); 861 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(low)) { 862 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(low); 863 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset); 864 } else { 865 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, low); 866 } 867 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(high)) { 868 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(high); 869 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInStack, offset); 870 } else { 871 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kInRegister, high); 872 } 873 ++i; 874 DCHECK_LT(i, environment_size); 875 break; 876 } 877 878 case Location::kInvalid: { 879 stack_map_stream_.AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0); 880 break; 881 } 882 883 default: 884 LOG(FATAL) << "Unexpected kind " << location.GetKind(); 885 } 886 } 887 888 if (environment->GetParent() != nullptr) { 889 stack_map_stream_.EndInlineInfoEntry(); 890 } 891} 892 893bool CodeGenerator::CanMoveNullCheckToUser(HNullCheck* null_check) { 894 HInstruction* first_next_not_move = null_check->GetNextDisregardingMoves(); 895 896 return (first_next_not_move != nullptr) 897 && first_next_not_move->CanDoImplicitNullCheckOn(null_check->InputAt(0)); 898} 899 900void CodeGenerator::MaybeRecordImplicitNullCheck(HInstruction* instr) { 901 // If we are from a static path don't record the pc as we can't throw NPE. 902 // NB: having the checks here makes the code much less verbose in the arch 903 // specific code generators. 904 if (instr->IsStaticFieldSet() || instr->IsStaticFieldGet()) { 905 return; 906 } 907 908 if (!compiler_options_.GetImplicitNullChecks()) { 909 return; 910 } 911 912 if (!instr->CanDoImplicitNullCheckOn(instr->InputAt(0))) { 913 return; 914 } 915 916 // Find the first previous instruction which is not a move. 917 HInstruction* first_prev_not_move = instr->GetPreviousDisregardingMoves(); 918 919 // If the instruction is a null check it means that `instr` is the first user 920 // and needs to record the pc. 921 if (first_prev_not_move != nullptr && first_prev_not_move->IsNullCheck()) { 922 HNullCheck* null_check = first_prev_not_move->AsNullCheck(); 923 // TODO: The parallel moves modify the environment. Their changes need to be reverted 924 // otherwise the stack maps at the throw point will not be correct. 925 RecordPcInfo(null_check, null_check->GetDexPc()); 926 } 927} 928 929void CodeGenerator::ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck* suspend_check) const { 930 LocationSummary* locations = suspend_check->GetLocations(); 931 HBasicBlock* block = suspend_check->GetBlock(); 932 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == suspend_check); 933 DCHECK(block->IsLoopHeader()); 934 935 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) { 936 HInstruction* current = it.Current(); 937 LiveInterval* interval = current->GetLiveInterval(); 938 // We only need to clear bits of loop phis containing objects and allocated in register. 939 // Loop phis allocated on stack already have the object in the stack. 940 if (current->GetType() == Primitive::kPrimNot 941 && interval->HasRegister() 942 && interval->HasSpillSlot()) { 943 locations->ClearStackBit(interval->GetSpillSlot() / kVRegSize); 944 } 945 } 946} 947 948void CodeGenerator::EmitParallelMoves(Location from1, 949 Location to1, 950 Primitive::Type type1, 951 Location from2, 952 Location to2, 953 Primitive::Type type2) { 954 HParallelMove parallel_move(GetGraph()->GetArena()); 955 parallel_move.AddMove(from1, to1, type1, nullptr); 956 parallel_move.AddMove(from2, to2, type2, nullptr); 957 GetMoveResolver()->EmitNativeCode(¶llel_move); 958} 959 960void SlowPathCode::RecordPcInfo(CodeGenerator* codegen, HInstruction* instruction, uint32_t dex_pc) { 961 codegen->RecordPcInfo(instruction, dex_pc, this); 962} 963 964void SlowPathCode::SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) { 965 RegisterSet* register_set = locations->GetLiveRegisters(); 966 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath(); 967 for (size_t i = 0, e = codegen->GetNumberOfCoreRegisters(); i < e; ++i) { 968 if (!codegen->IsCoreCalleeSaveRegister(i)) { 969 if (register_set->ContainsCoreRegister(i)) { 970 // If the register holds an object, update the stack mask. 971 if (locations->RegisterContainsObject(i)) { 972 locations->SetStackBit(stack_offset / kVRegSize); 973 } 974 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize()); 975 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters); 976 saved_core_stack_offsets_[i] = stack_offset; 977 stack_offset += codegen->SaveCoreRegister(stack_offset, i); 978 } 979 } 980 } 981 982 for (size_t i = 0, e = codegen->GetNumberOfFloatingPointRegisters(); i < e; ++i) { 983 if (!codegen->IsFloatingPointCalleeSaveRegister(i)) { 984 if (register_set->ContainsFloatingPointRegister(i)) { 985 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize()); 986 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters); 987 saved_fpu_stack_offsets_[i] = stack_offset; 988 stack_offset += codegen->SaveFloatingPointRegister(stack_offset, i); 989 } 990 } 991 } 992} 993 994void SlowPathCode::RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) { 995 RegisterSet* register_set = locations->GetLiveRegisters(); 996 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath(); 997 for (size_t i = 0, e = codegen->GetNumberOfCoreRegisters(); i < e; ++i) { 998 if (!codegen->IsCoreCalleeSaveRegister(i)) { 999 if (register_set->ContainsCoreRegister(i)) { 1000 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize()); 1001 stack_offset += codegen->RestoreCoreRegister(stack_offset, i); 1002 } 1003 } 1004 } 1005 1006 for (size_t i = 0, e = codegen->GetNumberOfFloatingPointRegisters(); i < e; ++i) { 1007 if (!codegen->IsFloatingPointCalleeSaveRegister(i)) { 1008 if (register_set->ContainsFloatingPointRegister(i)) { 1009 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize()); 1010 stack_offset += codegen->RestoreFloatingPointRegister(stack_offset, i); 1011 } 1012 } 1013 } 1014} 1015 1016} // namespace art 1017