• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_arm64.h"
18 
19 #include "aarch64/assembler-aarch64.h"
20 #include "aarch64/registers-aarch64.h"
21 #include "arch/arm64/asm_support_arm64.h"
22 #include "arch/arm64/instruction_set_features_arm64.h"
23 #include "arch/arm64/jni_frame_arm64.h"
24 #include "art_method-inl.h"
25 #include "base/bit_utils.h"
26 #include "base/bit_utils_iterator.h"
27 #include "class_root-inl.h"
28 #include "class_table.h"
29 #include "code_generator_utils.h"
30 #include "compiled_method.h"
31 #include "entrypoints/quick/quick_entrypoints.h"
32 #include "entrypoints/quick/quick_entrypoints_enum.h"
33 #include "gc/accounting/card_table.h"
34 #include "gc/space/image_space.h"
35 #include "heap_poisoning.h"
36 #include "interpreter/mterp/nterp.h"
37 #include "intrinsics.h"
38 #include "intrinsics_arm64.h"
39 #include "intrinsics_utils.h"
40 #include "linker/linker_patch.h"
41 #include "lock_word.h"
42 #include "mirror/array-inl.h"
43 #include "mirror/class-inl.h"
44 #include "mirror/var_handle.h"
45 #include "offsets.h"
46 #include "optimizing/common_arm64.h"
47 #include "thread.h"
48 #include "utils/arm64/assembler_arm64.h"
49 #include "utils/assembler.h"
50 #include "utils/stack_checks.h"
51 
52 using namespace vixl::aarch64;  // NOLINT(build/namespaces)
53 using vixl::ExactAssemblyScope;
54 using vixl::CodeBufferCheckScope;
55 using vixl::EmissionCheckScope;
56 
57 #ifdef __
58 #error "ARM64 Codegen VIXL macro-assembler macro already defined."
59 #endif
60 
61 namespace art {
62 
63 template<class MirrorType>
64 class GcRoot;
65 
66 namespace arm64 {
67 
68 using helpers::ARM64EncodableConstantOrRegister;
69 using helpers::ArtVixlRegCodeCoherentForRegSet;
70 using helpers::CPURegisterFrom;
71 using helpers::DRegisterFrom;
72 using helpers::FPRegisterFrom;
73 using helpers::HeapOperand;
74 using helpers::HeapOperandFrom;
75 using helpers::InputCPURegisterOrZeroRegAt;
76 using helpers::InputFPRegisterAt;
77 using helpers::InputOperandAt;
78 using helpers::InputRegisterAt;
79 using helpers::Int64FromLocation;
80 using helpers::IsConstantZeroBitPattern;
81 using helpers::LocationFrom;
82 using helpers::OperandFromMemOperand;
83 using helpers::OutputCPURegister;
84 using helpers::OutputFPRegister;
85 using helpers::OutputRegister;
86 using helpers::RegisterFrom;
87 using helpers::StackOperandFrom;
88 using helpers::VIXLRegCodeFromART;
89 using helpers::WRegisterFrom;
90 using helpers::XRegisterFrom;
91 
92 // The compare/jump sequence will generate about (1.5 * num_entries + 3) instructions. While jump
93 // table version generates 7 instructions and num_entries literals. Compare/jump sequence will
94 // generates less code/data with a small num_entries.
95 static constexpr uint32_t kPackedSwitchCompareJumpThreshold = 7;
96 
97 // Reference load (except object array loads) is using LDR Wt, [Xn, #offset] which can handle
98 // offset < 16KiB. For offsets >= 16KiB, the load shall be emitted as two or more instructions.
99 // For the Baker read barrier implementation using link-time generated thunks we need to split
100 // the offset explicitly.
101 constexpr uint32_t kReferenceLoadMinFarOffset = 16 * KB;
102 
ARM64Condition(IfCondition cond)103 inline Condition ARM64Condition(IfCondition cond) {
104   switch (cond) {
105     case kCondEQ: return eq;
106     case kCondNE: return ne;
107     case kCondLT: return lt;
108     case kCondLE: return le;
109     case kCondGT: return gt;
110     case kCondGE: return ge;
111     case kCondB:  return lo;
112     case kCondBE: return ls;
113     case kCondA:  return hi;
114     case kCondAE: return hs;
115   }
116   LOG(FATAL) << "Unreachable";
117   UNREACHABLE();
118 }
119 
ARM64FPCondition(IfCondition cond,bool gt_bias)120 inline Condition ARM64FPCondition(IfCondition cond, bool gt_bias) {
121   // The ARM64 condition codes can express all the necessary branches, see the
122   // "Meaning (floating-point)" column in the table C1-1 in the ARMv8 reference manual.
123   // There is no dex instruction or HIR that would need the missing conditions
124   // "equal or unordered" or "not equal".
125   switch (cond) {
126     case kCondEQ: return eq;
127     case kCondNE: return ne /* unordered */;
128     case kCondLT: return gt_bias ? cc : lt /* unordered */;
129     case kCondLE: return gt_bias ? ls : le /* unordered */;
130     case kCondGT: return gt_bias ? hi /* unordered */ : gt;
131     case kCondGE: return gt_bias ? cs /* unordered */ : ge;
132     default:
133       LOG(FATAL) << "UNREACHABLE";
134       UNREACHABLE();
135   }
136 }
137 
ARM64ReturnLocation(DataType::Type return_type)138 Location ARM64ReturnLocation(DataType::Type return_type) {
139   // Note that in practice, `LocationFrom(x0)` and `LocationFrom(w0)` create the
140   // same Location object, and so do `LocationFrom(d0)` and `LocationFrom(s0)`,
141   // but we use the exact registers for clarity.
142   if (return_type == DataType::Type::kFloat32) {
143     return LocationFrom(s0);
144   } else if (return_type == DataType::Type::kFloat64) {
145     return LocationFrom(d0);
146   } else if (return_type == DataType::Type::kInt64) {
147     return LocationFrom(x0);
148   } else if (return_type == DataType::Type::kVoid) {
149     return Location::NoLocation();
150   } else {
151     return LocationFrom(w0);
152   }
153 }
154 
GetReturnLocation(DataType::Type return_type)155 Location InvokeRuntimeCallingConvention::GetReturnLocation(DataType::Type return_type) {
156   return ARM64ReturnLocation(return_type);
157 }
158 
OneRegInReferenceOutSaveEverythingCallerSaves()159 static RegisterSet OneRegInReferenceOutSaveEverythingCallerSaves() {
160   InvokeRuntimeCallingConvention calling_convention;
161   RegisterSet caller_saves = RegisterSet::Empty();
162   caller_saves.Add(Location::RegisterLocation(calling_convention.GetRegisterAt(0).GetCode()));
163   DCHECK_EQ(calling_convention.GetRegisterAt(0).GetCode(),
164             RegisterFrom(calling_convention.GetReturnLocation(DataType::Type::kReference),
165                          DataType::Type::kReference).GetCode());
166   return caller_saves;
167 }
168 
169 // NOLINT on __ macro to suppress wrong warning/fix (misc-macro-parentheses) from clang-tidy.
170 #define __ down_cast<CodeGeneratorARM64*>(codegen)->GetVIXLAssembler()->  // NOLINT
171 #define QUICK_ENTRY_POINT(x) QUICK_ENTRYPOINT_OFFSET(kArm64PointerSize, x).Int32Value()
172 
SaveLiveRegisters(CodeGenerator * codegen,LocationSummary * locations)173 void SlowPathCodeARM64::SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
174   size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
175   const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
176   for (uint32_t i : LowToHighBits(core_spills)) {
177     // If the register holds an object, update the stack mask.
178     if (locations->RegisterContainsObject(i)) {
179       locations->SetStackBit(stack_offset / kVRegSize);
180     }
181     DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
182     DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
183     saved_core_stack_offsets_[i] = stack_offset;
184     stack_offset += kXRegSizeInBytes;
185   }
186 
187   const size_t fp_reg_size = codegen->GetSlowPathFPWidth();
188   const uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
189   for (uint32_t i : LowToHighBits(fp_spills)) {
190     DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
191     DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
192     saved_fpu_stack_offsets_[i] = stack_offset;
193     stack_offset += fp_reg_size;
194   }
195 
196   InstructionCodeGeneratorARM64* visitor =
197       down_cast<CodeGeneratorARM64*>(codegen)->GetInstructionCodeGeneratorArm64();
198   visitor->SaveLiveRegistersHelper(locations, codegen->GetFirstRegisterSlotInSlowPath());
199 }
200 
RestoreLiveRegisters(CodeGenerator * codegen,LocationSummary * locations)201 void SlowPathCodeARM64::RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
202   InstructionCodeGeneratorARM64* visitor =
203       down_cast<CodeGeneratorARM64*>(codegen)->GetInstructionCodeGeneratorArm64();
204   visitor->RestoreLiveRegistersHelper(locations, codegen->GetFirstRegisterSlotInSlowPath());
205 }
206 
207 class BoundsCheckSlowPathARM64 : public SlowPathCodeARM64 {
208  public:
BoundsCheckSlowPathARM64(HBoundsCheck * instruction)209   explicit BoundsCheckSlowPathARM64(HBoundsCheck* instruction) : SlowPathCodeARM64(instruction) {}
210 
EmitNativeCode(CodeGenerator * codegen)211   void EmitNativeCode(CodeGenerator* codegen) override {
212     LocationSummary* locations = instruction_->GetLocations();
213     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
214 
215     __ Bind(GetEntryLabel());
216     if (instruction_->CanThrowIntoCatchBlock()) {
217       // Live registers will be restored in the catch block if caught.
218       SaveLiveRegisters(codegen, instruction_->GetLocations());
219     }
220     // We're moving two locations to locations that could overlap, so we need a parallel
221     // move resolver.
222     InvokeRuntimeCallingConvention calling_convention;
223     codegen->EmitParallelMoves(locations->InAt(0),
224                                LocationFrom(calling_convention.GetRegisterAt(0)),
225                                DataType::Type::kInt32,
226                                locations->InAt(1),
227                                LocationFrom(calling_convention.GetRegisterAt(1)),
228                                DataType::Type::kInt32);
229     QuickEntrypointEnum entrypoint = instruction_->AsBoundsCheck()->IsStringCharAt()
230         ? kQuickThrowStringBounds
231         : kQuickThrowArrayBounds;
232     arm64_codegen->InvokeRuntime(entrypoint, instruction_, instruction_->GetDexPc(), this);
233     CheckEntrypointTypes<kQuickThrowStringBounds, void, int32_t, int32_t>();
234     CheckEntrypointTypes<kQuickThrowArrayBounds, void, int32_t, int32_t>();
235   }
236 
IsFatal() const237   bool IsFatal() const override { return true; }
238 
GetDescription() const239   const char* GetDescription() const override { return "BoundsCheckSlowPathARM64"; }
240 
241  private:
242   DISALLOW_COPY_AND_ASSIGN(BoundsCheckSlowPathARM64);
243 };
244 
245 class DivZeroCheckSlowPathARM64 : public SlowPathCodeARM64 {
246  public:
DivZeroCheckSlowPathARM64(HDivZeroCheck * instruction)247   explicit DivZeroCheckSlowPathARM64(HDivZeroCheck* instruction) : SlowPathCodeARM64(instruction) {}
248 
EmitNativeCode(CodeGenerator * codegen)249   void EmitNativeCode(CodeGenerator* codegen) override {
250     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
251     __ Bind(GetEntryLabel());
252     arm64_codegen->InvokeRuntime(kQuickThrowDivZero, instruction_, instruction_->GetDexPc(), this);
253     CheckEntrypointTypes<kQuickThrowDivZero, void, void>();
254   }
255 
IsFatal() const256   bool IsFatal() const override { return true; }
257 
GetDescription() const258   const char* GetDescription() const override { return "DivZeroCheckSlowPathARM64"; }
259 
260  private:
261   DISALLOW_COPY_AND_ASSIGN(DivZeroCheckSlowPathARM64);
262 };
263 
264 class LoadClassSlowPathARM64 : public SlowPathCodeARM64 {
265  public:
LoadClassSlowPathARM64(HLoadClass * cls,HInstruction * at)266   LoadClassSlowPathARM64(HLoadClass* cls, HInstruction* at)
267       : SlowPathCodeARM64(at), cls_(cls) {
268     DCHECK(at->IsLoadClass() || at->IsClinitCheck());
269     DCHECK_EQ(instruction_->IsLoadClass(), cls_ == instruction_);
270   }
271 
EmitNativeCode(CodeGenerator * codegen)272   void EmitNativeCode(CodeGenerator* codegen) override {
273     LocationSummary* locations = instruction_->GetLocations();
274     Location out = locations->Out();
275     const uint32_t dex_pc = instruction_->GetDexPc();
276     bool must_resolve_type = instruction_->IsLoadClass() && cls_->MustResolveTypeOnSlowPath();
277     bool must_do_clinit = instruction_->IsClinitCheck() || cls_->MustGenerateClinitCheck();
278 
279     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
280     __ Bind(GetEntryLabel());
281     SaveLiveRegisters(codegen, locations);
282 
283     InvokeRuntimeCallingConvention calling_convention;
284     if (must_resolve_type) {
285       DCHECK(IsSameDexFile(cls_->GetDexFile(), arm64_codegen->GetGraph()->GetDexFile()) ||
286              arm64_codegen->GetCompilerOptions().WithinOatFile(&cls_->GetDexFile()) ||
287              ContainsElement(Runtime::Current()->GetClassLinker()->GetBootClassPath(),
288                              &cls_->GetDexFile()));
289       dex::TypeIndex type_index = cls_->GetTypeIndex();
290       __ Mov(calling_convention.GetRegisterAt(0).W(), type_index.index_);
291       if (cls_->NeedsAccessCheck()) {
292         CheckEntrypointTypes<kQuickResolveTypeAndVerifyAccess, void*, uint32_t>();
293         arm64_codegen->InvokeRuntime(kQuickResolveTypeAndVerifyAccess, instruction_, dex_pc, this);
294       } else {
295         CheckEntrypointTypes<kQuickResolveType, void*, uint32_t>();
296         arm64_codegen->InvokeRuntime(kQuickResolveType, instruction_, dex_pc, this);
297       }
298       // If we also must_do_clinit, the resolved type is now in the correct register.
299     } else {
300       DCHECK(must_do_clinit);
301       Location source = instruction_->IsLoadClass() ? out : locations->InAt(0);
302       arm64_codegen->MoveLocation(LocationFrom(calling_convention.GetRegisterAt(0)),
303                                   source,
304                                   cls_->GetType());
305     }
306     if (must_do_clinit) {
307       arm64_codegen->InvokeRuntime(kQuickInitializeStaticStorage, instruction_, dex_pc, this);
308       CheckEntrypointTypes<kQuickInitializeStaticStorage, void*, mirror::Class*>();
309     }
310 
311     // Move the class to the desired location.
312     if (out.IsValid()) {
313       DCHECK(out.IsRegister() && !locations->GetLiveRegisters()->ContainsCoreRegister(out.reg()));
314       DataType::Type type = instruction_->GetType();
315       arm64_codegen->MoveLocation(out, calling_convention.GetReturnLocation(type), type);
316     }
317     RestoreLiveRegisters(codegen, locations);
318     __ B(GetExitLabel());
319   }
320 
GetDescription() const321   const char* GetDescription() const override { return "LoadClassSlowPathARM64"; }
322 
323  private:
324   // The class this slow path will load.
325   HLoadClass* const cls_;
326 
327   DISALLOW_COPY_AND_ASSIGN(LoadClassSlowPathARM64);
328 };
329 
330 class LoadStringSlowPathARM64 : public SlowPathCodeARM64 {
331  public:
LoadStringSlowPathARM64(HLoadString * instruction)332   explicit LoadStringSlowPathARM64(HLoadString* instruction)
333       : SlowPathCodeARM64(instruction) {}
334 
EmitNativeCode(CodeGenerator * codegen)335   void EmitNativeCode(CodeGenerator* codegen) override {
336     LocationSummary* locations = instruction_->GetLocations();
337     DCHECK(!locations->GetLiveRegisters()->ContainsCoreRegister(locations->Out().reg()));
338     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
339 
340     __ Bind(GetEntryLabel());
341     SaveLiveRegisters(codegen, locations);
342 
343     InvokeRuntimeCallingConvention calling_convention;
344     const dex::StringIndex string_index = instruction_->AsLoadString()->GetStringIndex();
345     __ Mov(calling_convention.GetRegisterAt(0).W(), string_index.index_);
346     arm64_codegen->InvokeRuntime(kQuickResolveString, instruction_, instruction_->GetDexPc(), this);
347     CheckEntrypointTypes<kQuickResolveString, void*, uint32_t>();
348     DataType::Type type = instruction_->GetType();
349     arm64_codegen->MoveLocation(locations->Out(), calling_convention.GetReturnLocation(type), type);
350 
351     RestoreLiveRegisters(codegen, locations);
352 
353     __ B(GetExitLabel());
354   }
355 
GetDescription() const356   const char* GetDescription() const override { return "LoadStringSlowPathARM64"; }
357 
358  private:
359   DISALLOW_COPY_AND_ASSIGN(LoadStringSlowPathARM64);
360 };
361 
362 class NullCheckSlowPathARM64 : public SlowPathCodeARM64 {
363  public:
NullCheckSlowPathARM64(HNullCheck * instr)364   explicit NullCheckSlowPathARM64(HNullCheck* instr) : SlowPathCodeARM64(instr) {}
365 
EmitNativeCode(CodeGenerator * codegen)366   void EmitNativeCode(CodeGenerator* codegen) override {
367     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
368     __ Bind(GetEntryLabel());
369     if (instruction_->CanThrowIntoCatchBlock()) {
370       // Live registers will be restored in the catch block if caught.
371       SaveLiveRegisters(codegen, instruction_->GetLocations());
372     }
373     arm64_codegen->InvokeRuntime(kQuickThrowNullPointer,
374                                  instruction_,
375                                  instruction_->GetDexPc(),
376                                  this);
377     CheckEntrypointTypes<kQuickThrowNullPointer, void, void>();
378   }
379 
IsFatal() const380   bool IsFatal() const override { return true; }
381 
GetDescription() const382   const char* GetDescription() const override { return "NullCheckSlowPathARM64"; }
383 
384  private:
385   DISALLOW_COPY_AND_ASSIGN(NullCheckSlowPathARM64);
386 };
387 
388 class SuspendCheckSlowPathARM64 : public SlowPathCodeARM64 {
389  public:
SuspendCheckSlowPathARM64(HSuspendCheck * instruction,HBasicBlock * successor)390   SuspendCheckSlowPathARM64(HSuspendCheck* instruction, HBasicBlock* successor)
391       : SlowPathCodeARM64(instruction), successor_(successor) {}
392 
EmitNativeCode(CodeGenerator * codegen)393   void EmitNativeCode(CodeGenerator* codegen) override {
394     LocationSummary* locations = instruction_->GetLocations();
395     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
396     __ Bind(GetEntryLabel());
397     SaveLiveRegisters(codegen, locations);  // Only saves live vector regs for SIMD.
398     arm64_codegen->InvokeRuntime(kQuickTestSuspend, instruction_, instruction_->GetDexPc(), this);
399     CheckEntrypointTypes<kQuickTestSuspend, void, void>();
400     RestoreLiveRegisters(codegen, locations);  // Only restores live vector regs for SIMD.
401     if (successor_ == nullptr) {
402       __ B(GetReturnLabel());
403     } else {
404       __ B(arm64_codegen->GetLabelOf(successor_));
405     }
406   }
407 
GetReturnLabel()408   vixl::aarch64::Label* GetReturnLabel() {
409     DCHECK(successor_ == nullptr);
410     return &return_label_;
411   }
412 
GetSuccessor() const413   HBasicBlock* GetSuccessor() const {
414     return successor_;
415   }
416 
GetDescription() const417   const char* GetDescription() const override { return "SuspendCheckSlowPathARM64"; }
418 
419  private:
420   // If not null, the block to branch to after the suspend check.
421   HBasicBlock* const successor_;
422 
423   // If `successor_` is null, the label to branch to after the suspend check.
424   vixl::aarch64::Label return_label_;
425 
426   DISALLOW_COPY_AND_ASSIGN(SuspendCheckSlowPathARM64);
427 };
428 
429 class TypeCheckSlowPathARM64 : public SlowPathCodeARM64 {
430  public:
TypeCheckSlowPathARM64(HInstruction * instruction,bool is_fatal)431   TypeCheckSlowPathARM64(HInstruction* instruction, bool is_fatal)
432       : SlowPathCodeARM64(instruction), is_fatal_(is_fatal) {}
433 
EmitNativeCode(CodeGenerator * codegen)434   void EmitNativeCode(CodeGenerator* codegen) override {
435     LocationSummary* locations = instruction_->GetLocations();
436 
437     DCHECK(instruction_->IsCheckCast()
438            || !locations->GetLiveRegisters()->ContainsCoreRegister(locations->Out().reg()));
439     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
440     uint32_t dex_pc = instruction_->GetDexPc();
441 
442     __ Bind(GetEntryLabel());
443 
444     if (!is_fatal_ || instruction_->CanThrowIntoCatchBlock()) {
445       SaveLiveRegisters(codegen, locations);
446     }
447 
448     // We're moving two locations to locations that could overlap, so we need a parallel
449     // move resolver.
450     InvokeRuntimeCallingConvention calling_convention;
451     codegen->EmitParallelMoves(locations->InAt(0),
452                                LocationFrom(calling_convention.GetRegisterAt(0)),
453                                DataType::Type::kReference,
454                                locations->InAt(1),
455                                LocationFrom(calling_convention.GetRegisterAt(1)),
456                                DataType::Type::kReference);
457     if (instruction_->IsInstanceOf()) {
458       arm64_codegen->InvokeRuntime(kQuickInstanceofNonTrivial, instruction_, dex_pc, this);
459       CheckEntrypointTypes<kQuickInstanceofNonTrivial, size_t, mirror::Object*, mirror::Class*>();
460       DataType::Type ret_type = instruction_->GetType();
461       Location ret_loc = calling_convention.GetReturnLocation(ret_type);
462       arm64_codegen->MoveLocation(locations->Out(), ret_loc, ret_type);
463     } else {
464       DCHECK(instruction_->IsCheckCast());
465       arm64_codegen->InvokeRuntime(kQuickCheckInstanceOf, instruction_, dex_pc, this);
466       CheckEntrypointTypes<kQuickCheckInstanceOf, void, mirror::Object*, mirror::Class*>();
467     }
468 
469     if (!is_fatal_) {
470       RestoreLiveRegisters(codegen, locations);
471       __ B(GetExitLabel());
472     }
473   }
474 
GetDescription() const475   const char* GetDescription() const override { return "TypeCheckSlowPathARM64"; }
IsFatal() const476   bool IsFatal() const override { return is_fatal_; }
477 
478  private:
479   const bool is_fatal_;
480 
481   DISALLOW_COPY_AND_ASSIGN(TypeCheckSlowPathARM64);
482 };
483 
484 class DeoptimizationSlowPathARM64 : public SlowPathCodeARM64 {
485  public:
DeoptimizationSlowPathARM64(HDeoptimize * instruction)486   explicit DeoptimizationSlowPathARM64(HDeoptimize* instruction)
487       : SlowPathCodeARM64(instruction) {}
488 
EmitNativeCode(CodeGenerator * codegen)489   void EmitNativeCode(CodeGenerator* codegen) override {
490     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
491     __ Bind(GetEntryLabel());
492     LocationSummary* locations = instruction_->GetLocations();
493     SaveLiveRegisters(codegen, locations);
494     InvokeRuntimeCallingConvention calling_convention;
495     __ Mov(calling_convention.GetRegisterAt(0),
496            static_cast<uint32_t>(instruction_->AsDeoptimize()->GetDeoptimizationKind()));
497     arm64_codegen->InvokeRuntime(kQuickDeoptimize, instruction_, instruction_->GetDexPc(), this);
498     CheckEntrypointTypes<kQuickDeoptimize, void, DeoptimizationKind>();
499   }
500 
GetDescription() const501   const char* GetDescription() const override { return "DeoptimizationSlowPathARM64"; }
502 
503  private:
504   DISALLOW_COPY_AND_ASSIGN(DeoptimizationSlowPathARM64);
505 };
506 
507 class ArraySetSlowPathARM64 : public SlowPathCodeARM64 {
508  public:
ArraySetSlowPathARM64(HInstruction * instruction)509   explicit ArraySetSlowPathARM64(HInstruction* instruction) : SlowPathCodeARM64(instruction) {}
510 
EmitNativeCode(CodeGenerator * codegen)511   void EmitNativeCode(CodeGenerator* codegen) override {
512     LocationSummary* locations = instruction_->GetLocations();
513     __ Bind(GetEntryLabel());
514     SaveLiveRegisters(codegen, locations);
515 
516     InvokeRuntimeCallingConvention calling_convention;
517     HParallelMove parallel_move(codegen->GetGraph()->GetAllocator());
518     parallel_move.AddMove(
519         locations->InAt(0),
520         LocationFrom(calling_convention.GetRegisterAt(0)),
521         DataType::Type::kReference,
522         nullptr);
523     parallel_move.AddMove(
524         locations->InAt(1),
525         LocationFrom(calling_convention.GetRegisterAt(1)),
526         DataType::Type::kInt32,
527         nullptr);
528     parallel_move.AddMove(
529         locations->InAt(2),
530         LocationFrom(calling_convention.GetRegisterAt(2)),
531         DataType::Type::kReference,
532         nullptr);
533     codegen->GetMoveResolver()->EmitNativeCode(&parallel_move);
534 
535     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
536     arm64_codegen->InvokeRuntime(kQuickAputObject, instruction_, instruction_->GetDexPc(), this);
537     CheckEntrypointTypes<kQuickAputObject, void, mirror::Array*, int32_t, mirror::Object*>();
538     RestoreLiveRegisters(codegen, locations);
539     __ B(GetExitLabel());
540   }
541 
GetDescription() const542   const char* GetDescription() const override { return "ArraySetSlowPathARM64"; }
543 
544  private:
545   DISALLOW_COPY_AND_ASSIGN(ArraySetSlowPathARM64);
546 };
547 
EmitTable(CodeGeneratorARM64 * codegen)548 void JumpTableARM64::EmitTable(CodeGeneratorARM64* codegen) {
549   uint32_t num_entries = switch_instr_->GetNumEntries();
550   DCHECK_GE(num_entries, kPackedSwitchCompareJumpThreshold);
551 
552   // We are about to use the assembler to place literals directly. Make sure we have enough
553   // underlying code buffer and we have generated the jump table with right size.
554   EmissionCheckScope scope(codegen->GetVIXLAssembler(),
555                            num_entries * sizeof(int32_t),
556                            CodeBufferCheckScope::kExactSize);
557 
558   __ Bind(&table_start_);
559   const ArenaVector<HBasicBlock*>& successors = switch_instr_->GetBlock()->GetSuccessors();
560   for (uint32_t i = 0; i < num_entries; i++) {
561     vixl::aarch64::Label* target_label = codegen->GetLabelOf(successors[i]);
562     DCHECK(target_label->IsBound());
563     ptrdiff_t jump_offset = target_label->GetLocation() - table_start_.GetLocation();
564     DCHECK_GT(jump_offset, std::numeric_limits<int32_t>::min());
565     DCHECK_LE(jump_offset, std::numeric_limits<int32_t>::max());
566     Literal<int32_t> literal(jump_offset);
567     __ place(&literal);
568   }
569 }
570 
571 // Slow path generating a read barrier for a heap reference.
572 class ReadBarrierForHeapReferenceSlowPathARM64 : public SlowPathCodeARM64 {
573  public:
ReadBarrierForHeapReferenceSlowPathARM64(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)574   ReadBarrierForHeapReferenceSlowPathARM64(HInstruction* instruction,
575                                            Location out,
576                                            Location ref,
577                                            Location obj,
578                                            uint32_t offset,
579                                            Location index)
580       : SlowPathCodeARM64(instruction),
581         out_(out),
582         ref_(ref),
583         obj_(obj),
584         offset_(offset),
585         index_(index) {
586     DCHECK(kEmitCompilerReadBarrier);
587     // If `obj` is equal to `out` or `ref`, it means the initial object
588     // has been overwritten by (or after) the heap object reference load
589     // to be instrumented, e.g.:
590     //
591     //   __ Ldr(out, HeapOperand(out, class_offset);
592     //   codegen_->GenerateReadBarrierSlow(instruction, out_loc, out_loc, out_loc, offset);
593     //
594     // In that case, we have lost the information about the original
595     // object, and the emitted read barrier cannot work properly.
596     DCHECK(!obj.Equals(out)) << "obj=" << obj << " out=" << out;
597     DCHECK(!obj.Equals(ref)) << "obj=" << obj << " ref=" << ref;
598   }
599 
EmitNativeCode(CodeGenerator * codegen)600   void EmitNativeCode(CodeGenerator* codegen) override {
601     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
602     LocationSummary* locations = instruction_->GetLocations();
603     DataType::Type type = DataType::Type::kReference;
604     DCHECK(locations->CanCall());
605     DCHECK(!locations->GetLiveRegisters()->ContainsCoreRegister(out_.reg()));
606     DCHECK(instruction_->IsInstanceFieldGet() ||
607            instruction_->IsPredicatedInstanceFieldGet() ||
608            instruction_->IsStaticFieldGet() ||
609            instruction_->IsArrayGet() ||
610            instruction_->IsInstanceOf() ||
611            instruction_->IsCheckCast() ||
612            (instruction_->IsInvoke() && instruction_->GetLocations()->Intrinsified()))
613         << "Unexpected instruction in read barrier for heap reference slow path: "
614         << instruction_->DebugName();
615     // The read barrier instrumentation of object ArrayGet
616     // instructions does not support the HIntermediateAddress
617     // instruction.
618     DCHECK(!(instruction_->IsArrayGet() &&
619              instruction_->AsArrayGet()->GetArray()->IsIntermediateAddress()));
620 
621     __ Bind(GetEntryLabel());
622 
623     SaveLiveRegisters(codegen, locations);
624 
625     // We may have to change the index's value, but as `index_` is a
626     // constant member (like other "inputs" of this slow path),
627     // introduce a copy of it, `index`.
628     Location index = index_;
629     if (index_.IsValid()) {
630       // Handle `index_` for HArrayGet and UnsafeGetObject/UnsafeGetObjectVolatile intrinsics.
631       if (instruction_->IsArrayGet()) {
632         // Compute the actual memory offset and store it in `index`.
633         Register index_reg = RegisterFrom(index_, DataType::Type::kInt32);
634         DCHECK(locations->GetLiveRegisters()->ContainsCoreRegister(index_.reg()));
635         if (codegen->IsCoreCalleeSaveRegister(index_.reg())) {
636           // We are about to change the value of `index_reg` (see the
637           // calls to vixl::MacroAssembler::Lsl and
638           // vixl::MacroAssembler::Mov below), but it has
639           // not been saved by the previous call to
640           // art::SlowPathCode::SaveLiveRegisters, as it is a
641           // callee-save register --
642           // art::SlowPathCode::SaveLiveRegisters does not consider
643           // callee-save registers, as it has been designed with the
644           // assumption that callee-save registers are supposed to be
645           // handled by the called function.  So, as a callee-save
646           // register, `index_reg` _would_ eventually be saved onto
647           // the stack, but it would be too late: we would have
648           // changed its value earlier.  Therefore, we manually save
649           // it here into another freely available register,
650           // `free_reg`, chosen of course among the caller-save
651           // registers (as a callee-save `free_reg` register would
652           // exhibit the same problem).
653           //
654           // Note we could have requested a temporary register from
655           // the register allocator instead; but we prefer not to, as
656           // this is a slow path, and we know we can find a
657           // caller-save register that is available.
658           Register free_reg = FindAvailableCallerSaveRegister(codegen);
659           __ Mov(free_reg.W(), index_reg);
660           index_reg = free_reg;
661           index = LocationFrom(index_reg);
662         } else {
663           // The initial register stored in `index_` has already been
664           // saved in the call to art::SlowPathCode::SaveLiveRegisters
665           // (as it is not a callee-save register), so we can freely
666           // use it.
667         }
668         // Shifting the index value contained in `index_reg` by the scale
669         // factor (2) cannot overflow in practice, as the runtime is
670         // unable to allocate object arrays with a size larger than
671         // 2^26 - 1 (that is, 2^28 - 4 bytes).
672         __ Lsl(index_reg, index_reg, DataType::SizeShift(type));
673         static_assert(
674             sizeof(mirror::HeapReference<mirror::Object>) == sizeof(int32_t),
675             "art::mirror::HeapReference<art::mirror::Object> and int32_t have different sizes.");
676         __ Add(index_reg, index_reg, Operand(offset_));
677       } else {
678         // In the case of the following intrinsics `index_` is not shifted by a scale factor of 2
679         // (as in the case of ArrayGet), as it is actually an offset to an object field within an
680         // object.
681         DCHECK(instruction_->IsInvoke()) << instruction_->DebugName();
682         DCHECK(instruction_->GetLocations()->Intrinsified());
683         HInvoke* invoke = instruction_->AsInvoke();
684         DCHECK(IsUnsafeGetObject(invoke) ||
685                IsVarHandleGet(invoke) ||
686                IsUnsafeCASObject(invoke) ||
687                IsVarHandleCASFamily(invoke)) << invoke->GetIntrinsic();
688         DCHECK_EQ(offset_, 0u);
689         DCHECK(index_.IsRegister());
690       }
691     }
692 
693     // We're moving two or three locations to locations that could
694     // overlap, so we need a parallel move resolver.
695     InvokeRuntimeCallingConvention calling_convention;
696     HParallelMove parallel_move(codegen->GetGraph()->GetAllocator());
697     parallel_move.AddMove(ref_,
698                           LocationFrom(calling_convention.GetRegisterAt(0)),
699                           type,
700                           nullptr);
701     parallel_move.AddMove(obj_,
702                           LocationFrom(calling_convention.GetRegisterAt(1)),
703                           type,
704                           nullptr);
705     if (index.IsValid()) {
706       parallel_move.AddMove(index,
707                             LocationFrom(calling_convention.GetRegisterAt(2)),
708                             DataType::Type::kInt32,
709                             nullptr);
710       codegen->GetMoveResolver()->EmitNativeCode(&parallel_move);
711     } else {
712       codegen->GetMoveResolver()->EmitNativeCode(&parallel_move);
713       arm64_codegen->MoveConstant(LocationFrom(calling_convention.GetRegisterAt(2)), offset_);
714     }
715     arm64_codegen->InvokeRuntime(kQuickReadBarrierSlow,
716                                  instruction_,
717                                  instruction_->GetDexPc(),
718                                  this);
719     CheckEntrypointTypes<
720         kQuickReadBarrierSlow, mirror::Object*, mirror::Object*, mirror::Object*, uint32_t>();
721     arm64_codegen->MoveLocation(out_, calling_convention.GetReturnLocation(type), type);
722 
723     RestoreLiveRegisters(codegen, locations);
724 
725     __ B(GetExitLabel());
726   }
727 
GetDescription() const728   const char* GetDescription() const override { return "ReadBarrierForHeapReferenceSlowPathARM64"; }
729 
730  private:
FindAvailableCallerSaveRegister(CodeGenerator * codegen)731   Register FindAvailableCallerSaveRegister(CodeGenerator* codegen) {
732     size_t ref = static_cast<int>(XRegisterFrom(ref_).GetCode());
733     size_t obj = static_cast<int>(XRegisterFrom(obj_).GetCode());
734     for (size_t i = 0, e = codegen->GetNumberOfCoreRegisters(); i < e; ++i) {
735       if (i != ref && i != obj && !codegen->IsCoreCalleeSaveRegister(i)) {
736         return Register(VIXLRegCodeFromART(i), kXRegSize);
737       }
738     }
739     // We shall never fail to find a free caller-save register, as
740     // there are more than two core caller-save registers on ARM64
741     // (meaning it is possible to find one which is different from
742     // `ref` and `obj`).
743     DCHECK_GT(codegen->GetNumberOfCoreCallerSaveRegisters(), 2u);
744     LOG(FATAL) << "Could not find a free register";
745     UNREACHABLE();
746   }
747 
748   const Location out_;
749   const Location ref_;
750   const Location obj_;
751   const uint32_t offset_;
752   // An additional location containing an index to an array.
753   // Only used for HArrayGet and the UnsafeGetObject &
754   // UnsafeGetObjectVolatile intrinsics.
755   const Location index_;
756 
757   DISALLOW_COPY_AND_ASSIGN(ReadBarrierForHeapReferenceSlowPathARM64);
758 };
759 
760 // Slow path generating a read barrier for a GC root.
761 class ReadBarrierForRootSlowPathARM64 : public SlowPathCodeARM64 {
762  public:
ReadBarrierForRootSlowPathARM64(HInstruction * instruction,Location out,Location root)763   ReadBarrierForRootSlowPathARM64(HInstruction* instruction, Location out, Location root)
764       : SlowPathCodeARM64(instruction), out_(out), root_(root) {
765     DCHECK(kEmitCompilerReadBarrier);
766   }
767 
EmitNativeCode(CodeGenerator * codegen)768   void EmitNativeCode(CodeGenerator* codegen) override {
769     LocationSummary* locations = instruction_->GetLocations();
770     DataType::Type type = DataType::Type::kReference;
771     DCHECK(locations->CanCall());
772     DCHECK(!locations->GetLiveRegisters()->ContainsCoreRegister(out_.reg()));
773     DCHECK(instruction_->IsLoadClass() ||
774            instruction_->IsLoadString() ||
775            (instruction_->IsInvoke() && instruction_->GetLocations()->Intrinsified()))
776         << "Unexpected instruction in read barrier for GC root slow path: "
777         << instruction_->DebugName();
778 
779     __ Bind(GetEntryLabel());
780     SaveLiveRegisters(codegen, locations);
781 
782     InvokeRuntimeCallingConvention calling_convention;
783     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
784     // The argument of the ReadBarrierForRootSlow is not a managed
785     // reference (`mirror::Object*`), but a `GcRoot<mirror::Object>*`;
786     // thus we need a 64-bit move here, and we cannot use
787     //
788     //   arm64_codegen->MoveLocation(
789     //       LocationFrom(calling_convention.GetRegisterAt(0)),
790     //       root_,
791     //       type);
792     //
793     // which would emit a 32-bit move, as `type` is a (32-bit wide)
794     // reference type (`DataType::Type::kReference`).
795     __ Mov(calling_convention.GetRegisterAt(0), XRegisterFrom(out_));
796     arm64_codegen->InvokeRuntime(kQuickReadBarrierForRootSlow,
797                                  instruction_,
798                                  instruction_->GetDexPc(),
799                                  this);
800     CheckEntrypointTypes<kQuickReadBarrierForRootSlow, mirror::Object*, GcRoot<mirror::Object>*>();
801     arm64_codegen->MoveLocation(out_, calling_convention.GetReturnLocation(type), type);
802 
803     RestoreLiveRegisters(codegen, locations);
804     __ B(GetExitLabel());
805   }
806 
GetDescription() const807   const char* GetDescription() const override { return "ReadBarrierForRootSlowPathARM64"; }
808 
809  private:
810   const Location out_;
811   const Location root_;
812 
813   DISALLOW_COPY_AND_ASSIGN(ReadBarrierForRootSlowPathARM64);
814 };
815 
816 class MethodEntryExitHooksSlowPathARM64 : public SlowPathCodeARM64 {
817  public:
MethodEntryExitHooksSlowPathARM64(HInstruction * instruction)818   explicit MethodEntryExitHooksSlowPathARM64(HInstruction* instruction)
819       : SlowPathCodeARM64(instruction) {}
820 
EmitNativeCode(CodeGenerator * codegen)821   void EmitNativeCode(CodeGenerator* codegen) override {
822     LocationSummary* locations = instruction_->GetLocations();
823     QuickEntrypointEnum entry_point =
824         (instruction_->IsMethodEntryHook()) ? kQuickMethodEntryHook : kQuickMethodExitHook;
825     CodeGeneratorARM64* arm64_codegen = down_cast<CodeGeneratorARM64*>(codegen);
826     __ Bind(GetEntryLabel());
827     SaveLiveRegisters(codegen, locations);
828     arm64_codegen->InvokeRuntime(entry_point, instruction_, instruction_->GetDexPc(), this);
829     RestoreLiveRegisters(codegen, locations);
830     __ B(GetExitLabel());
831   }
832 
GetDescription() const833   const char* GetDescription() const override {
834     return "MethodEntryExitHooksSlowPath";
835   }
836 
837  private:
838   DISALLOW_COPY_AND_ASSIGN(MethodEntryExitHooksSlowPathARM64);
839 };
840 
841 class CompileOptimizedSlowPathARM64 : public SlowPathCodeARM64 {
842  public:
CompileOptimizedSlowPathARM64()843   CompileOptimizedSlowPathARM64() : SlowPathCodeARM64(/* instruction= */ nullptr) {}
844 
EmitNativeCode(CodeGenerator * codegen)845   void EmitNativeCode(CodeGenerator* codegen) override {
846     uint32_t entrypoint_offset =
847         GetThreadOffset<kArm64PointerSize>(kQuickCompileOptimized).Int32Value();
848     __ Bind(GetEntryLabel());
849     __ Ldr(lr, MemOperand(tr, entrypoint_offset));
850     // Note: we don't record the call here (and therefore don't generate a stack
851     // map), as the entrypoint should never be suspended.
852     __ Blr(lr);
853     __ B(GetExitLabel());
854   }
855 
GetDescription() const856   const char* GetDescription() const override {
857     return "CompileOptimizedSlowPath";
858   }
859 
860  private:
861   DISALLOW_COPY_AND_ASSIGN(CompileOptimizedSlowPathARM64);
862 };
863 
864 #undef __
865 
GetNextLocation(DataType::Type type)866 Location InvokeDexCallingConventionVisitorARM64::GetNextLocation(DataType::Type type) {
867   Location next_location;
868   if (type == DataType::Type::kVoid) {
869     LOG(FATAL) << "Unreachable type " << type;
870   }
871 
872   if (DataType::IsFloatingPointType(type) &&
873       (float_index_ < calling_convention.GetNumberOfFpuRegisters())) {
874     next_location = LocationFrom(calling_convention.GetFpuRegisterAt(float_index_++));
875   } else if (!DataType::IsFloatingPointType(type) &&
876              (gp_index_ < calling_convention.GetNumberOfRegisters())) {
877     next_location = LocationFrom(calling_convention.GetRegisterAt(gp_index_++));
878   } else {
879     size_t stack_offset = calling_convention.GetStackOffsetOf(stack_index_);
880     next_location = DataType::Is64BitType(type) ? Location::DoubleStackSlot(stack_offset)
881                                                 : Location::StackSlot(stack_offset);
882   }
883 
884   // Space on the stack is reserved for all arguments.
885   stack_index_ += DataType::Is64BitType(type) ? 2 : 1;
886   return next_location;
887 }
888 
GetMethodLocation() const889 Location InvokeDexCallingConventionVisitorARM64::GetMethodLocation() const {
890   return LocationFrom(kArtMethodRegister);
891 }
892 
GetNextLocation(DataType::Type type)893 Location CriticalNativeCallingConventionVisitorARM64::GetNextLocation(DataType::Type type) {
894   DCHECK_NE(type, DataType::Type::kReference);
895 
896   Location location = Location::NoLocation();
897   if (DataType::IsFloatingPointType(type)) {
898     if (fpr_index_ < kParameterFPRegistersLength) {
899       location = LocationFrom(kParameterFPRegisters[fpr_index_]);
900       ++fpr_index_;
901     }
902   } else {
903     // Native ABI uses the same registers as managed, except that the method register x0
904     // is a normal argument.
905     if (gpr_index_ < 1u + kParameterCoreRegistersLength) {
906       location = LocationFrom(gpr_index_ == 0u ? x0 : kParameterCoreRegisters[gpr_index_ - 1u]);
907       ++gpr_index_;
908     }
909   }
910   if (location.IsInvalid()) {
911     if (DataType::Is64BitType(type)) {
912       location = Location::DoubleStackSlot(stack_offset_);
913     } else {
914       location = Location::StackSlot(stack_offset_);
915     }
916     stack_offset_ += kFramePointerSize;
917 
918     if (for_register_allocation_) {
919       location = Location::Any();
920     }
921   }
922   return location;
923 }
924 
GetReturnLocation(DataType::Type type) const925 Location CriticalNativeCallingConventionVisitorARM64::GetReturnLocation(DataType::Type type) const {
926   // We perform conversion to the managed ABI return register after the call if needed.
927   InvokeDexCallingConventionVisitorARM64 dex_calling_convention;
928   return dex_calling_convention.GetReturnLocation(type);
929 }
930 
GetMethodLocation() const931 Location CriticalNativeCallingConventionVisitorARM64::GetMethodLocation() const {
932   // Pass the method in the hidden argument x15.
933   return Location::RegisterLocation(x15.GetCode());
934 }
935 
CodeGeneratorARM64(HGraph * graph,const CompilerOptions & compiler_options,OptimizingCompilerStats * stats)936 CodeGeneratorARM64::CodeGeneratorARM64(HGraph* graph,
937                                        const CompilerOptions& compiler_options,
938                                        OptimizingCompilerStats* stats)
939     : CodeGenerator(graph,
940                     kNumberOfAllocatableRegisters,
941                     kNumberOfAllocatableFPRegisters,
942                     kNumberOfAllocatableRegisterPairs,
943                     callee_saved_core_registers.GetList(),
944                     callee_saved_fp_registers.GetList(),
945                     compiler_options,
946                     stats),
947       block_labels_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
948       jump_tables_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
949       location_builder_neon_(graph, this),
950       instruction_visitor_neon_(graph, this),
951       location_builder_sve_(graph, this),
952       instruction_visitor_sve_(graph, this),
953       move_resolver_(graph->GetAllocator(), this),
954       assembler_(graph->GetAllocator(),
955                  compiler_options.GetInstructionSetFeatures()->AsArm64InstructionSetFeatures()),
956       boot_image_method_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
957       method_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
958       boot_image_type_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
959       type_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
960       public_type_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
961       package_type_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
962       boot_image_string_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
963       string_bss_entry_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
964       boot_image_jni_entrypoint_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
965       boot_image_other_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
966       call_entrypoint_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
967       baker_read_barrier_patches_(graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
968       uint32_literals_(std::less<uint32_t>(),
969                        graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
970       uint64_literals_(std::less<uint64_t>(),
971                        graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
972       jit_string_patches_(StringReferenceValueComparator(),
973                           graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
974       jit_class_patches_(TypeReferenceValueComparator(),
975                          graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)),
976       jit_baker_read_barrier_slow_paths_(std::less<uint32_t>(),
977                                          graph->GetAllocator()->Adapter(kArenaAllocCodeGenerator)) {
978   // Save the link register (containing the return address) to mimic Quick.
979   AddAllocatedRegister(LocationFrom(lr));
980 
981   bool use_sve = ShouldUseSVE();
982   if (use_sve) {
983     location_builder_ = &location_builder_sve_;
984     instruction_visitor_ = &instruction_visitor_sve_;
985   } else {
986     location_builder_ = &location_builder_neon_;
987     instruction_visitor_ = &instruction_visitor_neon_;
988   }
989 }
990 
ShouldUseSVE() const991 bool CodeGeneratorARM64::ShouldUseSVE() const {
992   return GetInstructionSetFeatures().HasSVE();
993 }
994 
GetSIMDRegisterWidth() const995 size_t CodeGeneratorARM64::GetSIMDRegisterWidth() const {
996   return SupportsPredicatedSIMD()
997       ? GetInstructionSetFeatures().GetSVEVectorLength() / kBitsPerByte
998       : vixl::aarch64::kQRegSizeInBytes;
999 }
1000 
1001 #define __ GetVIXLAssembler()->
1002 
EmitJumpTables()1003 void CodeGeneratorARM64::EmitJumpTables() {
1004   for (auto&& jump_table : jump_tables_) {
1005     jump_table->EmitTable(this);
1006   }
1007 }
1008 
Finalize(CodeAllocator * allocator)1009 void CodeGeneratorARM64::Finalize(CodeAllocator* allocator) {
1010   EmitJumpTables();
1011 
1012   // Emit JIT baker read barrier slow paths.
1013   DCHECK(GetCompilerOptions().IsJitCompiler() || jit_baker_read_barrier_slow_paths_.empty());
1014   for (auto& entry : jit_baker_read_barrier_slow_paths_) {
1015     uint32_t encoded_data = entry.first;
1016     vixl::aarch64::Label* slow_path_entry = &entry.second.label;
1017     __ Bind(slow_path_entry);
1018     CompileBakerReadBarrierThunk(*GetAssembler(), encoded_data, /* debug_name= */ nullptr);
1019   }
1020 
1021   // Ensure we emit the literal pool.
1022   __ FinalizeCode();
1023 
1024   CodeGenerator::Finalize(allocator);
1025 
1026   // Verify Baker read barrier linker patches.
1027   if (kIsDebugBuild) {
1028     ArrayRef<const uint8_t> code = allocator->GetMemory();
1029     for (const BakerReadBarrierPatchInfo& info : baker_read_barrier_patches_) {
1030       DCHECK(info.label.IsBound());
1031       uint32_t literal_offset = info.label.GetLocation();
1032       DCHECK_ALIGNED(literal_offset, 4u);
1033 
1034       auto GetInsn = [&code](uint32_t offset) {
1035         DCHECK_ALIGNED(offset, 4u);
1036         return
1037             (static_cast<uint32_t>(code[offset + 0]) << 0) +
1038             (static_cast<uint32_t>(code[offset + 1]) << 8) +
1039             (static_cast<uint32_t>(code[offset + 2]) << 16)+
1040             (static_cast<uint32_t>(code[offset + 3]) << 24);
1041       };
1042 
1043       const uint32_t encoded_data = info.custom_data;
1044       BakerReadBarrierKind kind = BakerReadBarrierKindField::Decode(encoded_data);
1045       // Check that the next instruction matches the expected LDR.
1046       switch (kind) {
1047         case BakerReadBarrierKind::kField:
1048         case BakerReadBarrierKind::kAcquire: {
1049           DCHECK_GE(code.size() - literal_offset, 8u);
1050           uint32_t next_insn = GetInsn(literal_offset + 4u);
1051           CheckValidReg(next_insn & 0x1fu);  // Check destination register.
1052           const uint32_t base_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
1053           if (kind == BakerReadBarrierKind::kField) {
1054             // LDR (immediate) with correct base_reg.
1055             CHECK_EQ(next_insn & 0xffc003e0u, 0xb9400000u | (base_reg << 5));
1056           } else {
1057             DCHECK(kind == BakerReadBarrierKind::kAcquire);
1058             // LDAR with correct base_reg.
1059             CHECK_EQ(next_insn & 0xffffffe0u, 0x88dffc00u | (base_reg << 5));
1060           }
1061           break;
1062         }
1063         case BakerReadBarrierKind::kArray: {
1064           DCHECK_GE(code.size() - literal_offset, 8u);
1065           uint32_t next_insn = GetInsn(literal_offset + 4u);
1066           // LDR (register) with the correct base_reg, size=10 (32-bit), option=011 (extend = LSL),
1067           // and S=1 (shift amount = 2 for 32-bit version), i.e. LDR Wt, [Xn, Xm, LSL #2].
1068           CheckValidReg(next_insn & 0x1fu);  // Check destination register.
1069           const uint32_t base_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
1070           CHECK_EQ(next_insn & 0xffe0ffe0u, 0xb8607800u | (base_reg << 5));
1071           CheckValidReg((next_insn >> 16) & 0x1f);  // Check index register
1072           break;
1073         }
1074         case BakerReadBarrierKind::kGcRoot: {
1075           DCHECK_GE(literal_offset, 4u);
1076           uint32_t prev_insn = GetInsn(literal_offset - 4u);
1077           const uint32_t root_reg = BakerReadBarrierFirstRegField::Decode(encoded_data);
1078           // Usually LDR (immediate) with correct root_reg but
1079           // we may have a "MOV marked, old_value" for intrinsic CAS.
1080           if ((prev_insn & 0xffe0ffff) != (0x2a0003e0 | root_reg)) {    // MOV?
1081             CHECK_EQ(prev_insn & 0xffc0001fu, 0xb9400000u | root_reg);  // LDR?
1082           }
1083           break;
1084         }
1085         default:
1086           LOG(FATAL) << "Unexpected kind: " << static_cast<uint32_t>(kind);
1087           UNREACHABLE();
1088       }
1089     }
1090   }
1091 }
1092 
PrepareForEmitNativeCode()1093 void ParallelMoveResolverARM64::PrepareForEmitNativeCode() {
1094   // Note: There are 6 kinds of moves:
1095   // 1. constant -> GPR/FPR (non-cycle)
1096   // 2. constant -> stack (non-cycle)
1097   // 3. GPR/FPR -> GPR/FPR
1098   // 4. GPR/FPR -> stack
1099   // 5. stack -> GPR/FPR
1100   // 6. stack -> stack (non-cycle)
1101   // Case 1, 2 and 6 should never be included in a dependency cycle on ARM64. For case 3, 4, and 5
1102   // VIXL uses at most 1 GPR. VIXL has 2 GPR and 1 FPR temps, and there should be no intersecting
1103   // cycles on ARM64, so we always have 1 GPR and 1 FPR available VIXL temps to resolve the
1104   // dependency.
1105   vixl_temps_.Open(GetVIXLAssembler());
1106 }
1107 
FinishEmitNativeCode()1108 void ParallelMoveResolverARM64::FinishEmitNativeCode() {
1109   vixl_temps_.Close();
1110 }
1111 
AllocateScratchLocationFor(Location::Kind kind)1112 Location ParallelMoveResolverARM64::AllocateScratchLocationFor(Location::Kind kind) {
1113   DCHECK(kind == Location::kRegister || kind == Location::kFpuRegister
1114          || kind == Location::kStackSlot || kind == Location::kDoubleStackSlot
1115          || kind == Location::kSIMDStackSlot);
1116   kind = (kind == Location::kFpuRegister || kind == Location::kSIMDStackSlot)
1117       ? Location::kFpuRegister
1118       : Location::kRegister;
1119   Location scratch = GetScratchLocation(kind);
1120   if (!scratch.Equals(Location::NoLocation())) {
1121     return scratch;
1122   }
1123   // Allocate from VIXL temp registers.
1124   if (kind == Location::kRegister) {
1125     scratch = LocationFrom(vixl_temps_.AcquireX());
1126   } else {
1127     DCHECK_EQ(kind, Location::kFpuRegister);
1128     scratch = codegen_->GetGraph()->HasSIMD()
1129         ? codegen_->GetInstructionCodeGeneratorArm64()->AllocateSIMDScratchLocation(&vixl_temps_)
1130         : LocationFrom(vixl_temps_.AcquireD());
1131   }
1132   AddScratchLocation(scratch);
1133   return scratch;
1134 }
1135 
FreeScratchLocation(Location loc)1136 void ParallelMoveResolverARM64::FreeScratchLocation(Location loc) {
1137   if (loc.IsRegister()) {
1138     vixl_temps_.Release(XRegisterFrom(loc));
1139   } else {
1140     DCHECK(loc.IsFpuRegister());
1141     if (codegen_->GetGraph()->HasSIMD()) {
1142       codegen_->GetInstructionCodeGeneratorArm64()->FreeSIMDScratchLocation(loc, &vixl_temps_);
1143     } else {
1144       vixl_temps_.Release(DRegisterFrom(loc));
1145     }
1146   }
1147   RemoveScratchLocation(loc);
1148 }
1149 
EmitMove(size_t index)1150 void ParallelMoveResolverARM64::EmitMove(size_t index) {
1151   MoveOperands* move = moves_[index];
1152   codegen_->MoveLocation(move->GetDestination(), move->GetSource(), DataType::Type::kVoid);
1153 }
1154 
VisitMethodExitHook(HMethodExitHook * method_hook)1155 void LocationsBuilderARM64::VisitMethodExitHook(HMethodExitHook* method_hook) {
1156   LocationSummary* locations = new (GetGraph()->GetAllocator())
1157       LocationSummary(method_hook, LocationSummary::kCallOnSlowPath);
1158   DataType::Type return_type = method_hook->InputAt(0)->GetType();
1159   locations->SetInAt(0, ARM64ReturnLocation(return_type));
1160 }
1161 
GenerateMethodEntryExitHook(HInstruction * instruction)1162 void InstructionCodeGeneratorARM64::GenerateMethodEntryExitHook(HInstruction* instruction) {
1163   MacroAssembler* masm = GetVIXLAssembler();
1164   UseScratchRegisterScope temps(masm);
1165   Register temp = temps.AcquireX();
1166   Register value = temps.AcquireW();
1167 
1168   SlowPathCodeARM64* slow_path =
1169       new (codegen_->GetScopedAllocator()) MethodEntryExitHooksSlowPathARM64(instruction);
1170   codegen_->AddSlowPath(slow_path);
1171 
1172   uint64_t address = reinterpret_cast64<uint64_t>(Runtime::Current()->GetInstrumentation());
1173   int offset = instrumentation::Instrumentation::NeedsEntryExitHooksOffset().Int32Value();
1174   __ Mov(temp, address + offset);
1175   __ Ldrb(value, MemOperand(temp, 0));
1176   __ Cbnz(value, slow_path->GetEntryLabel());
1177   __ Bind(slow_path->GetExitLabel());
1178 }
1179 
VisitMethodExitHook(HMethodExitHook * instruction)1180 void InstructionCodeGeneratorARM64::VisitMethodExitHook(HMethodExitHook* instruction) {
1181   DCHECK(codegen_->GetCompilerOptions().IsJitCompiler() && GetGraph()->IsDebuggable());
1182   DCHECK(codegen_->RequiresCurrentMethod());
1183   GenerateMethodEntryExitHook(instruction);
1184 }
1185 
VisitMethodEntryHook(HMethodEntryHook * method_hook)1186 void LocationsBuilderARM64::VisitMethodEntryHook(HMethodEntryHook* method_hook) {
1187   new (GetGraph()->GetAllocator()) LocationSummary(method_hook, LocationSummary::kCallOnSlowPath);
1188 }
1189 
VisitMethodEntryHook(HMethodEntryHook * instruction)1190 void InstructionCodeGeneratorARM64::VisitMethodEntryHook(HMethodEntryHook* instruction) {
1191   DCHECK(codegen_->GetCompilerOptions().IsJitCompiler() && GetGraph()->IsDebuggable());
1192   DCHECK(codegen_->RequiresCurrentMethod());
1193   GenerateMethodEntryExitHook(instruction);
1194 }
1195 
MaybeIncrementHotness(bool is_frame_entry)1196 void CodeGeneratorARM64::MaybeIncrementHotness(bool is_frame_entry) {
1197   MacroAssembler* masm = GetVIXLAssembler();
1198   if (GetCompilerOptions().CountHotnessInCompiledCode()) {
1199     UseScratchRegisterScope temps(masm);
1200     Register counter = temps.AcquireX();
1201     Register method = is_frame_entry ? kArtMethodRegister : temps.AcquireX();
1202     if (!is_frame_entry) {
1203       __ Ldr(method, MemOperand(sp, 0));
1204     }
1205     __ Ldrh(counter, MemOperand(method, ArtMethod::HotnessCountOffset().Int32Value()));
1206     vixl::aarch64::Label done;
1207     DCHECK_EQ(0u, interpreter::kNterpHotnessValue);
1208     __ Cbz(counter, &done);
1209     __ Add(counter, counter, -1);
1210     __ Strh(counter, MemOperand(method, ArtMethod::HotnessCountOffset().Int32Value()));
1211     __ Bind(&done);
1212   }
1213 
1214   if (GetGraph()->IsCompilingBaseline() && !Runtime::Current()->IsAotCompiler()) {
1215     SlowPathCodeARM64* slow_path = new (GetScopedAllocator()) CompileOptimizedSlowPathARM64();
1216     AddSlowPath(slow_path);
1217     ProfilingInfo* info = GetGraph()->GetProfilingInfo();
1218     DCHECK(info != nullptr);
1219     DCHECK(!HasEmptyFrame());
1220     uint64_t address = reinterpret_cast64<uint64_t>(info);
1221     vixl::aarch64::Label done;
1222     UseScratchRegisterScope temps(masm);
1223     Register temp = temps.AcquireX();
1224     Register counter = temps.AcquireW();
1225     __ Ldr(temp, DeduplicateUint64Literal(address));
1226     __ Ldrh(counter, MemOperand(temp, ProfilingInfo::BaselineHotnessCountOffset().Int32Value()));
1227     __ Cbz(counter, slow_path->GetEntryLabel());
1228     __ Add(counter, counter, -1);
1229     __ Strh(counter, MemOperand(temp, ProfilingInfo::BaselineHotnessCountOffset().Int32Value()));
1230     __ Bind(slow_path->GetExitLabel());
1231   }
1232 }
1233 
GenerateFrameEntry()1234 void CodeGeneratorARM64::GenerateFrameEntry() {
1235   MacroAssembler* masm = GetVIXLAssembler();
1236   __ Bind(&frame_entry_label_);
1237 
1238   bool do_overflow_check =
1239       FrameNeedsStackCheck(GetFrameSize(), InstructionSet::kArm64) || !IsLeafMethod();
1240   if (do_overflow_check) {
1241     UseScratchRegisterScope temps(masm);
1242     Register temp = temps.AcquireX();
1243     DCHECK(GetCompilerOptions().GetImplicitStackOverflowChecks());
1244     __ Sub(temp, sp, static_cast<int32_t>(GetStackOverflowReservedBytes(InstructionSet::kArm64)));
1245     {
1246       // Ensure that between load and RecordPcInfo there are no pools emitted.
1247       ExactAssemblyScope eas(GetVIXLAssembler(),
1248                              kInstructionSize,
1249                              CodeBufferCheckScope::kExactSize);
1250       __ ldr(wzr, MemOperand(temp, 0));
1251       RecordPcInfo(nullptr, 0);
1252     }
1253   }
1254 
1255   if (!HasEmptyFrame()) {
1256     // Stack layout:
1257     //      sp[frame_size - 8]        : lr.
1258     //      ...                       : other preserved core registers.
1259     //      ...                       : other preserved fp registers.
1260     //      ...                       : reserved frame space.
1261     //      sp[0]                     : current method.
1262     int32_t frame_size = dchecked_integral_cast<int32_t>(GetFrameSize());
1263     uint32_t core_spills_offset = frame_size - GetCoreSpillSize();
1264     CPURegList preserved_core_registers = GetFramePreservedCoreRegisters();
1265     DCHECK(!preserved_core_registers.IsEmpty());
1266     uint32_t fp_spills_offset = frame_size - FrameEntrySpillSize();
1267     CPURegList preserved_fp_registers = GetFramePreservedFPRegisters();
1268 
1269     // Save the current method if we need it, or if using STP reduces code
1270     // size. Note that we do not do this in HCurrentMethod, as the
1271     // instruction might have been removed in the SSA graph.
1272     CPURegister lowest_spill;
1273     if (core_spills_offset == kXRegSizeInBytes) {
1274       // If there is no gap between the method and the lowest core spill, use
1275       // aligned STP pre-index to store both. Max difference is 512. We do
1276       // that to reduce code size even if we do not have to save the method.
1277       DCHECK_LE(frame_size, 512);  // 32 core registers are only 256 bytes.
1278       lowest_spill = preserved_core_registers.PopLowestIndex();
1279       __ Stp(kArtMethodRegister, lowest_spill, MemOperand(sp, -frame_size, PreIndex));
1280     } else if (RequiresCurrentMethod()) {
1281       __ Str(kArtMethodRegister, MemOperand(sp, -frame_size, PreIndex));
1282     } else {
1283       __ Claim(frame_size);
1284     }
1285     GetAssembler()->cfi().AdjustCFAOffset(frame_size);
1286     if (lowest_spill.IsValid()) {
1287       GetAssembler()->cfi().RelOffset(DWARFReg(lowest_spill), core_spills_offset);
1288       core_spills_offset += kXRegSizeInBytes;
1289     }
1290     GetAssembler()->SpillRegisters(preserved_core_registers, core_spills_offset);
1291     GetAssembler()->SpillRegisters(preserved_fp_registers, fp_spills_offset);
1292 
1293     if (GetGraph()->HasShouldDeoptimizeFlag()) {
1294       // Initialize should_deoptimize flag to 0.
1295       Register wzr = Register(VIXLRegCodeFromART(WZR), kWRegSize);
1296       __ Str(wzr, MemOperand(sp, GetStackOffsetOfShouldDeoptimizeFlag()));
1297     }
1298   }
1299   MaybeIncrementHotness(/* is_frame_entry= */ true);
1300   MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
1301 }
1302 
GenerateFrameExit()1303 void CodeGeneratorARM64::GenerateFrameExit() {
1304   GetAssembler()->cfi().RememberState();
1305   if (!HasEmptyFrame()) {
1306     int32_t frame_size = dchecked_integral_cast<int32_t>(GetFrameSize());
1307     uint32_t core_spills_offset = frame_size - GetCoreSpillSize();
1308     CPURegList preserved_core_registers = GetFramePreservedCoreRegisters();
1309     DCHECK(!preserved_core_registers.IsEmpty());
1310     uint32_t fp_spills_offset = frame_size - FrameEntrySpillSize();
1311     CPURegList preserved_fp_registers = GetFramePreservedFPRegisters();
1312 
1313     CPURegister lowest_spill;
1314     if (core_spills_offset == kXRegSizeInBytes) {
1315       // If there is no gap between the method and the lowest core spill, use
1316       // aligned LDP pre-index to pop both. Max difference is 504. We do
1317       // that to reduce code size even though the loaded method is unused.
1318       DCHECK_LE(frame_size, 504);  // 32 core registers are only 256 bytes.
1319       lowest_spill = preserved_core_registers.PopLowestIndex();
1320       core_spills_offset += kXRegSizeInBytes;
1321     }
1322     GetAssembler()->UnspillRegisters(preserved_fp_registers, fp_spills_offset);
1323     GetAssembler()->UnspillRegisters(preserved_core_registers, core_spills_offset);
1324     if (lowest_spill.IsValid()) {
1325       __ Ldp(xzr, lowest_spill, MemOperand(sp, frame_size, PostIndex));
1326       GetAssembler()->cfi().Restore(DWARFReg(lowest_spill));
1327     } else {
1328       __ Drop(frame_size);
1329     }
1330     GetAssembler()->cfi().AdjustCFAOffset(-frame_size);
1331   }
1332   __ Ret();
1333   GetAssembler()->cfi().RestoreState();
1334   GetAssembler()->cfi().DefCFAOffset(GetFrameSize());
1335 }
1336 
GetFramePreservedCoreRegisters() const1337 CPURegList CodeGeneratorARM64::GetFramePreservedCoreRegisters() const {
1338   DCHECK(ArtVixlRegCodeCoherentForRegSet(core_spill_mask_, GetNumberOfCoreRegisters(), 0, 0));
1339   return CPURegList(CPURegister::kRegister, kXRegSize,
1340                     core_spill_mask_);
1341 }
1342 
GetFramePreservedFPRegisters() const1343 CPURegList CodeGeneratorARM64::GetFramePreservedFPRegisters() const {
1344   DCHECK(ArtVixlRegCodeCoherentForRegSet(0, 0, fpu_spill_mask_,
1345                                          GetNumberOfFloatingPointRegisters()));
1346   return CPURegList(CPURegister::kVRegister, kDRegSize,
1347                     fpu_spill_mask_);
1348 }
1349 
Bind(HBasicBlock * block)1350 void CodeGeneratorARM64::Bind(HBasicBlock* block) {
1351   __ Bind(GetLabelOf(block));
1352 }
1353 
MoveConstant(Location location,int32_t value)1354 void CodeGeneratorARM64::MoveConstant(Location location, int32_t value) {
1355   DCHECK(location.IsRegister());
1356   __ Mov(RegisterFrom(location, DataType::Type::kInt32), value);
1357 }
1358 
AddLocationAsTemp(Location location,LocationSummary * locations)1359 void CodeGeneratorARM64::AddLocationAsTemp(Location location, LocationSummary* locations) {
1360   if (location.IsRegister()) {
1361     locations->AddTemp(location);
1362   } else {
1363     UNIMPLEMENTED(FATAL) << "AddLocationAsTemp not implemented for location " << location;
1364   }
1365 }
1366 
MarkGCCard(Register object,Register value,bool value_can_be_null)1367 void CodeGeneratorARM64::MarkGCCard(Register object, Register value, bool value_can_be_null) {
1368   UseScratchRegisterScope temps(GetVIXLAssembler());
1369   Register card = temps.AcquireX();
1370   Register temp = temps.AcquireW();   // Index within the CardTable - 32bit.
1371   vixl::aarch64::Label done;
1372   if (value_can_be_null) {
1373     __ Cbz(value, &done);
1374   }
1375   // Load the address of the card table into `card`.
1376   __ Ldr(card, MemOperand(tr, Thread::CardTableOffset<kArm64PointerSize>().Int32Value()));
1377   // Calculate the offset (in the card table) of the card corresponding to
1378   // `object`.
1379   __ Lsr(temp, object, gc::accounting::CardTable::kCardShift);
1380   // Write the `art::gc::accounting::CardTable::kCardDirty` value into the
1381   // `object`'s card.
1382   //
1383   // Register `card` contains the address of the card table. Note that the card
1384   // table's base is biased during its creation so that it always starts at an
1385   // address whose least-significant byte is equal to `kCardDirty` (see
1386   // art::gc::accounting::CardTable::Create). Therefore the STRB instruction
1387   // below writes the `kCardDirty` (byte) value into the `object`'s card
1388   // (located at `card + object >> kCardShift`).
1389   //
1390   // This dual use of the value in register `card` (1. to calculate the location
1391   // of the card to mark; and 2. to load the `kCardDirty` value) saves a load
1392   // (no need to explicitly load `kCardDirty` as an immediate value).
1393   __ Strb(card, MemOperand(card, temp.X()));
1394   if (value_can_be_null) {
1395     __ Bind(&done);
1396   }
1397 }
1398 
SetupBlockedRegisters() const1399 void CodeGeneratorARM64::SetupBlockedRegisters() const {
1400   // Blocked core registers:
1401   //      lr        : Runtime reserved.
1402   //      tr        : Runtime reserved.
1403   //      mr        : Runtime reserved.
1404   //      ip1       : VIXL core temp.
1405   //      ip0       : VIXL core temp.
1406   //      x18       : Platform register.
1407   //
1408   // Blocked fp registers:
1409   //      d31       : VIXL fp temp.
1410   CPURegList reserved_core_registers = vixl_reserved_core_registers;
1411   reserved_core_registers.Combine(runtime_reserved_core_registers);
1412   while (!reserved_core_registers.IsEmpty()) {
1413     blocked_core_registers_[reserved_core_registers.PopLowestIndex().GetCode()] = true;
1414   }
1415   blocked_core_registers_[X18] = true;
1416 
1417   CPURegList reserved_fp_registers = vixl_reserved_fp_registers;
1418   while (!reserved_fp_registers.IsEmpty()) {
1419     blocked_fpu_registers_[reserved_fp_registers.PopLowestIndex().GetCode()] = true;
1420   }
1421 
1422   if (GetGraph()->IsDebuggable()) {
1423     // Stubs do not save callee-save floating point registers. If the graph
1424     // is debuggable, we need to deal with these registers differently. For
1425     // now, just block them.
1426     CPURegList reserved_fp_registers_debuggable = callee_saved_fp_registers;
1427     while (!reserved_fp_registers_debuggable.IsEmpty()) {
1428       blocked_fpu_registers_[reserved_fp_registers_debuggable.PopLowestIndex().GetCode()] = true;
1429     }
1430   }
1431 }
1432 
SaveCoreRegister(size_t stack_index,uint32_t reg_id)1433 size_t CodeGeneratorARM64::SaveCoreRegister(size_t stack_index, uint32_t reg_id) {
1434   Register reg = Register(VIXLRegCodeFromART(reg_id), kXRegSize);
1435   __ Str(reg, MemOperand(sp, stack_index));
1436   return kArm64WordSize;
1437 }
1438 
RestoreCoreRegister(size_t stack_index,uint32_t reg_id)1439 size_t CodeGeneratorARM64::RestoreCoreRegister(size_t stack_index, uint32_t reg_id) {
1440   Register reg = Register(VIXLRegCodeFromART(reg_id), kXRegSize);
1441   __ Ldr(reg, MemOperand(sp, stack_index));
1442   return kArm64WordSize;
1443 }
1444 
SaveFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,uint32_t reg_id ATTRIBUTE_UNUSED)1445 size_t CodeGeneratorARM64::SaveFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,
1446                                                      uint32_t reg_id ATTRIBUTE_UNUSED) {
1447   LOG(FATAL) << "FP registers shouldn't be saved/restored individually, "
1448              << "use SaveRestoreLiveRegistersHelper";
1449   UNREACHABLE();
1450 }
1451 
RestoreFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,uint32_t reg_id ATTRIBUTE_UNUSED)1452 size_t CodeGeneratorARM64::RestoreFloatingPointRegister(size_t stack_index ATTRIBUTE_UNUSED,
1453                                                         uint32_t reg_id ATTRIBUTE_UNUSED) {
1454   LOG(FATAL) << "FP registers shouldn't be saved/restored individually, "
1455              << "use SaveRestoreLiveRegistersHelper";
1456   UNREACHABLE();
1457 }
1458 
DumpCoreRegister(std::ostream & stream,int reg) const1459 void CodeGeneratorARM64::DumpCoreRegister(std::ostream& stream, int reg) const {
1460   stream << XRegister(reg);
1461 }
1462 
DumpFloatingPointRegister(std::ostream & stream,int reg) const1463 void CodeGeneratorARM64::DumpFloatingPointRegister(std::ostream& stream, int reg) const {
1464   stream << DRegister(reg);
1465 }
1466 
GetInstructionSetFeatures() const1467 const Arm64InstructionSetFeatures& CodeGeneratorARM64::GetInstructionSetFeatures() const {
1468   return *GetCompilerOptions().GetInstructionSetFeatures()->AsArm64InstructionSetFeatures();
1469 }
1470 
MoveConstant(CPURegister destination,HConstant * constant)1471 void CodeGeneratorARM64::MoveConstant(CPURegister destination, HConstant* constant) {
1472   if (constant->IsIntConstant()) {
1473     __ Mov(Register(destination), constant->AsIntConstant()->GetValue());
1474   } else if (constant->IsLongConstant()) {
1475     __ Mov(Register(destination), constant->AsLongConstant()->GetValue());
1476   } else if (constant->IsNullConstant()) {
1477     __ Mov(Register(destination), 0);
1478   } else if (constant->IsFloatConstant()) {
1479     __ Fmov(VRegister(destination), constant->AsFloatConstant()->GetValue());
1480   } else {
1481     DCHECK(constant->IsDoubleConstant());
1482     __ Fmov(VRegister(destination), constant->AsDoubleConstant()->GetValue());
1483   }
1484 }
1485 
1486 
CoherentConstantAndType(Location constant,DataType::Type type)1487 static bool CoherentConstantAndType(Location constant, DataType::Type type) {
1488   DCHECK(constant.IsConstant());
1489   HConstant* cst = constant.GetConstant();
1490   return (cst->IsIntConstant() && type == DataType::Type::kInt32) ||
1491          // Null is mapped to a core W register, which we associate with kPrimInt.
1492          (cst->IsNullConstant() && type == DataType::Type::kInt32) ||
1493          (cst->IsLongConstant() && type == DataType::Type::kInt64) ||
1494          (cst->IsFloatConstant() && type == DataType::Type::kFloat32) ||
1495          (cst->IsDoubleConstant() && type == DataType::Type::kFloat64);
1496 }
1497 
1498 // Allocate a scratch register from the VIXL pool, querying first
1499 // the floating-point register pool, and then the core register
1500 // pool. This is essentially a reimplementation of
1501 // vixl::aarch64::UseScratchRegisterScope::AcquireCPURegisterOfSize
1502 // using a different allocation strategy.
AcquireFPOrCoreCPURegisterOfSize(vixl::aarch64::MacroAssembler * masm,vixl::aarch64::UseScratchRegisterScope * temps,int size_in_bits)1503 static CPURegister AcquireFPOrCoreCPURegisterOfSize(vixl::aarch64::MacroAssembler* masm,
1504                                                     vixl::aarch64::UseScratchRegisterScope* temps,
1505                                                     int size_in_bits) {
1506   return masm->GetScratchVRegisterList()->IsEmpty()
1507       ? CPURegister(temps->AcquireRegisterOfSize(size_in_bits))
1508       : CPURegister(temps->AcquireVRegisterOfSize(size_in_bits));
1509 }
1510 
MoveLocation(Location destination,Location source,DataType::Type dst_type)1511 void CodeGeneratorARM64::MoveLocation(Location destination,
1512                                       Location source,
1513                                       DataType::Type dst_type) {
1514   if (source.Equals(destination)) {
1515     return;
1516   }
1517 
1518   // A valid move can always be inferred from the destination and source
1519   // locations. When moving from and to a register, the argument type can be
1520   // used to generate 32bit instead of 64bit moves. In debug mode we also
1521   // checks the coherency of the locations and the type.
1522   bool unspecified_type = (dst_type == DataType::Type::kVoid);
1523 
1524   if (destination.IsRegister() || destination.IsFpuRegister()) {
1525     if (unspecified_type) {
1526       HConstant* src_cst = source.IsConstant() ? source.GetConstant() : nullptr;
1527       if (source.IsStackSlot() ||
1528           (src_cst != nullptr && (src_cst->IsIntConstant()
1529                                   || src_cst->IsFloatConstant()
1530                                   || src_cst->IsNullConstant()))) {
1531         // For stack slots and 32bit constants, a 64bit type is appropriate.
1532         dst_type = destination.IsRegister() ? DataType::Type::kInt32 : DataType::Type::kFloat32;
1533       } else {
1534         // If the source is a double stack slot or a 64bit constant, a 64bit
1535         // type is appropriate. Else the source is a register, and since the
1536         // type has not been specified, we chose a 64bit type to force a 64bit
1537         // move.
1538         dst_type = destination.IsRegister() ? DataType::Type::kInt64 : DataType::Type::kFloat64;
1539       }
1540     }
1541     DCHECK((destination.IsFpuRegister() && DataType::IsFloatingPointType(dst_type)) ||
1542            (destination.IsRegister() && !DataType::IsFloatingPointType(dst_type)));
1543     CPURegister dst = CPURegisterFrom(destination, dst_type);
1544     if (source.IsStackSlot() || source.IsDoubleStackSlot()) {
1545       DCHECK(dst.Is64Bits() == source.IsDoubleStackSlot());
1546       __ Ldr(dst, StackOperandFrom(source));
1547     } else if (source.IsSIMDStackSlot()) {
1548       GetInstructionCodeGeneratorArm64()->LoadSIMDRegFromStack(destination, source);
1549     } else if (source.IsConstant()) {
1550       DCHECK(CoherentConstantAndType(source, dst_type));
1551       MoveConstant(dst, source.GetConstant());
1552     } else if (source.IsRegister()) {
1553       if (destination.IsRegister()) {
1554         __ Mov(Register(dst), RegisterFrom(source, dst_type));
1555       } else {
1556         DCHECK(destination.IsFpuRegister());
1557         DataType::Type source_type = DataType::Is64BitType(dst_type)
1558             ? DataType::Type::kInt64
1559             : DataType::Type::kInt32;
1560         __ Fmov(FPRegisterFrom(destination, dst_type), RegisterFrom(source, source_type));
1561       }
1562     } else {
1563       DCHECK(source.IsFpuRegister());
1564       if (destination.IsRegister()) {
1565         DataType::Type source_type = DataType::Is64BitType(dst_type)
1566             ? DataType::Type::kFloat64
1567             : DataType::Type::kFloat32;
1568         __ Fmov(RegisterFrom(destination, dst_type), FPRegisterFrom(source, source_type));
1569       } else {
1570         DCHECK(destination.IsFpuRegister());
1571         if (GetGraph()->HasSIMD()) {
1572           GetInstructionCodeGeneratorArm64()->MoveSIMDRegToSIMDReg(destination, source);
1573         } else {
1574           __ Fmov(VRegister(dst), FPRegisterFrom(source, dst_type));
1575         }
1576       }
1577     }
1578   } else if (destination.IsSIMDStackSlot()) {
1579     GetInstructionCodeGeneratorArm64()->MoveToSIMDStackSlot(destination, source);
1580   } else {  // The destination is not a register. It must be a stack slot.
1581     DCHECK(destination.IsStackSlot() || destination.IsDoubleStackSlot());
1582     if (source.IsRegister() || source.IsFpuRegister()) {
1583       if (unspecified_type) {
1584         if (source.IsRegister()) {
1585           dst_type = destination.IsStackSlot() ? DataType::Type::kInt32 : DataType::Type::kInt64;
1586         } else {
1587           dst_type =
1588               destination.IsStackSlot() ? DataType::Type::kFloat32 : DataType::Type::kFloat64;
1589         }
1590       }
1591       DCHECK((destination.IsDoubleStackSlot() == DataType::Is64BitType(dst_type)) &&
1592              (source.IsFpuRegister() == DataType::IsFloatingPointType(dst_type)));
1593       __ Str(CPURegisterFrom(source, dst_type), StackOperandFrom(destination));
1594     } else if (source.IsConstant()) {
1595       DCHECK(unspecified_type || CoherentConstantAndType(source, dst_type))
1596           << source << " " << dst_type;
1597       UseScratchRegisterScope temps(GetVIXLAssembler());
1598       HConstant* src_cst = source.GetConstant();
1599       CPURegister temp;
1600       if (src_cst->IsZeroBitPattern()) {
1601         temp = (src_cst->IsLongConstant() || src_cst->IsDoubleConstant())
1602             ? Register(xzr)
1603             : Register(wzr);
1604       } else {
1605         if (src_cst->IsIntConstant()) {
1606           temp = temps.AcquireW();
1607         } else if (src_cst->IsLongConstant()) {
1608           temp = temps.AcquireX();
1609         } else if (src_cst->IsFloatConstant()) {
1610           temp = temps.AcquireS();
1611         } else {
1612           DCHECK(src_cst->IsDoubleConstant());
1613           temp = temps.AcquireD();
1614         }
1615         MoveConstant(temp, src_cst);
1616       }
1617       __ Str(temp, StackOperandFrom(destination));
1618     } else {
1619       DCHECK(source.IsStackSlot() || source.IsDoubleStackSlot());
1620       DCHECK(source.IsDoubleStackSlot() == destination.IsDoubleStackSlot());
1621       UseScratchRegisterScope temps(GetVIXLAssembler());
1622       // Use any scratch register (a core or a floating-point one)
1623       // from VIXL scratch register pools as a temporary.
1624       //
1625       // We used to only use the FP scratch register pool, but in some
1626       // rare cases the only register from this pool (D31) would
1627       // already be used (e.g. within a ParallelMove instruction, when
1628       // a move is blocked by a another move requiring a scratch FP
1629       // register, which would reserve D31). To prevent this issue, we
1630       // ask for a scratch register of any type (core or FP).
1631       //
1632       // Also, we start by asking for a FP scratch register first, as the
1633       // demand of scratch core registers is higher. This is why we
1634       // use AcquireFPOrCoreCPURegisterOfSize instead of
1635       // UseScratchRegisterScope::AcquireCPURegisterOfSize, which
1636       // allocates core scratch registers first.
1637       CPURegister temp = AcquireFPOrCoreCPURegisterOfSize(
1638           GetVIXLAssembler(),
1639           &temps,
1640           (destination.IsDoubleStackSlot() ? kXRegSize : kWRegSize));
1641       __ Ldr(temp, StackOperandFrom(source));
1642       __ Str(temp, StackOperandFrom(destination));
1643     }
1644   }
1645 }
1646 
Load(DataType::Type type,CPURegister dst,const MemOperand & src)1647 void CodeGeneratorARM64::Load(DataType::Type type,
1648                               CPURegister dst,
1649                               const MemOperand& src) {
1650   switch (type) {
1651     case DataType::Type::kBool:
1652     case DataType::Type::kUint8:
1653       __ Ldrb(Register(dst), src);
1654       break;
1655     case DataType::Type::kInt8:
1656       __ Ldrsb(Register(dst), src);
1657       break;
1658     case DataType::Type::kUint16:
1659       __ Ldrh(Register(dst), src);
1660       break;
1661     case DataType::Type::kInt16:
1662       __ Ldrsh(Register(dst), src);
1663       break;
1664     case DataType::Type::kInt32:
1665     case DataType::Type::kReference:
1666     case DataType::Type::kInt64:
1667     case DataType::Type::kFloat32:
1668     case DataType::Type::kFloat64:
1669       DCHECK_EQ(dst.Is64Bits(), DataType::Is64BitType(type));
1670       __ Ldr(dst, src);
1671       break;
1672     case DataType::Type::kUint32:
1673     case DataType::Type::kUint64:
1674     case DataType::Type::kVoid:
1675       LOG(FATAL) << "Unreachable type " << type;
1676   }
1677 }
1678 
LoadAcquire(HInstruction * instruction,DataType::Type type,CPURegister dst,const MemOperand & src,bool needs_null_check)1679 void CodeGeneratorARM64::LoadAcquire(HInstruction* instruction,
1680                                      DataType::Type type,
1681                                      CPURegister dst,
1682                                      const MemOperand& src,
1683                                      bool needs_null_check) {
1684   MacroAssembler* masm = GetVIXLAssembler();
1685   UseScratchRegisterScope temps(masm);
1686   Register temp_base = temps.AcquireX();
1687 
1688   DCHECK(!src.IsPreIndex());
1689   DCHECK(!src.IsPostIndex());
1690 
1691   // TODO(vixl): Let the MacroAssembler handle MemOperand.
1692   __ Add(temp_base, src.GetBaseRegister(), OperandFromMemOperand(src));
1693   {
1694     // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
1695     MemOperand base = MemOperand(temp_base);
1696     switch (type) {
1697       case DataType::Type::kBool:
1698       case DataType::Type::kUint8:
1699       case DataType::Type::kInt8:
1700         {
1701           ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1702           __ ldarb(Register(dst), base);
1703           if (needs_null_check) {
1704             MaybeRecordImplicitNullCheck(instruction);
1705           }
1706         }
1707         if (type == DataType::Type::kInt8) {
1708           __ Sbfx(Register(dst), Register(dst), 0, DataType::Size(type) * kBitsPerByte);
1709         }
1710         break;
1711       case DataType::Type::kUint16:
1712       case DataType::Type::kInt16:
1713         {
1714           ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1715           __ ldarh(Register(dst), base);
1716           if (needs_null_check) {
1717             MaybeRecordImplicitNullCheck(instruction);
1718           }
1719         }
1720         if (type == DataType::Type::kInt16) {
1721           __ Sbfx(Register(dst), Register(dst), 0, DataType::Size(type) * kBitsPerByte);
1722         }
1723         break;
1724       case DataType::Type::kInt32:
1725       case DataType::Type::kReference:
1726       case DataType::Type::kInt64:
1727         DCHECK_EQ(dst.Is64Bits(), DataType::Is64BitType(type));
1728         {
1729           ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1730           __ ldar(Register(dst), base);
1731           if (needs_null_check) {
1732             MaybeRecordImplicitNullCheck(instruction);
1733           }
1734         }
1735         break;
1736       case DataType::Type::kFloat32:
1737       case DataType::Type::kFloat64: {
1738         DCHECK(dst.IsFPRegister());
1739         DCHECK_EQ(dst.Is64Bits(), DataType::Is64BitType(type));
1740 
1741         Register temp = dst.Is64Bits() ? temps.AcquireX() : temps.AcquireW();
1742         {
1743           ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1744           __ ldar(temp, base);
1745           if (needs_null_check) {
1746             MaybeRecordImplicitNullCheck(instruction);
1747           }
1748         }
1749         __ Fmov(VRegister(dst), temp);
1750         break;
1751       }
1752       case DataType::Type::kUint32:
1753       case DataType::Type::kUint64:
1754       case DataType::Type::kVoid:
1755         LOG(FATAL) << "Unreachable type " << type;
1756     }
1757   }
1758 }
1759 
Store(DataType::Type type,CPURegister src,const MemOperand & dst)1760 void CodeGeneratorARM64::Store(DataType::Type type,
1761                                CPURegister src,
1762                                const MemOperand& dst) {
1763   switch (type) {
1764     case DataType::Type::kBool:
1765     case DataType::Type::kUint8:
1766     case DataType::Type::kInt8:
1767       __ Strb(Register(src), dst);
1768       break;
1769     case DataType::Type::kUint16:
1770     case DataType::Type::kInt16:
1771       __ Strh(Register(src), dst);
1772       break;
1773     case DataType::Type::kInt32:
1774     case DataType::Type::kReference:
1775     case DataType::Type::kInt64:
1776     case DataType::Type::kFloat32:
1777     case DataType::Type::kFloat64:
1778       DCHECK_EQ(src.Is64Bits(), DataType::Is64BitType(type));
1779       __ Str(src, dst);
1780       break;
1781     case DataType::Type::kUint32:
1782     case DataType::Type::kUint64:
1783     case DataType::Type::kVoid:
1784       LOG(FATAL) << "Unreachable type " << type;
1785   }
1786 }
1787 
StoreRelease(HInstruction * instruction,DataType::Type type,CPURegister src,const MemOperand & dst,bool needs_null_check)1788 void CodeGeneratorARM64::StoreRelease(HInstruction* instruction,
1789                                       DataType::Type type,
1790                                       CPURegister src,
1791                                       const MemOperand& dst,
1792                                       bool needs_null_check) {
1793   MacroAssembler* masm = GetVIXLAssembler();
1794   UseScratchRegisterScope temps(GetVIXLAssembler());
1795   Register temp_base = temps.AcquireX();
1796 
1797   DCHECK(!dst.IsPreIndex());
1798   DCHECK(!dst.IsPostIndex());
1799 
1800   // TODO(vixl): Let the MacroAssembler handle this.
1801   Operand op = OperandFromMemOperand(dst);
1802   __ Add(temp_base, dst.GetBaseRegister(), op);
1803   MemOperand base = MemOperand(temp_base);
1804   // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
1805   switch (type) {
1806     case DataType::Type::kBool:
1807     case DataType::Type::kUint8:
1808     case DataType::Type::kInt8:
1809       {
1810         ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1811         __ stlrb(Register(src), base);
1812         if (needs_null_check) {
1813           MaybeRecordImplicitNullCheck(instruction);
1814         }
1815       }
1816       break;
1817     case DataType::Type::kUint16:
1818     case DataType::Type::kInt16:
1819       {
1820         ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1821         __ stlrh(Register(src), base);
1822         if (needs_null_check) {
1823           MaybeRecordImplicitNullCheck(instruction);
1824         }
1825       }
1826       break;
1827     case DataType::Type::kInt32:
1828     case DataType::Type::kReference:
1829     case DataType::Type::kInt64:
1830       DCHECK_EQ(src.Is64Bits(), DataType::Is64BitType(type));
1831       {
1832         ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1833         __ stlr(Register(src), base);
1834         if (needs_null_check) {
1835           MaybeRecordImplicitNullCheck(instruction);
1836         }
1837       }
1838       break;
1839     case DataType::Type::kFloat32:
1840     case DataType::Type::kFloat64: {
1841       DCHECK_EQ(src.Is64Bits(), DataType::Is64BitType(type));
1842       Register temp_src;
1843       if (src.IsZero()) {
1844         // The zero register is used to avoid synthesizing zero constants.
1845         temp_src = Register(src);
1846       } else {
1847         DCHECK(src.IsFPRegister());
1848         temp_src = src.Is64Bits() ? temps.AcquireX() : temps.AcquireW();
1849         __ Fmov(temp_src, VRegister(src));
1850       }
1851       {
1852         ExactAssemblyScope eas(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
1853         __ stlr(temp_src, base);
1854         if (needs_null_check) {
1855           MaybeRecordImplicitNullCheck(instruction);
1856         }
1857       }
1858       break;
1859     }
1860     case DataType::Type::kUint32:
1861     case DataType::Type::kUint64:
1862     case DataType::Type::kVoid:
1863       LOG(FATAL) << "Unreachable type " << type;
1864   }
1865 }
1866 
InvokeRuntime(QuickEntrypointEnum entrypoint,HInstruction * instruction,uint32_t dex_pc,SlowPathCode * slow_path)1867 void CodeGeneratorARM64::InvokeRuntime(QuickEntrypointEnum entrypoint,
1868                                        HInstruction* instruction,
1869                                        uint32_t dex_pc,
1870                                        SlowPathCode* slow_path) {
1871   ValidateInvokeRuntime(entrypoint, instruction, slow_path);
1872 
1873   ThreadOffset64 entrypoint_offset = GetThreadOffset<kArm64PointerSize>(entrypoint);
1874   // Reduce code size for AOT by using shared trampolines for slow path runtime calls across the
1875   // entire oat file. This adds an extra branch and we do not want to slow down the main path.
1876   // For JIT, thunk sharing is per-method, so the gains would be smaller or even negative.
1877   if (slow_path == nullptr || GetCompilerOptions().IsJitCompiler()) {
1878     __ Ldr(lr, MemOperand(tr, entrypoint_offset.Int32Value()));
1879     // Ensure the pc position is recorded immediately after the `blr` instruction.
1880     ExactAssemblyScope eas(GetVIXLAssembler(), kInstructionSize, CodeBufferCheckScope::kExactSize);
1881     __ blr(lr);
1882     if (EntrypointRequiresStackMap(entrypoint)) {
1883       RecordPcInfo(instruction, dex_pc, slow_path);
1884     }
1885   } else {
1886     // Ensure the pc position is recorded immediately after the `bl` instruction.
1887     ExactAssemblyScope eas(GetVIXLAssembler(), kInstructionSize, CodeBufferCheckScope::kExactSize);
1888     EmitEntrypointThunkCall(entrypoint_offset);
1889     if (EntrypointRequiresStackMap(entrypoint)) {
1890       RecordPcInfo(instruction, dex_pc, slow_path);
1891     }
1892   }
1893 }
1894 
InvokeRuntimeWithoutRecordingPcInfo(int32_t entry_point_offset,HInstruction * instruction,SlowPathCode * slow_path)1895 void CodeGeneratorARM64::InvokeRuntimeWithoutRecordingPcInfo(int32_t entry_point_offset,
1896                                                              HInstruction* instruction,
1897                                                              SlowPathCode* slow_path) {
1898   ValidateInvokeRuntimeWithoutRecordingPcInfo(instruction, slow_path);
1899   __ Ldr(lr, MemOperand(tr, entry_point_offset));
1900   __ Blr(lr);
1901 }
1902 
GenerateClassInitializationCheck(SlowPathCodeARM64 * slow_path,Register class_reg)1903 void InstructionCodeGeneratorARM64::GenerateClassInitializationCheck(SlowPathCodeARM64* slow_path,
1904                                                                      Register class_reg) {
1905   UseScratchRegisterScope temps(GetVIXLAssembler());
1906   Register temp = temps.AcquireW();
1907   constexpr size_t status_lsb_position = SubtypeCheckBits::BitStructSizeOf();
1908   const size_t status_byte_offset =
1909       mirror::Class::StatusOffset().SizeValue() + (status_lsb_position / kBitsPerByte);
1910   constexpr uint32_t shifted_visibly_initialized_value =
1911       enum_cast<uint32_t>(ClassStatus::kVisiblyInitialized) << (status_lsb_position % kBitsPerByte);
1912 
1913   // CMP (immediate) is limited to imm12 or imm12<<12, so we would need to materialize
1914   // the constant 0xf0000000 for comparison with the full 32-bit field. To reduce the code
1915   // size, load only the high byte of the field and compare with 0xf0.
1916   // Note: The same code size could be achieved with LDR+MNV(asr #24)+CBNZ but benchmarks
1917   // show that this pattern is slower (tested on little cores).
1918   __ Ldrb(temp, HeapOperand(class_reg, status_byte_offset));
1919   __ Cmp(temp, shifted_visibly_initialized_value);
1920   __ B(lo, slow_path->GetEntryLabel());
1921   __ Bind(slow_path->GetExitLabel());
1922 }
1923 
GenerateBitstringTypeCheckCompare(HTypeCheckInstruction * check,vixl::aarch64::Register temp)1924 void InstructionCodeGeneratorARM64::GenerateBitstringTypeCheckCompare(
1925     HTypeCheckInstruction* check, vixl::aarch64::Register temp) {
1926   uint32_t path_to_root = check->GetBitstringPathToRoot();
1927   uint32_t mask = check->GetBitstringMask();
1928   DCHECK(IsPowerOfTwo(mask + 1));
1929   size_t mask_bits = WhichPowerOf2(mask + 1);
1930 
1931   if (mask_bits == 16u) {
1932     // Load only the bitstring part of the status word.
1933     __ Ldrh(temp, HeapOperand(temp, mirror::Class::StatusOffset()));
1934   } else {
1935     // /* uint32_t */ temp = temp->status_
1936     __ Ldr(temp, HeapOperand(temp, mirror::Class::StatusOffset()));
1937     // Extract the bitstring bits.
1938     __ Ubfx(temp, temp, 0, mask_bits);
1939   }
1940   // Compare the bitstring bits to `path_to_root`.
1941   __ Cmp(temp, path_to_root);
1942 }
1943 
GenerateMemoryBarrier(MemBarrierKind kind)1944 void CodeGeneratorARM64::GenerateMemoryBarrier(MemBarrierKind kind) {
1945   BarrierType type = BarrierAll;
1946 
1947   switch (kind) {
1948     case MemBarrierKind::kAnyAny:
1949     case MemBarrierKind::kAnyStore: {
1950       type = BarrierAll;
1951       break;
1952     }
1953     case MemBarrierKind::kLoadAny: {
1954       type = BarrierReads;
1955       break;
1956     }
1957     case MemBarrierKind::kStoreStore: {
1958       type = BarrierWrites;
1959       break;
1960     }
1961     default:
1962       LOG(FATAL) << "Unexpected memory barrier " << kind;
1963   }
1964   __ Dmb(InnerShareable, type);
1965 }
1966 
CanUseImplicitSuspendCheck() const1967 bool CodeGeneratorARM64::CanUseImplicitSuspendCheck() const {
1968   // Use implicit suspend checks if requested in compiler options unless there are SIMD
1969   // instructions in the graph. The implicit suspend check saves all FP registers as
1970   // 64-bit (in line with the calling convention) but SIMD instructions can use 128-bit
1971   // registers, so they need to be saved in an explicit slow path.
1972   return GetCompilerOptions().GetImplicitSuspendChecks() && !GetGraph()->HasSIMD();
1973 }
1974 
GenerateSuspendCheck(HSuspendCheck * instruction,HBasicBlock * successor)1975 void InstructionCodeGeneratorARM64::GenerateSuspendCheck(HSuspendCheck* instruction,
1976                                                          HBasicBlock* successor) {
1977   if (codegen_->CanUseImplicitSuspendCheck()) {
1978     __ Ldr(kImplicitSuspendCheckRegister, MemOperand(kImplicitSuspendCheckRegister));
1979     codegen_->RecordPcInfo(instruction, instruction->GetDexPc());
1980     if (successor != nullptr) {
1981       __ B(codegen_->GetLabelOf(successor));
1982     }
1983     return;
1984   }
1985 
1986   SuspendCheckSlowPathARM64* slow_path =
1987       down_cast<SuspendCheckSlowPathARM64*>(instruction->GetSlowPath());
1988   if (slow_path == nullptr) {
1989     slow_path =
1990         new (codegen_->GetScopedAllocator()) SuspendCheckSlowPathARM64(instruction, successor);
1991     instruction->SetSlowPath(slow_path);
1992     codegen_->AddSlowPath(slow_path);
1993     if (successor != nullptr) {
1994       DCHECK(successor->IsLoopHeader());
1995     }
1996   } else {
1997     DCHECK_EQ(slow_path->GetSuccessor(), successor);
1998   }
1999 
2000   UseScratchRegisterScope temps(codegen_->GetVIXLAssembler());
2001   Register temp = temps.AcquireW();
2002 
2003   __ Ldr(temp, MemOperand(tr, Thread::ThreadFlagsOffset<kArm64PointerSize>().SizeValue()));
2004   __ Tst(temp, Thread::SuspendOrCheckpointRequestFlags());
2005   if (successor == nullptr) {
2006     __ B(ne, slow_path->GetEntryLabel());
2007     __ Bind(slow_path->GetReturnLabel());
2008   } else {
2009     __ B(eq, codegen_->GetLabelOf(successor));
2010     __ B(slow_path->GetEntryLabel());
2011     // slow_path will return to GetLabelOf(successor).
2012   }
2013 }
2014 
InstructionCodeGeneratorARM64(HGraph * graph,CodeGeneratorARM64 * codegen)2015 InstructionCodeGeneratorARM64::InstructionCodeGeneratorARM64(HGraph* graph,
2016                                                              CodeGeneratorARM64* codegen)
2017       : InstructionCodeGenerator(graph, codegen),
2018         assembler_(codegen->GetAssembler()),
2019         codegen_(codegen) {}
2020 
HandleBinaryOp(HBinaryOperation * instr)2021 void LocationsBuilderARM64::HandleBinaryOp(HBinaryOperation* instr) {
2022   DCHECK_EQ(instr->InputCount(), 2U);
2023   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instr);
2024   DataType::Type type = instr->GetResultType();
2025   switch (type) {
2026     case DataType::Type::kInt32:
2027     case DataType::Type::kInt64:
2028       locations->SetInAt(0, Location::RequiresRegister());
2029       locations->SetInAt(1, ARM64EncodableConstantOrRegister(instr->InputAt(1), instr));
2030       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2031       break;
2032 
2033     case DataType::Type::kFloat32:
2034     case DataType::Type::kFloat64:
2035       locations->SetInAt(0, Location::RequiresFpuRegister());
2036       locations->SetInAt(1, Location::RequiresFpuRegister());
2037       locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
2038       break;
2039 
2040     default:
2041       LOG(FATAL) << "Unexpected " << instr->DebugName() << " type " << type;
2042   }
2043 }
2044 
HandleFieldGet(HInstruction * instruction,const FieldInfo & field_info)2045 void LocationsBuilderARM64::HandleFieldGet(HInstruction* instruction,
2046                                            const FieldInfo& field_info) {
2047   DCHECK(instruction->IsInstanceFieldGet() ||
2048          instruction->IsStaticFieldGet() ||
2049          instruction->IsPredicatedInstanceFieldGet());
2050 
2051   bool is_predicated = instruction->IsPredicatedInstanceFieldGet();
2052 
2053   bool object_field_get_with_read_barrier =
2054       kEmitCompilerReadBarrier && (instruction->GetType() == DataType::Type::kReference);
2055   LocationSummary* locations =
2056       new (GetGraph()->GetAllocator()) LocationSummary(instruction,
2057                                                        object_field_get_with_read_barrier
2058                                                            ? LocationSummary::kCallOnSlowPath
2059                                                            : LocationSummary::kNoCall);
2060   if (object_field_get_with_read_barrier && kUseBakerReadBarrier) {
2061     locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty());  // No caller-save registers.
2062     // We need a temporary register for the read barrier load in
2063     // CodeGeneratorARM64::GenerateFieldLoadWithBakerReadBarrier()
2064     // only if the field is volatile or the offset is too big.
2065     if (field_info.IsVolatile() ||
2066         field_info.GetFieldOffset().Uint32Value() >= kReferenceLoadMinFarOffset) {
2067       locations->AddTemp(FixedTempLocation());
2068     }
2069   }
2070   // Input for object receiver.
2071   locations->SetInAt(is_predicated ? 1 : 0, Location::RequiresRegister());
2072   if (DataType::IsFloatingPointType(instruction->GetType())) {
2073     if (is_predicated) {
2074       locations->SetInAt(0, Location::RequiresFpuRegister());
2075       locations->SetOut(Location::SameAsFirstInput());
2076     } else {
2077       locations->SetOut(Location::RequiresFpuRegister());
2078     }
2079   } else {
2080     if (is_predicated) {
2081       locations->SetInAt(0, Location::RequiresRegister());
2082       locations->SetOut(Location::SameAsFirstInput());
2083     } else {
2084       // The output overlaps for an object field get when read barriers
2085       // are enabled: we do not want the load to overwrite the object's
2086       // location, as we need it to emit the read barrier.
2087       locations->SetOut(Location::RequiresRegister(),
2088                         object_field_get_with_read_barrier ? Location::kOutputOverlap
2089                                                            : Location::kNoOutputOverlap);
2090     }
2091   }
2092 }
2093 
HandleFieldGet(HInstruction * instruction,const FieldInfo & field_info)2094 void InstructionCodeGeneratorARM64::HandleFieldGet(HInstruction* instruction,
2095                                                    const FieldInfo& field_info) {
2096   DCHECK(instruction->IsInstanceFieldGet() ||
2097          instruction->IsStaticFieldGet() ||
2098          instruction->IsPredicatedInstanceFieldGet());
2099   bool is_predicated = instruction->IsPredicatedInstanceFieldGet();
2100   LocationSummary* locations = instruction->GetLocations();
2101   uint32_t receiver_input = is_predicated ? 1 : 0;
2102   Location base_loc = locations->InAt(receiver_input);
2103   Location out = locations->Out();
2104   uint32_t offset = field_info.GetFieldOffset().Uint32Value();
2105   DCHECK_EQ(DataType::Size(field_info.GetFieldType()), DataType::Size(instruction->GetType()));
2106   DataType::Type load_type = instruction->GetType();
2107   MemOperand field =
2108       HeapOperand(InputRegisterAt(instruction, receiver_input), field_info.GetFieldOffset());
2109 
2110   if (kEmitCompilerReadBarrier && kUseBakerReadBarrier &&
2111       load_type == DataType::Type::kReference) {
2112     // Object FieldGet with Baker's read barrier case.
2113     // /* HeapReference<Object> */ out = *(base + offset)
2114     Register base = RegisterFrom(base_loc, DataType::Type::kReference);
2115     Location maybe_temp =
2116         (locations->GetTempCount() != 0) ? locations->GetTemp(0) : Location::NoLocation();
2117     // Note that potential implicit null checks are handled in this
2118     // CodeGeneratorARM64::GenerateFieldLoadWithBakerReadBarrier call.
2119     codegen_->GenerateFieldLoadWithBakerReadBarrier(
2120         instruction,
2121         out,
2122         base,
2123         offset,
2124         maybe_temp,
2125         /* needs_null_check= */ true,
2126         field_info.IsVolatile());
2127   } else {
2128     // General case.
2129     if (field_info.IsVolatile()) {
2130       // Note that a potential implicit null check is handled in this
2131       // CodeGeneratorARM64::LoadAcquire call.
2132       // NB: LoadAcquire will record the pc info if needed.
2133       codegen_->LoadAcquire(instruction,
2134                             load_type,
2135                             OutputCPURegister(instruction),
2136                             field,
2137                             /* needs_null_check= */ true);
2138     } else {
2139       // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
2140       EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2141       codegen_->Load(load_type, OutputCPURegister(instruction), field);
2142       codegen_->MaybeRecordImplicitNullCheck(instruction);
2143     }
2144     if (load_type == DataType::Type::kReference) {
2145       // If read barriers are enabled, emit read barriers other than
2146       // Baker's using a slow path (and also unpoison the loaded
2147       // reference, if heap poisoning is enabled).
2148       codegen_->MaybeGenerateReadBarrierSlow(instruction, out, out, base_loc, offset);
2149     }
2150   }
2151 }
2152 
HandleFieldSet(HInstruction * instruction)2153 void LocationsBuilderARM64::HandleFieldSet(HInstruction* instruction) {
2154   LocationSummary* locations =
2155       new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
2156   locations->SetInAt(0, Location::RequiresRegister());
2157   if (IsConstantZeroBitPattern(instruction->InputAt(1))) {
2158     locations->SetInAt(1, Location::ConstantLocation(instruction->InputAt(1)->AsConstant()));
2159   } else if (DataType::IsFloatingPointType(instruction->InputAt(1)->GetType())) {
2160     locations->SetInAt(1, Location::RequiresFpuRegister());
2161   } else {
2162     locations->SetInAt(1, Location::RequiresRegister());
2163   }
2164 }
2165 
HandleFieldSet(HInstruction * instruction,const FieldInfo & field_info,bool value_can_be_null)2166 void InstructionCodeGeneratorARM64::HandleFieldSet(HInstruction* instruction,
2167                                                    const FieldInfo& field_info,
2168                                                    bool value_can_be_null) {
2169   DCHECK(instruction->IsInstanceFieldSet() || instruction->IsStaticFieldSet());
2170   bool is_predicated =
2171       instruction->IsInstanceFieldSet() && instruction->AsInstanceFieldSet()->GetIsPredicatedSet();
2172 
2173   Register obj = InputRegisterAt(instruction, 0);
2174   CPURegister value = InputCPURegisterOrZeroRegAt(instruction, 1);
2175   CPURegister source = value;
2176   Offset offset = field_info.GetFieldOffset();
2177   DataType::Type field_type = field_info.GetFieldType();
2178   std::optional<vixl::aarch64::Label> pred_is_null;
2179   if (is_predicated) {
2180     pred_is_null.emplace();
2181     __ Cbz(obj, &*pred_is_null);
2182   }
2183 
2184   {
2185     // We use a block to end the scratch scope before the write barrier, thus
2186     // freeing the temporary registers so they can be used in `MarkGCCard`.
2187     UseScratchRegisterScope temps(GetVIXLAssembler());
2188 
2189     if (kPoisonHeapReferences && field_type == DataType::Type::kReference) {
2190       DCHECK(value.IsW());
2191       Register temp = temps.AcquireW();
2192       __ Mov(temp, value.W());
2193       GetAssembler()->PoisonHeapReference(temp.W());
2194       source = temp;
2195     }
2196 
2197     if (field_info.IsVolatile()) {
2198       codegen_->StoreRelease(
2199           instruction, field_type, source, HeapOperand(obj, offset), /* needs_null_check= */ true);
2200     } else {
2201       // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
2202       EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2203       codegen_->Store(field_type, source, HeapOperand(obj, offset));
2204       codegen_->MaybeRecordImplicitNullCheck(instruction);
2205     }
2206   }
2207 
2208   if (CodeGenerator::StoreNeedsWriteBarrier(field_type, instruction->InputAt(1))) {
2209     codegen_->MarkGCCard(obj, Register(value), value_can_be_null);
2210   }
2211 
2212   if (is_predicated) {
2213     __ Bind(&*pred_is_null);
2214   }
2215 }
2216 
HandleBinaryOp(HBinaryOperation * instr)2217 void InstructionCodeGeneratorARM64::HandleBinaryOp(HBinaryOperation* instr) {
2218   DataType::Type type = instr->GetType();
2219 
2220   switch (type) {
2221     case DataType::Type::kInt32:
2222     case DataType::Type::kInt64: {
2223       Register dst = OutputRegister(instr);
2224       Register lhs = InputRegisterAt(instr, 0);
2225       Operand rhs = InputOperandAt(instr, 1);
2226       if (instr->IsAdd()) {
2227         __ Add(dst, lhs, rhs);
2228       } else if (instr->IsAnd()) {
2229         __ And(dst, lhs, rhs);
2230       } else if (instr->IsOr()) {
2231         __ Orr(dst, lhs, rhs);
2232       } else if (instr->IsSub()) {
2233         __ Sub(dst, lhs, rhs);
2234       } else if (instr->IsRor()) {
2235         if (rhs.IsImmediate()) {
2236           uint32_t shift = rhs.GetImmediate() & (lhs.GetSizeInBits() - 1);
2237           __ Ror(dst, lhs, shift);
2238         } else {
2239           // Ensure shift distance is in the same size register as the result. If
2240           // we are rotating a long and the shift comes in a w register originally,
2241           // we don't need to sxtw for use as an x since the shift distances are
2242           // all & reg_bits - 1.
2243           __ Ror(dst, lhs, RegisterFrom(instr->GetLocations()->InAt(1), type));
2244         }
2245       } else if (instr->IsMin() || instr->IsMax()) {
2246           __ Cmp(lhs, rhs);
2247           __ Csel(dst, lhs, rhs, instr->IsMin() ? lt : gt);
2248       } else {
2249         DCHECK(instr->IsXor());
2250         __ Eor(dst, lhs, rhs);
2251       }
2252       break;
2253     }
2254     case DataType::Type::kFloat32:
2255     case DataType::Type::kFloat64: {
2256       VRegister dst = OutputFPRegister(instr);
2257       VRegister lhs = InputFPRegisterAt(instr, 0);
2258       VRegister rhs = InputFPRegisterAt(instr, 1);
2259       if (instr->IsAdd()) {
2260         __ Fadd(dst, lhs, rhs);
2261       } else if (instr->IsSub()) {
2262         __ Fsub(dst, lhs, rhs);
2263       } else if (instr->IsMin()) {
2264         __ Fmin(dst, lhs, rhs);
2265       } else if (instr->IsMax()) {
2266         __ Fmax(dst, lhs, rhs);
2267       } else {
2268         LOG(FATAL) << "Unexpected floating-point binary operation";
2269       }
2270       break;
2271     }
2272     default:
2273       LOG(FATAL) << "Unexpected binary operation type " << type;
2274   }
2275 }
2276 
HandleShift(HBinaryOperation * instr)2277 void LocationsBuilderARM64::HandleShift(HBinaryOperation* instr) {
2278   DCHECK(instr->IsShl() || instr->IsShr() || instr->IsUShr());
2279 
2280   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instr);
2281   DataType::Type type = instr->GetResultType();
2282   switch (type) {
2283     case DataType::Type::kInt32:
2284     case DataType::Type::kInt64: {
2285       locations->SetInAt(0, Location::RequiresRegister());
2286       locations->SetInAt(1, Location::RegisterOrConstant(instr->InputAt(1)));
2287       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2288       break;
2289     }
2290     default:
2291       LOG(FATAL) << "Unexpected shift type " << type;
2292   }
2293 }
2294 
HandleShift(HBinaryOperation * instr)2295 void InstructionCodeGeneratorARM64::HandleShift(HBinaryOperation* instr) {
2296   DCHECK(instr->IsShl() || instr->IsShr() || instr->IsUShr());
2297 
2298   DataType::Type type = instr->GetType();
2299   switch (type) {
2300     case DataType::Type::kInt32:
2301     case DataType::Type::kInt64: {
2302       Register dst = OutputRegister(instr);
2303       Register lhs = InputRegisterAt(instr, 0);
2304       Operand rhs = InputOperandAt(instr, 1);
2305       if (rhs.IsImmediate()) {
2306         uint32_t shift_value = rhs.GetImmediate() &
2307             (type == DataType::Type::kInt32 ? kMaxIntShiftDistance : kMaxLongShiftDistance);
2308         if (instr->IsShl()) {
2309           __ Lsl(dst, lhs, shift_value);
2310         } else if (instr->IsShr()) {
2311           __ Asr(dst, lhs, shift_value);
2312         } else {
2313           __ Lsr(dst, lhs, shift_value);
2314         }
2315       } else {
2316         Register rhs_reg = dst.IsX() ? rhs.GetRegister().X() : rhs.GetRegister().W();
2317 
2318         if (instr->IsShl()) {
2319           __ Lsl(dst, lhs, rhs_reg);
2320         } else if (instr->IsShr()) {
2321           __ Asr(dst, lhs, rhs_reg);
2322         } else {
2323           __ Lsr(dst, lhs, rhs_reg);
2324         }
2325       }
2326       break;
2327     }
2328     default:
2329       LOG(FATAL) << "Unexpected shift operation type " << type;
2330   }
2331 }
2332 
VisitAdd(HAdd * instruction)2333 void LocationsBuilderARM64::VisitAdd(HAdd* instruction) {
2334   HandleBinaryOp(instruction);
2335 }
2336 
VisitAdd(HAdd * instruction)2337 void InstructionCodeGeneratorARM64::VisitAdd(HAdd* instruction) {
2338   HandleBinaryOp(instruction);
2339 }
2340 
VisitAnd(HAnd * instruction)2341 void LocationsBuilderARM64::VisitAnd(HAnd* instruction) {
2342   HandleBinaryOp(instruction);
2343 }
2344 
VisitAnd(HAnd * instruction)2345 void InstructionCodeGeneratorARM64::VisitAnd(HAnd* instruction) {
2346   HandleBinaryOp(instruction);
2347 }
2348 
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instr)2349 void LocationsBuilderARM64::VisitBitwiseNegatedRight(HBitwiseNegatedRight* instr) {
2350   DCHECK(DataType::IsIntegralType(instr->GetType())) << instr->GetType();
2351   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instr);
2352   locations->SetInAt(0, Location::RequiresRegister());
2353   // There is no immediate variant of negated bitwise instructions in AArch64.
2354   locations->SetInAt(1, Location::RequiresRegister());
2355   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2356 }
2357 
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instr)2358 void InstructionCodeGeneratorARM64::VisitBitwiseNegatedRight(HBitwiseNegatedRight* instr) {
2359   Register dst = OutputRegister(instr);
2360   Register lhs = InputRegisterAt(instr, 0);
2361   Register rhs = InputRegisterAt(instr, 1);
2362 
2363   switch (instr->GetOpKind()) {
2364     case HInstruction::kAnd:
2365       __ Bic(dst, lhs, rhs);
2366       break;
2367     case HInstruction::kOr:
2368       __ Orn(dst, lhs, rhs);
2369       break;
2370     case HInstruction::kXor:
2371       __ Eon(dst, lhs, rhs);
2372       break;
2373     default:
2374       LOG(FATAL) << "Unreachable";
2375   }
2376 }
2377 
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)2378 void LocationsBuilderARM64::VisitDataProcWithShifterOp(
2379     HDataProcWithShifterOp* instruction) {
2380   DCHECK(instruction->GetType() == DataType::Type::kInt32 ||
2381          instruction->GetType() == DataType::Type::kInt64);
2382   LocationSummary* locations =
2383       new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
2384   if (instruction->GetInstrKind() == HInstruction::kNeg) {
2385     locations->SetInAt(0, Location::ConstantLocation(instruction->InputAt(0)->AsConstant()));
2386   } else {
2387     locations->SetInAt(0, Location::RequiresRegister());
2388   }
2389   locations->SetInAt(1, Location::RequiresRegister());
2390   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2391 }
2392 
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)2393 void InstructionCodeGeneratorARM64::VisitDataProcWithShifterOp(
2394     HDataProcWithShifterOp* instruction) {
2395   DataType::Type type = instruction->GetType();
2396   HInstruction::InstructionKind kind = instruction->GetInstrKind();
2397   DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
2398   Register out = OutputRegister(instruction);
2399   Register left;
2400   if (kind != HInstruction::kNeg) {
2401     left = InputRegisterAt(instruction, 0);
2402   }
2403   // If this `HDataProcWithShifterOp` was created by merging a type conversion as the
2404   // shifter operand operation, the IR generating `right_reg` (input to the type
2405   // conversion) can have a different type from the current instruction's type,
2406   // so we manually indicate the type.
2407   Register right_reg = RegisterFrom(instruction->GetLocations()->InAt(1), type);
2408   Operand right_operand(0);
2409 
2410   HDataProcWithShifterOp::OpKind op_kind = instruction->GetOpKind();
2411   if (HDataProcWithShifterOp::IsExtensionOp(op_kind)) {
2412     right_operand = Operand(right_reg, helpers::ExtendFromOpKind(op_kind));
2413   } else {
2414     right_operand = Operand(right_reg,
2415                             helpers::ShiftFromOpKind(op_kind),
2416                             instruction->GetShiftAmount());
2417   }
2418 
2419   // Logical binary operations do not support extension operations in the
2420   // operand. Note that VIXL would still manage if it was passed by generating
2421   // the extension as a separate instruction.
2422   // `HNeg` also does not support extension. See comments in `ShifterOperandSupportsExtension()`.
2423   DCHECK_IMPLIES(right_operand.IsExtendedRegister(),
2424                  kind != HInstruction::kAnd && kind != HInstruction::kOr &&
2425                      kind != HInstruction::kXor && kind != HInstruction::kNeg);
2426   switch (kind) {
2427     case HInstruction::kAdd:
2428       __ Add(out, left, right_operand);
2429       break;
2430     case HInstruction::kAnd:
2431       __ And(out, left, right_operand);
2432       break;
2433     case HInstruction::kNeg:
2434       DCHECK(instruction->InputAt(0)->AsConstant()->IsArithmeticZero());
2435       __ Neg(out, right_operand);
2436       break;
2437     case HInstruction::kOr:
2438       __ Orr(out, left, right_operand);
2439       break;
2440     case HInstruction::kSub:
2441       __ Sub(out, left, right_operand);
2442       break;
2443     case HInstruction::kXor:
2444       __ Eor(out, left, right_operand);
2445       break;
2446     default:
2447       LOG(FATAL) << "Unexpected operation kind: " << kind;
2448       UNREACHABLE();
2449   }
2450 }
2451 
VisitIntermediateAddress(HIntermediateAddress * instruction)2452 void LocationsBuilderARM64::VisitIntermediateAddress(HIntermediateAddress* instruction) {
2453   LocationSummary* locations =
2454       new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
2455   locations->SetInAt(0, Location::RequiresRegister());
2456   locations->SetInAt(1, ARM64EncodableConstantOrRegister(instruction->GetOffset(), instruction));
2457   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2458 }
2459 
VisitIntermediateAddress(HIntermediateAddress * instruction)2460 void InstructionCodeGeneratorARM64::VisitIntermediateAddress(HIntermediateAddress* instruction) {
2461   __ Add(OutputRegister(instruction),
2462          InputRegisterAt(instruction, 0),
2463          Operand(InputOperandAt(instruction, 1)));
2464 }
2465 
VisitIntermediateAddressIndex(HIntermediateAddressIndex * instruction)2466 void LocationsBuilderARM64::VisitIntermediateAddressIndex(HIntermediateAddressIndex* instruction) {
2467   LocationSummary* locations =
2468       new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
2469 
2470   HIntConstant* shift = instruction->GetShift()->AsIntConstant();
2471 
2472   locations->SetInAt(0, Location::RequiresRegister());
2473   // For byte case we don't need to shift the index variable so we can encode the data offset into
2474   // ADD instruction. For other cases we prefer the data_offset to be in register; that will hoist
2475   // data offset constant generation out of the loop and reduce the critical path length in the
2476   // loop.
2477   locations->SetInAt(1, shift->GetValue() == 0
2478                         ? Location::ConstantLocation(instruction->GetOffset()->AsIntConstant())
2479                         : Location::RequiresRegister());
2480   locations->SetInAt(2, Location::ConstantLocation(shift));
2481   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2482 }
2483 
VisitIntermediateAddressIndex(HIntermediateAddressIndex * instruction)2484 void InstructionCodeGeneratorARM64::VisitIntermediateAddressIndex(
2485     HIntermediateAddressIndex* instruction) {
2486   Register index_reg = InputRegisterAt(instruction, 0);
2487   uint32_t shift = Int64FromLocation(instruction->GetLocations()->InAt(2));
2488   uint32_t offset = instruction->GetOffset()->AsIntConstant()->GetValue();
2489 
2490   if (shift == 0) {
2491     __ Add(OutputRegister(instruction), index_reg, offset);
2492   } else {
2493     Register offset_reg = InputRegisterAt(instruction, 1);
2494     __ Add(OutputRegister(instruction), offset_reg, Operand(index_reg, LSL, shift));
2495   }
2496 }
2497 
VisitMultiplyAccumulate(HMultiplyAccumulate * instr)2498 void LocationsBuilderARM64::VisitMultiplyAccumulate(HMultiplyAccumulate* instr) {
2499   LocationSummary* locations =
2500       new (GetGraph()->GetAllocator()) LocationSummary(instr, LocationSummary::kNoCall);
2501   HInstruction* accumulator = instr->InputAt(HMultiplyAccumulate::kInputAccumulatorIndex);
2502   if (instr->GetOpKind() == HInstruction::kSub &&
2503       accumulator->IsConstant() &&
2504       accumulator->AsConstant()->IsArithmeticZero()) {
2505     // Don't allocate register for Mneg instruction.
2506   } else {
2507     locations->SetInAt(HMultiplyAccumulate::kInputAccumulatorIndex,
2508                        Location::RequiresRegister());
2509   }
2510   locations->SetInAt(HMultiplyAccumulate::kInputMulLeftIndex, Location::RequiresRegister());
2511   locations->SetInAt(HMultiplyAccumulate::kInputMulRightIndex, Location::RequiresRegister());
2512   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2513 }
2514 
VisitMultiplyAccumulate(HMultiplyAccumulate * instr)2515 void InstructionCodeGeneratorARM64::VisitMultiplyAccumulate(HMultiplyAccumulate* instr) {
2516   Register res = OutputRegister(instr);
2517   Register mul_left = InputRegisterAt(instr, HMultiplyAccumulate::kInputMulLeftIndex);
2518   Register mul_right = InputRegisterAt(instr, HMultiplyAccumulate::kInputMulRightIndex);
2519 
2520   // Avoid emitting code that could trigger Cortex A53's erratum 835769.
2521   // This fixup should be carried out for all multiply-accumulate instructions:
2522   // madd, msub, smaddl, smsubl, umaddl and umsubl.
2523   if (instr->GetType() == DataType::Type::kInt64 &&
2524       codegen_->GetInstructionSetFeatures().NeedFixCortexA53_835769()) {
2525     MacroAssembler* masm = down_cast<CodeGeneratorARM64*>(codegen_)->GetVIXLAssembler();
2526     ptrdiff_t off = masm->GetCursorOffset();
2527     if (off >= static_cast<ptrdiff_t>(kInstructionSize) &&
2528         masm->GetInstructionAt(off - static_cast<ptrdiff_t>(kInstructionSize))->IsLoadOrStore()) {
2529       // Make sure we emit only exactly one nop.
2530       ExactAssemblyScope scope(masm, kInstructionSize, CodeBufferCheckScope::kExactSize);
2531       __ nop();
2532     }
2533   }
2534 
2535   if (instr->GetOpKind() == HInstruction::kAdd) {
2536     Register accumulator = InputRegisterAt(instr, HMultiplyAccumulate::kInputAccumulatorIndex);
2537     __ Madd(res, mul_left, mul_right, accumulator);
2538   } else {
2539     DCHECK(instr->GetOpKind() == HInstruction::kSub);
2540     HInstruction* accum_instr = instr->InputAt(HMultiplyAccumulate::kInputAccumulatorIndex);
2541     if (accum_instr->IsConstant() && accum_instr->AsConstant()->IsArithmeticZero()) {
2542       __ Mneg(res, mul_left, mul_right);
2543     } else {
2544       Register accumulator = InputRegisterAt(instr, HMultiplyAccumulate::kInputAccumulatorIndex);
2545       __ Msub(res, mul_left, mul_right, accumulator);
2546     }
2547   }
2548 }
2549 
VisitArrayGet(HArrayGet * instruction)2550 void LocationsBuilderARM64::VisitArrayGet(HArrayGet* instruction) {
2551   bool object_array_get_with_read_barrier =
2552       kEmitCompilerReadBarrier && (instruction->GetType() == DataType::Type::kReference);
2553   LocationSummary* locations =
2554       new (GetGraph()->GetAllocator()) LocationSummary(instruction,
2555                                                        object_array_get_with_read_barrier
2556                                                            ? LocationSummary::kCallOnSlowPath
2557                                                            : LocationSummary::kNoCall);
2558   if (object_array_get_with_read_barrier && kUseBakerReadBarrier) {
2559     locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty());  // No caller-save registers.
2560     if (instruction->GetIndex()->IsConstant()) {
2561       // Array loads with constant index are treated as field loads.
2562       // We need a temporary register for the read barrier load in
2563       // CodeGeneratorARM64::GenerateFieldLoadWithBakerReadBarrier()
2564       // only if the offset is too big.
2565       uint32_t offset = CodeGenerator::GetArrayDataOffset(instruction);
2566       uint32_t index = instruction->GetIndex()->AsIntConstant()->GetValue();
2567       offset += index << DataType::SizeShift(DataType::Type::kReference);
2568       if (offset >= kReferenceLoadMinFarOffset) {
2569         locations->AddTemp(FixedTempLocation());
2570       }
2571     } else if (!instruction->GetArray()->IsIntermediateAddress()) {
2572       // We need a non-scratch temporary for the array data pointer in
2573       // CodeGeneratorARM64::GenerateArrayLoadWithBakerReadBarrier() for the case with no
2574       // intermediate address.
2575       locations->AddTemp(Location::RequiresRegister());
2576     }
2577   }
2578   locations->SetInAt(0, Location::RequiresRegister());
2579   locations->SetInAt(1, Location::RegisterOrConstant(instruction->InputAt(1)));
2580   if (DataType::IsFloatingPointType(instruction->GetType())) {
2581     locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
2582   } else {
2583     // The output overlaps in the case of an object array get with
2584     // read barriers enabled: we do not want the move to overwrite the
2585     // array's location, as we need it to emit the read barrier.
2586     locations->SetOut(
2587         Location::RequiresRegister(),
2588         object_array_get_with_read_barrier ? Location::kOutputOverlap : Location::kNoOutputOverlap);
2589   }
2590 }
2591 
VisitArrayGet(HArrayGet * instruction)2592 void InstructionCodeGeneratorARM64::VisitArrayGet(HArrayGet* instruction) {
2593   DataType::Type type = instruction->GetType();
2594   Register obj = InputRegisterAt(instruction, 0);
2595   LocationSummary* locations = instruction->GetLocations();
2596   Location index = locations->InAt(1);
2597   Location out = locations->Out();
2598   uint32_t offset = CodeGenerator::GetArrayDataOffset(instruction);
2599   const bool maybe_compressed_char_at = mirror::kUseStringCompression &&
2600                                         instruction->IsStringCharAt();
2601   MacroAssembler* masm = GetVIXLAssembler();
2602   UseScratchRegisterScope temps(masm);
2603 
2604   // The non-Baker read barrier instrumentation of object ArrayGet instructions
2605   // does not support the HIntermediateAddress instruction.
2606   DCHECK(!((type == DataType::Type::kReference) &&
2607            instruction->GetArray()->IsIntermediateAddress() &&
2608            kEmitCompilerReadBarrier &&
2609            !kUseBakerReadBarrier));
2610 
2611   if (type == DataType::Type::kReference && kEmitCompilerReadBarrier && kUseBakerReadBarrier) {
2612     // Object ArrayGet with Baker's read barrier case.
2613     // Note that a potential implicit null check is handled in the
2614     // CodeGeneratorARM64::GenerateArrayLoadWithBakerReadBarrier call.
2615     DCHECK(!instruction->CanDoImplicitNullCheckOn(instruction->InputAt(0)));
2616     if (index.IsConstant()) {
2617       DCHECK(!instruction->GetArray()->IsIntermediateAddress());
2618       // Array load with a constant index can be treated as a field load.
2619       offset += Int64FromLocation(index) << DataType::SizeShift(type);
2620       Location maybe_temp =
2621           (locations->GetTempCount() != 0) ? locations->GetTemp(0) : Location::NoLocation();
2622       codegen_->GenerateFieldLoadWithBakerReadBarrier(instruction,
2623                                                       out,
2624                                                       obj.W(),
2625                                                       offset,
2626                                                       maybe_temp,
2627                                                       /* needs_null_check= */ false,
2628                                                       /* use_load_acquire= */ false);
2629     } else {
2630       codegen_->GenerateArrayLoadWithBakerReadBarrier(
2631           instruction, out, obj.W(), offset, index, /* needs_null_check= */ false);
2632     }
2633   } else {
2634     // General case.
2635     MemOperand source = HeapOperand(obj);
2636     Register length;
2637     if (maybe_compressed_char_at) {
2638       uint32_t count_offset = mirror::String::CountOffset().Uint32Value();
2639       length = temps.AcquireW();
2640       {
2641         // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
2642         EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2643 
2644         if (instruction->GetArray()->IsIntermediateAddress()) {
2645           DCHECK_LT(count_offset, offset);
2646           int64_t adjusted_offset =
2647               static_cast<int64_t>(count_offset) - static_cast<int64_t>(offset);
2648           // Note that `adjusted_offset` is negative, so this will be a LDUR.
2649           __ Ldr(length, MemOperand(obj.X(), adjusted_offset));
2650         } else {
2651           __ Ldr(length, HeapOperand(obj, count_offset));
2652         }
2653         codegen_->MaybeRecordImplicitNullCheck(instruction);
2654       }
2655     }
2656     if (index.IsConstant()) {
2657       if (maybe_compressed_char_at) {
2658         vixl::aarch64::Label uncompressed_load, done;
2659         static_assert(static_cast<uint32_t>(mirror::StringCompressionFlag::kCompressed) == 0u,
2660                       "Expecting 0=compressed, 1=uncompressed");
2661         __ Tbnz(length.W(), 0, &uncompressed_load);
2662         __ Ldrb(Register(OutputCPURegister(instruction)),
2663                 HeapOperand(obj, offset + Int64FromLocation(index)));
2664         __ B(&done);
2665         __ Bind(&uncompressed_load);
2666         __ Ldrh(Register(OutputCPURegister(instruction)),
2667                 HeapOperand(obj, offset + (Int64FromLocation(index) << 1)));
2668         __ Bind(&done);
2669       } else {
2670         offset += Int64FromLocation(index) << DataType::SizeShift(type);
2671         source = HeapOperand(obj, offset);
2672       }
2673     } else {
2674       Register temp = temps.AcquireSameSizeAs(obj);
2675       if (instruction->GetArray()->IsIntermediateAddress()) {
2676         // We do not need to compute the intermediate address from the array: the
2677         // input instruction has done it already. See the comment in
2678         // `TryExtractArrayAccessAddress()`.
2679         if (kIsDebugBuild) {
2680           HIntermediateAddress* interm_addr = instruction->GetArray()->AsIntermediateAddress();
2681           DCHECK_EQ(interm_addr->GetOffset()->AsIntConstant()->GetValueAsUint64(), offset);
2682         }
2683         temp = obj;
2684       } else {
2685         __ Add(temp, obj, offset);
2686       }
2687       if (maybe_compressed_char_at) {
2688         vixl::aarch64::Label uncompressed_load, done;
2689         static_assert(static_cast<uint32_t>(mirror::StringCompressionFlag::kCompressed) == 0u,
2690                       "Expecting 0=compressed, 1=uncompressed");
2691         __ Tbnz(length.W(), 0, &uncompressed_load);
2692         __ Ldrb(Register(OutputCPURegister(instruction)),
2693                 HeapOperand(temp, XRegisterFrom(index), LSL, 0));
2694         __ B(&done);
2695         __ Bind(&uncompressed_load);
2696         __ Ldrh(Register(OutputCPURegister(instruction)),
2697                 HeapOperand(temp, XRegisterFrom(index), LSL, 1));
2698         __ Bind(&done);
2699       } else {
2700         source = HeapOperand(temp, XRegisterFrom(index), LSL, DataType::SizeShift(type));
2701       }
2702     }
2703     if (!maybe_compressed_char_at) {
2704       // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
2705       EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2706       codegen_->Load(type, OutputCPURegister(instruction), source);
2707       codegen_->MaybeRecordImplicitNullCheck(instruction);
2708     }
2709 
2710     if (type == DataType::Type::kReference) {
2711       static_assert(
2712           sizeof(mirror::HeapReference<mirror::Object>) == sizeof(int32_t),
2713           "art::mirror::HeapReference<art::mirror::Object> and int32_t have different sizes.");
2714       Location obj_loc = locations->InAt(0);
2715       if (index.IsConstant()) {
2716         codegen_->MaybeGenerateReadBarrierSlow(instruction, out, out, obj_loc, offset);
2717       } else {
2718         codegen_->MaybeGenerateReadBarrierSlow(instruction, out, out, obj_loc, offset, index);
2719       }
2720     }
2721   }
2722 }
2723 
VisitArrayLength(HArrayLength * instruction)2724 void LocationsBuilderARM64::VisitArrayLength(HArrayLength* instruction) {
2725   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
2726   locations->SetInAt(0, Location::RequiresRegister());
2727   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
2728 }
2729 
VisitArrayLength(HArrayLength * instruction)2730 void InstructionCodeGeneratorARM64::VisitArrayLength(HArrayLength* instruction) {
2731   uint32_t offset = CodeGenerator::GetArrayLengthOffset(instruction);
2732   vixl::aarch64::Register out = OutputRegister(instruction);
2733   {
2734     // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
2735     EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2736     __ Ldr(out, HeapOperand(InputRegisterAt(instruction, 0), offset));
2737     codegen_->MaybeRecordImplicitNullCheck(instruction);
2738   }
2739   // Mask out compression flag from String's array length.
2740   if (mirror::kUseStringCompression && instruction->IsStringLength()) {
2741     __ Lsr(out.W(), out.W(), 1u);
2742   }
2743 }
2744 
VisitArraySet(HArraySet * instruction)2745 void LocationsBuilderARM64::VisitArraySet(HArraySet* instruction) {
2746   DataType::Type value_type = instruction->GetComponentType();
2747 
2748   bool needs_type_check = instruction->NeedsTypeCheck();
2749   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
2750       instruction,
2751       needs_type_check ? LocationSummary::kCallOnSlowPath : LocationSummary::kNoCall);
2752   locations->SetInAt(0, Location::RequiresRegister());
2753   locations->SetInAt(1, Location::RegisterOrConstant(instruction->InputAt(1)));
2754   if (IsConstantZeroBitPattern(instruction->InputAt(2))) {
2755     locations->SetInAt(2, Location::ConstantLocation(instruction->InputAt(2)->AsConstant()));
2756   } else if (DataType::IsFloatingPointType(value_type)) {
2757     locations->SetInAt(2, Location::RequiresFpuRegister());
2758   } else {
2759     locations->SetInAt(2, Location::RequiresRegister());
2760   }
2761 }
2762 
VisitArraySet(HArraySet * instruction)2763 void InstructionCodeGeneratorARM64::VisitArraySet(HArraySet* instruction) {
2764   DataType::Type value_type = instruction->GetComponentType();
2765   LocationSummary* locations = instruction->GetLocations();
2766   bool needs_type_check = instruction->NeedsTypeCheck();
2767   bool needs_write_barrier =
2768       CodeGenerator::StoreNeedsWriteBarrier(value_type, instruction->GetValue());
2769 
2770   Register array = InputRegisterAt(instruction, 0);
2771   CPURegister value = InputCPURegisterOrZeroRegAt(instruction, 2);
2772   CPURegister source = value;
2773   Location index = locations->InAt(1);
2774   size_t offset = mirror::Array::DataOffset(DataType::Size(value_type)).Uint32Value();
2775   MemOperand destination = HeapOperand(array);
2776   MacroAssembler* masm = GetVIXLAssembler();
2777 
2778   if (!needs_write_barrier) {
2779     DCHECK(!needs_type_check);
2780     if (index.IsConstant()) {
2781       offset += Int64FromLocation(index) << DataType::SizeShift(value_type);
2782       destination = HeapOperand(array, offset);
2783     } else {
2784       UseScratchRegisterScope temps(masm);
2785       Register temp = temps.AcquireSameSizeAs(array);
2786       if (instruction->GetArray()->IsIntermediateAddress()) {
2787         // We do not need to compute the intermediate address from the array: the
2788         // input instruction has done it already. See the comment in
2789         // `TryExtractArrayAccessAddress()`.
2790         if (kIsDebugBuild) {
2791           HIntermediateAddress* interm_addr = instruction->GetArray()->AsIntermediateAddress();
2792           DCHECK(interm_addr->GetOffset()->AsIntConstant()->GetValueAsUint64() == offset);
2793         }
2794         temp = array;
2795       } else {
2796         __ Add(temp, array, offset);
2797       }
2798       destination = HeapOperand(temp,
2799                                 XRegisterFrom(index),
2800                                 LSL,
2801                                 DataType::SizeShift(value_type));
2802     }
2803     {
2804       // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
2805       EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2806       codegen_->Store(value_type, value, destination);
2807       codegen_->MaybeRecordImplicitNullCheck(instruction);
2808     }
2809   } else {
2810     DCHECK(!instruction->GetArray()->IsIntermediateAddress());
2811 
2812     bool can_value_be_null = instruction->GetValueCanBeNull();
2813     vixl::aarch64::Label do_store;
2814     if (can_value_be_null) {
2815       __ Cbz(Register(value), &do_store);
2816     }
2817 
2818     SlowPathCodeARM64* slow_path = nullptr;
2819     if (needs_type_check) {
2820       slow_path = new (codegen_->GetScopedAllocator()) ArraySetSlowPathARM64(instruction);
2821       codegen_->AddSlowPath(slow_path);
2822 
2823       const uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
2824       const uint32_t super_offset = mirror::Class::SuperClassOffset().Int32Value();
2825       const uint32_t component_offset = mirror::Class::ComponentTypeOffset().Int32Value();
2826 
2827       UseScratchRegisterScope temps(masm);
2828       Register temp = temps.AcquireSameSizeAs(array);
2829       Register temp2 = temps.AcquireSameSizeAs(array);
2830 
2831       // Note that when Baker read barriers are enabled, the type
2832       // checks are performed without read barriers.  This is fine,
2833       // even in the case where a class object is in the from-space
2834       // after the flip, as a comparison involving such a type would
2835       // not produce a false positive; it may of course produce a
2836       // false negative, in which case we would take the ArraySet
2837       // slow path.
2838 
2839       // /* HeapReference<Class> */ temp = array->klass_
2840       {
2841         // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
2842         EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2843         __ Ldr(temp, HeapOperand(array, class_offset));
2844         codegen_->MaybeRecordImplicitNullCheck(instruction);
2845       }
2846       GetAssembler()->MaybeUnpoisonHeapReference(temp);
2847 
2848       // /* HeapReference<Class> */ temp = temp->component_type_
2849       __ Ldr(temp, HeapOperand(temp, component_offset));
2850       // /* HeapReference<Class> */ temp2 = value->klass_
2851       __ Ldr(temp2, HeapOperand(Register(value), class_offset));
2852       // If heap poisoning is enabled, no need to unpoison `temp`
2853       // nor `temp2`, as we are comparing two poisoned references.
2854       __ Cmp(temp, temp2);
2855 
2856       if (instruction->StaticTypeOfArrayIsObjectArray()) {
2857         vixl::aarch64::Label do_put;
2858         __ B(eq, &do_put);
2859         // If heap poisoning is enabled, the `temp` reference has
2860         // not been unpoisoned yet; unpoison it now.
2861         GetAssembler()->MaybeUnpoisonHeapReference(temp);
2862 
2863         // /* HeapReference<Class> */ temp = temp->super_class_
2864         __ Ldr(temp, HeapOperand(temp, super_offset));
2865         // If heap poisoning is enabled, no need to unpoison
2866         // `temp`, as we are comparing against null below.
2867         __ Cbnz(temp, slow_path->GetEntryLabel());
2868         __ Bind(&do_put);
2869       } else {
2870         __ B(ne, slow_path->GetEntryLabel());
2871       }
2872     }
2873 
2874     codegen_->MarkGCCard(array, value.W(), /* value_can_be_null= */ false);
2875 
2876     if (can_value_be_null) {
2877       DCHECK(do_store.IsLinked());
2878       __ Bind(&do_store);
2879     }
2880 
2881     UseScratchRegisterScope temps(masm);
2882     if (kPoisonHeapReferences) {
2883       Register temp_source = temps.AcquireSameSizeAs(array);
2884         DCHECK(value.IsW());
2885       __ Mov(temp_source, value.W());
2886       GetAssembler()->PoisonHeapReference(temp_source);
2887       source = temp_source;
2888     }
2889 
2890     if (index.IsConstant()) {
2891       offset += Int64FromLocation(index) << DataType::SizeShift(value_type);
2892       destination = HeapOperand(array, offset);
2893     } else {
2894       Register temp_base = temps.AcquireSameSizeAs(array);
2895       __ Add(temp_base, array, offset);
2896       destination = HeapOperand(temp_base,
2897                                 XRegisterFrom(index),
2898                                 LSL,
2899                                 DataType::SizeShift(value_type));
2900     }
2901 
2902     {
2903       // Ensure that between store and MaybeRecordImplicitNullCheck there are no pools emitted.
2904       EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
2905       __ Str(source, destination);
2906 
2907       if (can_value_be_null || !needs_type_check) {
2908         codegen_->MaybeRecordImplicitNullCheck(instruction);
2909       }
2910     }
2911 
2912     if (slow_path != nullptr) {
2913       __ Bind(slow_path->GetExitLabel());
2914     }
2915   }
2916 }
2917 
VisitBoundsCheck(HBoundsCheck * instruction)2918 void LocationsBuilderARM64::VisitBoundsCheck(HBoundsCheck* instruction) {
2919   RegisterSet caller_saves = RegisterSet::Empty();
2920   InvokeRuntimeCallingConvention calling_convention;
2921   caller_saves.Add(Location::RegisterLocation(calling_convention.GetRegisterAt(0).GetCode()));
2922   caller_saves.Add(Location::RegisterLocation(calling_convention.GetRegisterAt(1).GetCode()));
2923   LocationSummary* locations = codegen_->CreateThrowingSlowPathLocations(instruction, caller_saves);
2924 
2925   // If both index and length are constant, we can check the bounds statically and
2926   // generate code accordingly. We want to make sure we generate constant locations
2927   // in that case, regardless of whether they are encodable in the comparison or not.
2928   HInstruction* index = instruction->InputAt(0);
2929   HInstruction* length = instruction->InputAt(1);
2930   bool both_const = index->IsConstant() && length->IsConstant();
2931   locations->SetInAt(0, both_const
2932       ? Location::ConstantLocation(index->AsConstant())
2933       : ARM64EncodableConstantOrRegister(index, instruction));
2934   locations->SetInAt(1, both_const
2935       ? Location::ConstantLocation(length->AsConstant())
2936       : ARM64EncodableConstantOrRegister(length, instruction));
2937 }
2938 
VisitBoundsCheck(HBoundsCheck * instruction)2939 void InstructionCodeGeneratorARM64::VisitBoundsCheck(HBoundsCheck* instruction) {
2940   LocationSummary* locations = instruction->GetLocations();
2941   Location index_loc = locations->InAt(0);
2942   Location length_loc = locations->InAt(1);
2943 
2944   int cmp_first_input = 0;
2945   int cmp_second_input = 1;
2946   Condition cond = hs;
2947 
2948   if (index_loc.IsConstant()) {
2949     int64_t index = Int64FromLocation(index_loc);
2950     if (length_loc.IsConstant()) {
2951       int64_t length = Int64FromLocation(length_loc);
2952       if (index < 0 || index >= length) {
2953         BoundsCheckSlowPathARM64* slow_path =
2954             new (codegen_->GetScopedAllocator()) BoundsCheckSlowPathARM64(instruction);
2955         codegen_->AddSlowPath(slow_path);
2956         __ B(slow_path->GetEntryLabel());
2957       } else {
2958         // BCE will remove the bounds check if we are guaranteed to pass.
2959         // However, some optimization after BCE may have generated this, and we should not
2960         // generate a bounds check if it is a valid range.
2961       }
2962       return;
2963     }
2964     // Only the index is constant: change the order of the operands and commute the condition
2965     // so we can use an immediate constant for the index (only the second input to a cmp
2966     // instruction can be an immediate).
2967     cmp_first_input = 1;
2968     cmp_second_input = 0;
2969     cond = ls;
2970   }
2971   BoundsCheckSlowPathARM64* slow_path =
2972       new (codegen_->GetScopedAllocator()) BoundsCheckSlowPathARM64(instruction);
2973   __ Cmp(InputRegisterAt(instruction, cmp_first_input),
2974          InputOperandAt(instruction, cmp_second_input));
2975   codegen_->AddSlowPath(slow_path);
2976   __ B(slow_path->GetEntryLabel(), cond);
2977 }
2978 
VisitClinitCheck(HClinitCheck * check)2979 void LocationsBuilderARM64::VisitClinitCheck(HClinitCheck* check) {
2980   LocationSummary* locations =
2981       new (GetGraph()->GetAllocator()) LocationSummary(check, LocationSummary::kCallOnSlowPath);
2982   locations->SetInAt(0, Location::RequiresRegister());
2983   if (check->HasUses()) {
2984     locations->SetOut(Location::SameAsFirstInput());
2985   }
2986   // Rely on the type initialization to save everything we need.
2987   locations->SetCustomSlowPathCallerSaves(OneRegInReferenceOutSaveEverythingCallerSaves());
2988 }
2989 
VisitClinitCheck(HClinitCheck * check)2990 void InstructionCodeGeneratorARM64::VisitClinitCheck(HClinitCheck* check) {
2991   // We assume the class is not null.
2992   SlowPathCodeARM64* slow_path =
2993       new (codegen_->GetScopedAllocator()) LoadClassSlowPathARM64(check->GetLoadClass(), check);
2994   codegen_->AddSlowPath(slow_path);
2995   GenerateClassInitializationCheck(slow_path, InputRegisterAt(check, 0));
2996 }
2997 
IsFloatingPointZeroConstant(HInstruction * inst)2998 static bool IsFloatingPointZeroConstant(HInstruction* inst) {
2999   return (inst->IsFloatConstant() && (inst->AsFloatConstant()->IsArithmeticZero()))
3000       || (inst->IsDoubleConstant() && (inst->AsDoubleConstant()->IsArithmeticZero()));
3001 }
3002 
GenerateFcmp(HInstruction * instruction)3003 void InstructionCodeGeneratorARM64::GenerateFcmp(HInstruction* instruction) {
3004   VRegister lhs_reg = InputFPRegisterAt(instruction, 0);
3005   Location rhs_loc = instruction->GetLocations()->InAt(1);
3006   if (rhs_loc.IsConstant()) {
3007     // 0.0 is the only immediate that can be encoded directly in
3008     // an FCMP instruction.
3009     //
3010     // Both the JLS (section 15.20.1) and the JVMS (section 6.5)
3011     // specify that in a floating-point comparison, positive zero
3012     // and negative zero are considered equal, so we can use the
3013     // literal 0.0 for both cases here.
3014     //
3015     // Note however that some methods (Float.equal, Float.compare,
3016     // Float.compareTo, Double.equal, Double.compare,
3017     // Double.compareTo, Math.max, Math.min, StrictMath.max,
3018     // StrictMath.min) consider 0.0 to be (strictly) greater than
3019     // -0.0. So if we ever translate calls to these methods into a
3020     // HCompare instruction, we must handle the -0.0 case with
3021     // care here.
3022     DCHECK(IsFloatingPointZeroConstant(rhs_loc.GetConstant()));
3023     __ Fcmp(lhs_reg, 0.0);
3024   } else {
3025     __ Fcmp(lhs_reg, InputFPRegisterAt(instruction, 1));
3026   }
3027 }
3028 
VisitCompare(HCompare * compare)3029 void LocationsBuilderARM64::VisitCompare(HCompare* compare) {
3030   LocationSummary* locations =
3031       new (GetGraph()->GetAllocator()) LocationSummary(compare, LocationSummary::kNoCall);
3032   DataType::Type in_type = compare->InputAt(0)->GetType();
3033   switch (in_type) {
3034     case DataType::Type::kBool:
3035     case DataType::Type::kUint8:
3036     case DataType::Type::kInt8:
3037     case DataType::Type::kUint16:
3038     case DataType::Type::kInt16:
3039     case DataType::Type::kInt32:
3040     case DataType::Type::kInt64: {
3041       locations->SetInAt(0, Location::RequiresRegister());
3042       locations->SetInAt(1, ARM64EncodableConstantOrRegister(compare->InputAt(1), compare));
3043       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3044       break;
3045     }
3046     case DataType::Type::kFloat32:
3047     case DataType::Type::kFloat64: {
3048       locations->SetInAt(0, Location::RequiresFpuRegister());
3049       locations->SetInAt(1,
3050                          IsFloatingPointZeroConstant(compare->InputAt(1))
3051                              ? Location::ConstantLocation(compare->InputAt(1)->AsConstant())
3052                              : Location::RequiresFpuRegister());
3053       locations->SetOut(Location::RequiresRegister());
3054       break;
3055     }
3056     default:
3057       LOG(FATAL) << "Unexpected type for compare operation " << in_type;
3058   }
3059 }
3060 
VisitCompare(HCompare * compare)3061 void InstructionCodeGeneratorARM64::VisitCompare(HCompare* compare) {
3062   DataType::Type in_type = compare->InputAt(0)->GetType();
3063 
3064   //  0 if: left == right
3065   //  1 if: left  > right
3066   // -1 if: left  < right
3067   switch (in_type) {
3068     case DataType::Type::kBool:
3069     case DataType::Type::kUint8:
3070     case DataType::Type::kInt8:
3071     case DataType::Type::kUint16:
3072     case DataType::Type::kInt16:
3073     case DataType::Type::kInt32:
3074     case DataType::Type::kInt64: {
3075       Register result = OutputRegister(compare);
3076       Register left = InputRegisterAt(compare, 0);
3077       Operand right = InputOperandAt(compare, 1);
3078       __ Cmp(left, right);
3079       __ Cset(result, ne);          // result == +1 if NE or 0 otherwise
3080       __ Cneg(result, result, lt);  // result == -1 if LT or unchanged otherwise
3081       break;
3082     }
3083     case DataType::Type::kFloat32:
3084     case DataType::Type::kFloat64: {
3085       Register result = OutputRegister(compare);
3086       GenerateFcmp(compare);
3087       __ Cset(result, ne);
3088       __ Cneg(result, result, ARM64FPCondition(kCondLT, compare->IsGtBias()));
3089       break;
3090     }
3091     default:
3092       LOG(FATAL) << "Unimplemented compare type " << in_type;
3093   }
3094 }
3095 
HandleCondition(HCondition * instruction)3096 void LocationsBuilderARM64::HandleCondition(HCondition* instruction) {
3097   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
3098 
3099   if (DataType::IsFloatingPointType(instruction->InputAt(0)->GetType())) {
3100     locations->SetInAt(0, Location::RequiresFpuRegister());
3101     locations->SetInAt(1,
3102                        IsFloatingPointZeroConstant(instruction->InputAt(1))
3103                            ? Location::ConstantLocation(instruction->InputAt(1)->AsConstant())
3104                            : Location::RequiresFpuRegister());
3105   } else {
3106     // Integer cases.
3107     locations->SetInAt(0, Location::RequiresRegister());
3108     locations->SetInAt(1, ARM64EncodableConstantOrRegister(instruction->InputAt(1), instruction));
3109   }
3110 
3111   if (!instruction->IsEmittedAtUseSite()) {
3112     locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3113   }
3114 }
3115 
HandleCondition(HCondition * instruction)3116 void InstructionCodeGeneratorARM64::HandleCondition(HCondition* instruction) {
3117   if (instruction->IsEmittedAtUseSite()) {
3118     return;
3119   }
3120 
3121   LocationSummary* locations = instruction->GetLocations();
3122   Register res = RegisterFrom(locations->Out(), instruction->GetType());
3123   IfCondition if_cond = instruction->GetCondition();
3124 
3125   if (DataType::IsFloatingPointType(instruction->InputAt(0)->GetType())) {
3126     GenerateFcmp(instruction);
3127     __ Cset(res, ARM64FPCondition(if_cond, instruction->IsGtBias()));
3128   } else {
3129     // Integer cases.
3130     Register lhs = InputRegisterAt(instruction, 0);
3131     Operand rhs = InputOperandAt(instruction, 1);
3132     __ Cmp(lhs, rhs);
3133     __ Cset(res, ARM64Condition(if_cond));
3134   }
3135 }
3136 
3137 #define FOR_EACH_CONDITION_INSTRUCTION(M)                                                \
3138   M(Equal)                                                                               \
3139   M(NotEqual)                                                                            \
3140   M(LessThan)                                                                            \
3141   M(LessThanOrEqual)                                                                     \
3142   M(GreaterThan)                                                                         \
3143   M(GreaterThanOrEqual)                                                                  \
3144   M(Below)                                                                               \
3145   M(BelowOrEqual)                                                                        \
3146   M(Above)                                                                               \
3147   M(AboveOrEqual)
3148 #define DEFINE_CONDITION_VISITORS(Name)                                                  \
3149 void LocationsBuilderARM64::Visit##Name(H##Name* comp) { HandleCondition(comp); }         \
3150 void InstructionCodeGeneratorARM64::Visit##Name(H##Name* comp) { HandleCondition(comp); }
FOR_EACH_CONDITION_INSTRUCTION(DEFINE_CONDITION_VISITORS)3151 FOR_EACH_CONDITION_INSTRUCTION(DEFINE_CONDITION_VISITORS)
3152 #undef DEFINE_CONDITION_VISITORS
3153 #undef FOR_EACH_CONDITION_INSTRUCTION
3154 
3155 void InstructionCodeGeneratorARM64::GenerateIntDivForPower2Denom(HDiv* instruction) {
3156   int64_t imm = Int64FromLocation(instruction->GetLocations()->InAt(1));
3157   uint64_t abs_imm = static_cast<uint64_t>(AbsOrMin(imm));
3158   DCHECK(IsPowerOfTwo(abs_imm)) << abs_imm;
3159 
3160   Register out = OutputRegister(instruction);
3161   Register dividend = InputRegisterAt(instruction, 0);
3162 
3163   Register final_dividend;
3164   if (HasNonNegativeOrMinIntInputAt(instruction, 0)) {
3165     // No need to adjust the result for non-negative dividends or the INT32_MIN/INT64_MIN dividends.
3166     // NOTE: The generated code for HDiv correctly works for the INT32_MIN/INT64_MIN dividends:
3167     //   imm == 2
3168     //     add out, dividend(0x80000000), dividend(0x80000000), lsr #31 => out = 0x80000001
3169     //     asr out, out(0x80000001), #1 => out = 0xc0000000
3170     //     This is the same as 'asr out, 0x80000000, #1'
3171     //
3172     //   imm > 2
3173     //     add temp, dividend(0x80000000), imm - 1 => temp = 0b10..01..1, where the number
3174     //         of the rightmost 1s is ctz_imm.
3175     //     cmp dividend(0x80000000), 0 => N = 1, V = 0 (lt is true)
3176     //     csel out, temp(0b10..01..1), dividend(0x80000000), lt => out = 0b10..01..1
3177     //     asr out, out(0b10..01..1), #ctz_imm => out = 0b1..10..0, where the number of the
3178     //         leftmost 1s is ctz_imm + 1.
3179     //     This is the same as 'asr out, dividend(0x80000000), #ctz_imm'.
3180     //
3181     //   imm == INT32_MIN
3182     //     add tmp, dividend(0x80000000), #0x7fffffff => tmp = -1
3183     //     cmp dividend(0x80000000), 0 => N = 1, V = 0 (lt is true)
3184     //     csel out, temp(-1), dividend(0x80000000), lt => out = -1
3185     //     neg out, out(-1), asr #31 => out = 1
3186     //     This is the same as 'neg out, dividend(0x80000000), asr #31'.
3187     final_dividend = dividend;
3188   } else {
3189     if (abs_imm == 2) {
3190       int bits = DataType::Size(instruction->GetResultType()) * kBitsPerByte;
3191       __ Add(out, dividend, Operand(dividend, LSR, bits - 1));
3192     } else {
3193       UseScratchRegisterScope temps(GetVIXLAssembler());
3194       Register temp = temps.AcquireSameSizeAs(out);
3195       __ Add(temp, dividend, abs_imm - 1);
3196       __ Cmp(dividend, 0);
3197       __ Csel(out, temp, dividend, lt);
3198     }
3199     final_dividend = out;
3200   }
3201 
3202   int ctz_imm = CTZ(abs_imm);
3203   if (imm > 0) {
3204     __ Asr(out, final_dividend, ctz_imm);
3205   } else {
3206     __ Neg(out, Operand(final_dividend, ASR, ctz_imm));
3207   }
3208 }
3209 
3210 // Return true if the magic number was modified by subtracting 2^32(Int32 div) or 2^64(Int64 div).
3211 // So dividend needs to be added.
NeedToAddDividend(int64_t magic_number,int64_t divisor)3212 static inline bool NeedToAddDividend(int64_t magic_number, int64_t divisor) {
3213   return divisor > 0 && magic_number < 0;
3214 }
3215 
3216 // Return true if the magic number was modified by adding 2^32(Int32 div) or 2^64(Int64 div).
3217 // So dividend needs to be subtracted.
NeedToSubDividend(int64_t magic_number,int64_t divisor)3218 static inline bool NeedToSubDividend(int64_t magic_number, int64_t divisor) {
3219   return divisor < 0 && magic_number > 0;
3220 }
3221 
3222 // Generate code which increments the value in register 'in' by 1 if the value is negative.
3223 // It is done with 'add out, in, in, lsr #31 or #63'.
3224 // If the value is a result of an operation setting the N flag, CINC MI can be used
3225 // instead of ADD. 'use_cond_inc' controls this.
GenerateIncrementNegativeByOne(Register out,Register in,bool use_cond_inc)3226 void InstructionCodeGeneratorARM64::GenerateIncrementNegativeByOne(
3227     Register out,
3228     Register in,
3229     bool use_cond_inc) {
3230   if (use_cond_inc) {
3231     __ Cinc(out, in, mi);
3232   } else {
3233     __ Add(out, in, Operand(in, LSR, in.GetSizeInBits() - 1));
3234   }
3235 }
3236 
3237 // Helper to generate code producing the result of HRem with a constant divisor.
GenerateResultRemWithAnyConstant(Register out,Register dividend,Register quotient,int64_t divisor,UseScratchRegisterScope * temps_scope)3238 void InstructionCodeGeneratorARM64::GenerateResultRemWithAnyConstant(
3239     Register out,
3240     Register dividend,
3241     Register quotient,
3242     int64_t divisor,
3243     UseScratchRegisterScope* temps_scope) {
3244   Register temp_imm = temps_scope->AcquireSameSizeAs(out);
3245   __ Mov(temp_imm, divisor);
3246   __ Msub(out, quotient, temp_imm, dividend);
3247 }
3248 
3249 // Helper to generate code for HDiv/HRem instructions when a dividend is non-negative and
3250 // a divisor is a positive constant, not power of 2.
GenerateInt64UnsignedDivRemWithAnyPositiveConstant(HBinaryOperation * instruction)3251 void InstructionCodeGeneratorARM64::GenerateInt64UnsignedDivRemWithAnyPositiveConstant(
3252     HBinaryOperation* instruction) {
3253   DCHECK(instruction->IsDiv() || instruction->IsRem());
3254   DCHECK(instruction->GetResultType() == DataType::Type::kInt64);
3255 
3256   LocationSummary* locations = instruction->GetLocations();
3257   Location second = locations->InAt(1);
3258   DCHECK(second.IsConstant());
3259 
3260   Register out = OutputRegister(instruction);
3261   Register dividend = InputRegisterAt(instruction, 0);
3262   int64_t imm = Int64FromConstant(second.GetConstant());
3263   DCHECK_GT(imm, 0);
3264 
3265   int64_t magic;
3266   int shift;
3267   CalculateMagicAndShiftForDivRem(imm, /* is_long= */ true, &magic, &shift);
3268 
3269   UseScratchRegisterScope temps(GetVIXLAssembler());
3270   Register temp = temps.AcquireSameSizeAs(out);
3271 
3272   auto generate_unsigned_div_code = [this, magic, shift](Register out,
3273                                                          Register dividend,
3274                                                          Register temp) {
3275     // temp = get_high(dividend * magic)
3276     __ Mov(temp, magic);
3277     if (magic > 0 && shift == 0) {
3278       __ Smulh(out, dividend, temp);
3279     } else {
3280       __ Smulh(temp, dividend, temp);
3281       if (magic < 0) {
3282         // The negative magic means that the multiplier m is greater than INT64_MAX.
3283         // In such a case shift is never 0. See the proof in
3284         // InstructionCodeGeneratorARMVIXL::GenerateDivRemWithAnyConstant.
3285         __ Add(temp, temp, dividend);
3286       }
3287       DCHECK_NE(shift, 0);
3288       __ Lsr(out, temp, shift);
3289     }
3290   };
3291 
3292   if (instruction->IsDiv()) {
3293     generate_unsigned_div_code(out, dividend, temp);
3294   } else {
3295     generate_unsigned_div_code(temp, dividend, temp);
3296     GenerateResultRemWithAnyConstant(out, dividend, temp, imm, &temps);
3297   }
3298 }
3299 
3300 // Helper to generate code for HDiv/HRem instructions for any dividend and a constant divisor
3301 // (not power of 2).
GenerateInt64DivRemWithAnyConstant(HBinaryOperation * instruction)3302 void InstructionCodeGeneratorARM64::GenerateInt64DivRemWithAnyConstant(
3303     HBinaryOperation* instruction) {
3304   DCHECK(instruction->IsDiv() || instruction->IsRem());
3305   DCHECK(instruction->GetResultType() == DataType::Type::kInt64);
3306 
3307   LocationSummary* locations = instruction->GetLocations();
3308   Location second = locations->InAt(1);
3309   DCHECK(second.IsConstant());
3310 
3311   Register out = OutputRegister(instruction);
3312   Register dividend = InputRegisterAt(instruction, 0);
3313   int64_t imm = Int64FromConstant(second.GetConstant());
3314 
3315   int64_t magic;
3316   int shift;
3317   CalculateMagicAndShiftForDivRem(imm, /* is_long= */ true, &magic, &shift);
3318 
3319   UseScratchRegisterScope temps(GetVIXLAssembler());
3320   Register temp = temps.AcquireSameSizeAs(out);
3321 
3322   // temp = get_high(dividend * magic)
3323   __ Mov(temp, magic);
3324   __ Smulh(temp, dividend, temp);
3325 
3326   // The multiplication result might need some corrections to be finalized.
3327   // The last correction is to increment by 1, if the result is negative.
3328   // Currently it is done with 'add result, temp_result, temp_result, lsr #31 or #63'.
3329   // Such ADD usually has latency 2, e.g. on Cortex-A55.
3330   // However if one of the corrections is ADD or SUB, the sign can be detected
3331   // with ADDS/SUBS. They set the N flag if the result is negative.
3332   // This allows to use CINC MI which has latency 1.
3333   bool use_cond_inc = false;
3334 
3335   // Some combinations of magic_number and the divisor require to correct the result.
3336   // Check whether the correction is needed.
3337   if (NeedToAddDividend(magic, imm)) {
3338     __ Adds(temp, temp, dividend);
3339     use_cond_inc = true;
3340   } else if (NeedToSubDividend(magic, imm)) {
3341     __ Subs(temp, temp, dividend);
3342     use_cond_inc = true;
3343   }
3344 
3345   if (shift != 0) {
3346     __ Asr(temp, temp, shift);
3347   }
3348 
3349   if (instruction->IsRem()) {
3350     GenerateIncrementNegativeByOne(temp, temp, use_cond_inc);
3351     GenerateResultRemWithAnyConstant(out, dividend, temp, imm, &temps);
3352   } else {
3353     GenerateIncrementNegativeByOne(out, temp, use_cond_inc);
3354   }
3355 }
3356 
GenerateInt32DivRemWithAnyConstant(HBinaryOperation * instruction)3357 void InstructionCodeGeneratorARM64::GenerateInt32DivRemWithAnyConstant(
3358     HBinaryOperation* instruction) {
3359   DCHECK(instruction->IsDiv() || instruction->IsRem());
3360   DCHECK(instruction->GetResultType() == DataType::Type::kInt32);
3361 
3362   LocationSummary* locations = instruction->GetLocations();
3363   Location second = locations->InAt(1);
3364   DCHECK(second.IsConstant());
3365 
3366   Register out = OutputRegister(instruction);
3367   Register dividend = InputRegisterAt(instruction, 0);
3368   int64_t imm = Int64FromConstant(second.GetConstant());
3369 
3370   int64_t magic;
3371   int shift;
3372   CalculateMagicAndShiftForDivRem(imm, /* is_long= */ false, &magic, &shift);
3373   UseScratchRegisterScope temps(GetVIXLAssembler());
3374   Register temp = temps.AcquireSameSizeAs(out);
3375 
3376   // temp = get_high(dividend * magic)
3377   __ Mov(temp, magic);
3378   __ Smull(temp.X(), dividend, temp);
3379 
3380   // The multiplication result might need some corrections to be finalized.
3381   // The last correction is to increment by 1, if the result is negative.
3382   // Currently it is done with 'add result, temp_result, temp_result, lsr #31 or #63'.
3383   // Such ADD usually has latency 2, e.g. on Cortex-A55.
3384   // However if one of the corrections is ADD or SUB, the sign can be detected
3385   // with ADDS/SUBS. They set the N flag if the result is negative.
3386   // This allows to use CINC MI which has latency 1.
3387   bool use_cond_inc = false;
3388 
3389   // ADD/SUB correction is performed in the high 32 bits
3390   // as high 32 bits are ignored because type are kInt32.
3391   if (NeedToAddDividend(magic, imm)) {
3392     __ Adds(temp.X(), temp.X(), Operand(dividend.X(), LSL, 32));
3393     use_cond_inc = true;
3394   } else if (NeedToSubDividend(magic, imm)) {
3395     __ Subs(temp.X(), temp.X(), Operand(dividend.X(), LSL, 32));
3396     use_cond_inc = true;
3397   }
3398 
3399   // Extract the result from the high 32 bits and apply the final right shift.
3400   DCHECK_LT(shift, 32);
3401   if (imm > 0 && HasNonNegativeInputAt(instruction, 0)) {
3402     // No need to adjust the result for a non-negative dividend and a positive divisor.
3403     if (instruction->IsDiv()) {
3404       __ Lsr(out.X(), temp.X(), 32 + shift);
3405     } else {
3406       __ Lsr(temp.X(), temp.X(), 32 + shift);
3407       GenerateResultRemWithAnyConstant(out, dividend, temp, imm, &temps);
3408     }
3409   } else {
3410     __ Asr(temp.X(), temp.X(), 32 + shift);
3411 
3412     if (instruction->IsRem()) {
3413       GenerateIncrementNegativeByOne(temp, temp, use_cond_inc);
3414       GenerateResultRemWithAnyConstant(out, dividend, temp, imm, &temps);
3415     } else {
3416       GenerateIncrementNegativeByOne(out, temp, use_cond_inc);
3417     }
3418   }
3419 }
3420 
GenerateDivRemWithAnyConstant(HBinaryOperation * instruction,int64_t divisor)3421 void InstructionCodeGeneratorARM64::GenerateDivRemWithAnyConstant(HBinaryOperation* instruction,
3422                                                                   int64_t divisor) {
3423   DCHECK(instruction->IsDiv() || instruction->IsRem());
3424   if (instruction->GetResultType() == DataType::Type::kInt64) {
3425     if (divisor > 0 && HasNonNegativeInputAt(instruction, 0)) {
3426       GenerateInt64UnsignedDivRemWithAnyPositiveConstant(instruction);
3427     } else {
3428       GenerateInt64DivRemWithAnyConstant(instruction);
3429     }
3430   } else {
3431     GenerateInt32DivRemWithAnyConstant(instruction);
3432   }
3433 }
3434 
GenerateIntDivForConstDenom(HDiv * instruction)3435 void InstructionCodeGeneratorARM64::GenerateIntDivForConstDenom(HDiv *instruction) {
3436   int64_t imm = Int64FromLocation(instruction->GetLocations()->InAt(1));
3437 
3438   if (imm == 0) {
3439     // Do not generate anything. DivZeroCheck would prevent any code to be executed.
3440     return;
3441   }
3442 
3443   if (IsPowerOfTwo(AbsOrMin(imm))) {
3444     GenerateIntDivForPower2Denom(instruction);
3445   } else {
3446     // Cases imm == -1 or imm == 1 are handled by InstructionSimplifier.
3447     DCHECK(imm < -2 || imm > 2) << imm;
3448     GenerateDivRemWithAnyConstant(instruction, imm);
3449   }
3450 }
3451 
GenerateIntDiv(HDiv * instruction)3452 void InstructionCodeGeneratorARM64::GenerateIntDiv(HDiv *instruction) {
3453   DCHECK(DataType::IsIntOrLongType(instruction->GetResultType()))
3454        << instruction->GetResultType();
3455 
3456   if (instruction->GetLocations()->InAt(1).IsConstant()) {
3457     GenerateIntDivForConstDenom(instruction);
3458   } else {
3459     Register out = OutputRegister(instruction);
3460     Register dividend = InputRegisterAt(instruction, 0);
3461     Register divisor = InputRegisterAt(instruction, 1);
3462     __ Sdiv(out, dividend, divisor);
3463   }
3464 }
3465 
VisitDiv(HDiv * div)3466 void LocationsBuilderARM64::VisitDiv(HDiv* div) {
3467   LocationSummary* locations =
3468       new (GetGraph()->GetAllocator()) LocationSummary(div, LocationSummary::kNoCall);
3469   switch (div->GetResultType()) {
3470     case DataType::Type::kInt32:
3471     case DataType::Type::kInt64:
3472       locations->SetInAt(0, Location::RequiresRegister());
3473       locations->SetInAt(1, Location::RegisterOrConstant(div->InputAt(1)));
3474       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3475       break;
3476 
3477     case DataType::Type::kFloat32:
3478     case DataType::Type::kFloat64:
3479       locations->SetInAt(0, Location::RequiresFpuRegister());
3480       locations->SetInAt(1, Location::RequiresFpuRegister());
3481       locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
3482       break;
3483 
3484     default:
3485       LOG(FATAL) << "Unexpected div type " << div->GetResultType();
3486   }
3487 }
3488 
VisitDiv(HDiv * div)3489 void InstructionCodeGeneratorARM64::VisitDiv(HDiv* div) {
3490   DataType::Type type = div->GetResultType();
3491   switch (type) {
3492     case DataType::Type::kInt32:
3493     case DataType::Type::kInt64:
3494       GenerateIntDiv(div);
3495       break;
3496 
3497     case DataType::Type::kFloat32:
3498     case DataType::Type::kFloat64:
3499       __ Fdiv(OutputFPRegister(div), InputFPRegisterAt(div, 0), InputFPRegisterAt(div, 1));
3500       break;
3501 
3502     default:
3503       LOG(FATAL) << "Unexpected div type " << type;
3504   }
3505 }
3506 
VisitDivZeroCheck(HDivZeroCheck * instruction)3507 void LocationsBuilderARM64::VisitDivZeroCheck(HDivZeroCheck* instruction) {
3508   LocationSummary* locations = codegen_->CreateThrowingSlowPathLocations(instruction);
3509   locations->SetInAt(0, Location::RegisterOrConstant(instruction->InputAt(0)));
3510 }
3511 
VisitDivZeroCheck(HDivZeroCheck * instruction)3512 void InstructionCodeGeneratorARM64::VisitDivZeroCheck(HDivZeroCheck* instruction) {
3513   SlowPathCodeARM64* slow_path =
3514       new (codegen_->GetScopedAllocator()) DivZeroCheckSlowPathARM64(instruction);
3515   codegen_->AddSlowPath(slow_path);
3516   Location value = instruction->GetLocations()->InAt(0);
3517 
3518   DataType::Type type = instruction->GetType();
3519 
3520   if (!DataType::IsIntegralType(type)) {
3521     LOG(FATAL) << "Unexpected type " << type << " for DivZeroCheck.";
3522     UNREACHABLE();
3523   }
3524 
3525   if (value.IsConstant()) {
3526     int64_t divisor = Int64FromLocation(value);
3527     if (divisor == 0) {
3528       __ B(slow_path->GetEntryLabel());
3529     } else {
3530       // A division by a non-null constant is valid. We don't need to perform
3531       // any check, so simply fall through.
3532     }
3533   } else {
3534     __ Cbz(InputRegisterAt(instruction, 0), slow_path->GetEntryLabel());
3535   }
3536 }
3537 
VisitDoubleConstant(HDoubleConstant * constant)3538 void LocationsBuilderARM64::VisitDoubleConstant(HDoubleConstant* constant) {
3539   LocationSummary* locations =
3540       new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3541   locations->SetOut(Location::ConstantLocation(constant));
3542 }
3543 
VisitDoubleConstant(HDoubleConstant * constant ATTRIBUTE_UNUSED)3544 void InstructionCodeGeneratorARM64::VisitDoubleConstant(
3545     HDoubleConstant* constant ATTRIBUTE_UNUSED) {
3546   // Will be generated at use site.
3547 }
3548 
VisitExit(HExit * exit)3549 void LocationsBuilderARM64::VisitExit(HExit* exit) {
3550   exit->SetLocations(nullptr);
3551 }
3552 
VisitExit(HExit * exit ATTRIBUTE_UNUSED)3553 void InstructionCodeGeneratorARM64::VisitExit(HExit* exit ATTRIBUTE_UNUSED) {
3554 }
3555 
VisitFloatConstant(HFloatConstant * constant)3556 void LocationsBuilderARM64::VisitFloatConstant(HFloatConstant* constant) {
3557   LocationSummary* locations =
3558       new (GetGraph()->GetAllocator()) LocationSummary(constant, LocationSummary::kNoCall);
3559   locations->SetOut(Location::ConstantLocation(constant));
3560 }
3561 
VisitFloatConstant(HFloatConstant * constant ATTRIBUTE_UNUSED)3562 void InstructionCodeGeneratorARM64::VisitFloatConstant(HFloatConstant* constant ATTRIBUTE_UNUSED) {
3563   // Will be generated at use site.
3564 }
3565 
HandleGoto(HInstruction * got,HBasicBlock * successor)3566 void InstructionCodeGeneratorARM64::HandleGoto(HInstruction* got, HBasicBlock* successor) {
3567   if (successor->IsExitBlock()) {
3568     DCHECK(got->GetPrevious()->AlwaysThrows());
3569     return;  // no code needed
3570   }
3571 
3572   HBasicBlock* block = got->GetBlock();
3573   HInstruction* previous = got->GetPrevious();
3574   HLoopInformation* info = block->GetLoopInformation();
3575 
3576   if (info != nullptr && info->IsBackEdge(*block) && info->HasSuspendCheck()) {
3577     codegen_->MaybeIncrementHotness(/* is_frame_entry= */ false);
3578     GenerateSuspendCheck(info->GetSuspendCheck(), successor);
3579     return;  // `GenerateSuspendCheck()` emitted the jump.
3580   }
3581   if (block->IsEntryBlock() && (previous != nullptr) && previous->IsSuspendCheck()) {
3582     GenerateSuspendCheck(previous->AsSuspendCheck(), nullptr);
3583     codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
3584   }
3585   if (!codegen_->GoesToNextBlock(block, successor)) {
3586     __ B(codegen_->GetLabelOf(successor));
3587   }
3588 }
3589 
VisitGoto(HGoto * got)3590 void LocationsBuilderARM64::VisitGoto(HGoto* got) {
3591   got->SetLocations(nullptr);
3592 }
3593 
VisitGoto(HGoto * got)3594 void InstructionCodeGeneratorARM64::VisitGoto(HGoto* got) {
3595   HandleGoto(got, got->GetSuccessor());
3596 }
3597 
VisitTryBoundary(HTryBoundary * try_boundary)3598 void LocationsBuilderARM64::VisitTryBoundary(HTryBoundary* try_boundary) {
3599   try_boundary->SetLocations(nullptr);
3600 }
3601 
VisitTryBoundary(HTryBoundary * try_boundary)3602 void InstructionCodeGeneratorARM64::VisitTryBoundary(HTryBoundary* try_boundary) {
3603   HBasicBlock* successor = try_boundary->GetNormalFlowSuccessor();
3604   if (!successor->IsExitBlock()) {
3605     HandleGoto(try_boundary, successor);
3606   }
3607 }
3608 
GenerateTestAndBranch(HInstruction * instruction,size_t condition_input_index,vixl::aarch64::Label * true_target,vixl::aarch64::Label * false_target)3609 void InstructionCodeGeneratorARM64::GenerateTestAndBranch(HInstruction* instruction,
3610                                                           size_t condition_input_index,
3611                                                           vixl::aarch64::Label* true_target,
3612                                                           vixl::aarch64::Label* false_target) {
3613   HInstruction* cond = instruction->InputAt(condition_input_index);
3614 
3615   if (true_target == nullptr && false_target == nullptr) {
3616     // Nothing to do. The code always falls through.
3617     return;
3618   } else if (cond->IsIntConstant()) {
3619     // Constant condition, statically compared against "true" (integer value 1).
3620     if (cond->AsIntConstant()->IsTrue()) {
3621       if (true_target != nullptr) {
3622         __ B(true_target);
3623       }
3624     } else {
3625       DCHECK(cond->AsIntConstant()->IsFalse()) << cond->AsIntConstant()->GetValue();
3626       if (false_target != nullptr) {
3627         __ B(false_target);
3628       }
3629     }
3630     return;
3631   }
3632 
3633   // The following code generates these patterns:
3634   //  (1) true_target == nullptr && false_target != nullptr
3635   //        - opposite condition true => branch to false_target
3636   //  (2) true_target != nullptr && false_target == nullptr
3637   //        - condition true => branch to true_target
3638   //  (3) true_target != nullptr && false_target != nullptr
3639   //        - condition true => branch to true_target
3640   //        - branch to false_target
3641   if (IsBooleanValueOrMaterializedCondition(cond)) {
3642     // The condition instruction has been materialized, compare the output to 0.
3643     Location cond_val = instruction->GetLocations()->InAt(condition_input_index);
3644     DCHECK(cond_val.IsRegister());
3645       if (true_target == nullptr) {
3646       __ Cbz(InputRegisterAt(instruction, condition_input_index), false_target);
3647     } else {
3648       __ Cbnz(InputRegisterAt(instruction, condition_input_index), true_target);
3649     }
3650   } else {
3651     // The condition instruction has not been materialized, use its inputs as
3652     // the comparison and its condition as the branch condition.
3653     HCondition* condition = cond->AsCondition();
3654 
3655     DataType::Type type = condition->InputAt(0)->GetType();
3656     if (DataType::IsFloatingPointType(type)) {
3657       GenerateFcmp(condition);
3658       if (true_target == nullptr) {
3659         IfCondition opposite_condition = condition->GetOppositeCondition();
3660         __ B(ARM64FPCondition(opposite_condition, condition->IsGtBias()), false_target);
3661       } else {
3662         __ B(ARM64FPCondition(condition->GetCondition(), condition->IsGtBias()), true_target);
3663       }
3664     } else {
3665       // Integer cases.
3666       Register lhs = InputRegisterAt(condition, 0);
3667       Operand rhs = InputOperandAt(condition, 1);
3668 
3669       Condition arm64_cond;
3670       vixl::aarch64::Label* non_fallthrough_target;
3671       if (true_target == nullptr) {
3672         arm64_cond = ARM64Condition(condition->GetOppositeCondition());
3673         non_fallthrough_target = false_target;
3674       } else {
3675         arm64_cond = ARM64Condition(condition->GetCondition());
3676         non_fallthrough_target = true_target;
3677       }
3678 
3679       if ((arm64_cond == eq || arm64_cond == ne || arm64_cond == lt || arm64_cond == ge) &&
3680           rhs.IsImmediate() && (rhs.GetImmediate() == 0)) {
3681         switch (arm64_cond) {
3682           case eq:
3683             __ Cbz(lhs, non_fallthrough_target);
3684             break;
3685           case ne:
3686             __ Cbnz(lhs, non_fallthrough_target);
3687             break;
3688           case lt:
3689             // Test the sign bit and branch accordingly.
3690             __ Tbnz(lhs, (lhs.IsX() ? kXRegSize : kWRegSize) - 1, non_fallthrough_target);
3691             break;
3692           case ge:
3693             // Test the sign bit and branch accordingly.
3694             __ Tbz(lhs, (lhs.IsX() ? kXRegSize : kWRegSize) - 1, non_fallthrough_target);
3695             break;
3696           default:
3697             // Without the `static_cast` the compiler throws an error for
3698             // `-Werror=sign-promo`.
3699             LOG(FATAL) << "Unexpected condition: " << static_cast<int>(arm64_cond);
3700         }
3701       } else {
3702         __ Cmp(lhs, rhs);
3703         __ B(arm64_cond, non_fallthrough_target);
3704       }
3705     }
3706   }
3707 
3708   // If neither branch falls through (case 3), the conditional branch to `true_target`
3709   // was already emitted (case 2) and we need to emit a jump to `false_target`.
3710   if (true_target != nullptr && false_target != nullptr) {
3711     __ B(false_target);
3712   }
3713 }
3714 
VisitIf(HIf * if_instr)3715 void LocationsBuilderARM64::VisitIf(HIf* if_instr) {
3716   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(if_instr);
3717   if (IsBooleanValueOrMaterializedCondition(if_instr->InputAt(0))) {
3718     locations->SetInAt(0, Location::RequiresRegister());
3719   }
3720 }
3721 
VisitIf(HIf * if_instr)3722 void InstructionCodeGeneratorARM64::VisitIf(HIf* if_instr) {
3723   HBasicBlock* true_successor = if_instr->IfTrueSuccessor();
3724   HBasicBlock* false_successor = if_instr->IfFalseSuccessor();
3725   vixl::aarch64::Label* true_target = codegen_->GetLabelOf(true_successor);
3726   if (codegen_->GoesToNextBlock(if_instr->GetBlock(), true_successor)) {
3727     true_target = nullptr;
3728   }
3729   vixl::aarch64::Label* false_target = codegen_->GetLabelOf(false_successor);
3730   if (codegen_->GoesToNextBlock(if_instr->GetBlock(), false_successor)) {
3731     false_target = nullptr;
3732   }
3733   GenerateTestAndBranch(if_instr, /* condition_input_index= */ 0, true_target, false_target);
3734 }
3735 
VisitDeoptimize(HDeoptimize * deoptimize)3736 void LocationsBuilderARM64::VisitDeoptimize(HDeoptimize* deoptimize) {
3737   LocationSummary* locations = new (GetGraph()->GetAllocator())
3738       LocationSummary(deoptimize, LocationSummary::kCallOnSlowPath);
3739   InvokeRuntimeCallingConvention calling_convention;
3740   RegisterSet caller_saves = RegisterSet::Empty();
3741   caller_saves.Add(Location::RegisterLocation(calling_convention.GetRegisterAt(0).GetCode()));
3742   locations->SetCustomSlowPathCallerSaves(caller_saves);
3743   if (IsBooleanValueOrMaterializedCondition(deoptimize->InputAt(0))) {
3744     locations->SetInAt(0, Location::RequiresRegister());
3745   }
3746 }
3747 
VisitDeoptimize(HDeoptimize * deoptimize)3748 void InstructionCodeGeneratorARM64::VisitDeoptimize(HDeoptimize* deoptimize) {
3749   SlowPathCodeARM64* slow_path =
3750       deopt_slow_paths_.NewSlowPath<DeoptimizationSlowPathARM64>(deoptimize);
3751   GenerateTestAndBranch(deoptimize,
3752                         /* condition_input_index= */ 0,
3753                         slow_path->GetEntryLabel(),
3754                         /* false_target= */ nullptr);
3755 }
3756 
VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag * flag)3757 void LocationsBuilderARM64::VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag* flag) {
3758   LocationSummary* locations = new (GetGraph()->GetAllocator())
3759       LocationSummary(flag, LocationSummary::kNoCall);
3760   locations->SetOut(Location::RequiresRegister());
3761 }
3762 
VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag * flag)3763 void InstructionCodeGeneratorARM64::VisitShouldDeoptimizeFlag(HShouldDeoptimizeFlag* flag) {
3764   __ Ldr(OutputRegister(flag),
3765          MemOperand(sp, codegen_->GetStackOffsetOfShouldDeoptimizeFlag()));
3766 }
3767 
IsConditionOnFloatingPointValues(HInstruction * condition)3768 static inline bool IsConditionOnFloatingPointValues(HInstruction* condition) {
3769   return condition->IsCondition() &&
3770          DataType::IsFloatingPointType(condition->InputAt(0)->GetType());
3771 }
3772 
GetConditionForSelect(HCondition * condition)3773 static inline Condition GetConditionForSelect(HCondition* condition) {
3774   IfCondition cond = condition->AsCondition()->GetCondition();
3775   return IsConditionOnFloatingPointValues(condition) ? ARM64FPCondition(cond, condition->IsGtBias())
3776                                                      : ARM64Condition(cond);
3777 }
3778 
VisitSelect(HSelect * select)3779 void LocationsBuilderARM64::VisitSelect(HSelect* select) {
3780   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(select);
3781   if (DataType::IsFloatingPointType(select->GetType())) {
3782     locations->SetInAt(0, Location::RequiresFpuRegister());
3783     locations->SetInAt(1, Location::RequiresFpuRegister());
3784     locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
3785   } else {
3786     HConstant* cst_true_value = select->GetTrueValue()->AsConstant();
3787     HConstant* cst_false_value = select->GetFalseValue()->AsConstant();
3788     bool is_true_value_constant = cst_true_value != nullptr;
3789     bool is_false_value_constant = cst_false_value != nullptr;
3790     // Ask VIXL whether we should synthesize constants in registers.
3791     // We give an arbitrary register to VIXL when dealing with non-constant inputs.
3792     Operand true_op = is_true_value_constant ?
3793         Operand(Int64FromConstant(cst_true_value)) : Operand(x1);
3794     Operand false_op = is_false_value_constant ?
3795         Operand(Int64FromConstant(cst_false_value)) : Operand(x2);
3796     bool true_value_in_register = false;
3797     bool false_value_in_register = false;
3798     MacroAssembler::GetCselSynthesisInformation(
3799         x0, true_op, false_op, &true_value_in_register, &false_value_in_register);
3800     true_value_in_register |= !is_true_value_constant;
3801     false_value_in_register |= !is_false_value_constant;
3802 
3803     locations->SetInAt(1, true_value_in_register ? Location::RequiresRegister()
3804                                                  : Location::ConstantLocation(cst_true_value));
3805     locations->SetInAt(0, false_value_in_register ? Location::RequiresRegister()
3806                                                   : Location::ConstantLocation(cst_false_value));
3807     locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
3808   }
3809 
3810   if (IsBooleanValueOrMaterializedCondition(select->GetCondition())) {
3811     locations->SetInAt(2, Location::RequiresRegister());
3812   }
3813 }
3814 
VisitSelect(HSelect * select)3815 void InstructionCodeGeneratorARM64::VisitSelect(HSelect* select) {
3816   HInstruction* cond = select->GetCondition();
3817   Condition csel_cond;
3818 
3819   if (IsBooleanValueOrMaterializedCondition(cond)) {
3820     if (cond->IsCondition() && cond->GetNext() == select) {
3821       // Use the condition flags set by the previous instruction.
3822       csel_cond = GetConditionForSelect(cond->AsCondition());
3823     } else {
3824       __ Cmp(InputRegisterAt(select, 2), 0);
3825       csel_cond = ne;
3826     }
3827   } else if (IsConditionOnFloatingPointValues(cond)) {
3828     GenerateFcmp(cond);
3829     csel_cond = GetConditionForSelect(cond->AsCondition());
3830   } else {
3831     __ Cmp(InputRegisterAt(cond, 0), InputOperandAt(cond, 1));
3832     csel_cond = GetConditionForSelect(cond->AsCondition());
3833   }
3834 
3835   if (DataType::IsFloatingPointType(select->GetType())) {
3836     __ Fcsel(OutputFPRegister(select),
3837              InputFPRegisterAt(select, 1),
3838              InputFPRegisterAt(select, 0),
3839              csel_cond);
3840   } else {
3841     __ Csel(OutputRegister(select),
3842             InputOperandAt(select, 1),
3843             InputOperandAt(select, 0),
3844             csel_cond);
3845   }
3846 }
3847 
VisitNativeDebugInfo(HNativeDebugInfo * info)3848 void LocationsBuilderARM64::VisitNativeDebugInfo(HNativeDebugInfo* info) {
3849   new (GetGraph()->GetAllocator()) LocationSummary(info);
3850 }
3851 
VisitNativeDebugInfo(HNativeDebugInfo *)3852 void InstructionCodeGeneratorARM64::VisitNativeDebugInfo(HNativeDebugInfo*) {
3853   // MaybeRecordNativeDebugInfo is already called implicitly in CodeGenerator::Compile.
3854 }
3855 
IncreaseFrame(size_t adjustment)3856 void CodeGeneratorARM64::IncreaseFrame(size_t adjustment) {
3857   __ Claim(adjustment);
3858   GetAssembler()->cfi().AdjustCFAOffset(adjustment);
3859 }
3860 
DecreaseFrame(size_t adjustment)3861 void CodeGeneratorARM64::DecreaseFrame(size_t adjustment) {
3862   __ Drop(adjustment);
3863   GetAssembler()->cfi().AdjustCFAOffset(-adjustment);
3864 }
3865 
GenerateNop()3866 void CodeGeneratorARM64::GenerateNop() {
3867   __ Nop();
3868 }
3869 
VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet * instruction)3870 void LocationsBuilderARM64::VisitPredicatedInstanceFieldGet(
3871     HPredicatedInstanceFieldGet* instruction) {
3872   HandleFieldGet(instruction, instruction->GetFieldInfo());
3873 }
3874 
VisitInstanceFieldGet(HInstanceFieldGet * instruction)3875 void LocationsBuilderARM64::VisitInstanceFieldGet(HInstanceFieldGet* instruction) {
3876   HandleFieldGet(instruction, instruction->GetFieldInfo());
3877 }
3878 
VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet * instruction)3879 void InstructionCodeGeneratorARM64::VisitPredicatedInstanceFieldGet(
3880     HPredicatedInstanceFieldGet* instruction) {
3881   vixl::aarch64::Label finish;
3882   __ Cbz(InputRegisterAt(instruction, 1), &finish);
3883   HandleFieldGet(instruction, instruction->GetFieldInfo());
3884   __ Bind(&finish);
3885 }
3886 
VisitInstanceFieldGet(HInstanceFieldGet * instruction)3887 void InstructionCodeGeneratorARM64::VisitInstanceFieldGet(HInstanceFieldGet* instruction) {
3888   HandleFieldGet(instruction, instruction->GetFieldInfo());
3889 }
3890 
VisitInstanceFieldSet(HInstanceFieldSet * instruction)3891 void LocationsBuilderARM64::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
3892   HandleFieldSet(instruction);
3893 }
3894 
VisitInstanceFieldSet(HInstanceFieldSet * instruction)3895 void InstructionCodeGeneratorARM64::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
3896   HandleFieldSet(instruction, instruction->GetFieldInfo(), instruction->GetValueCanBeNull());
3897 }
3898 
3899 // Temp is used for read barrier.
NumberOfInstanceOfTemps(TypeCheckKind type_check_kind)3900 static size_t NumberOfInstanceOfTemps(TypeCheckKind type_check_kind) {
3901   if (kEmitCompilerReadBarrier &&
3902       (kUseBakerReadBarrier ||
3903           type_check_kind == TypeCheckKind::kAbstractClassCheck ||
3904           type_check_kind == TypeCheckKind::kClassHierarchyCheck ||
3905           type_check_kind == TypeCheckKind::kArrayObjectCheck)) {
3906     return 1;
3907   }
3908   return 0;
3909 }
3910 
3911 // Interface case has 3 temps, one for holding the number of interfaces, one for the current
3912 // interface pointer, one for loading the current interface.
3913 // The other checks have one temp for loading the object's class.
NumberOfCheckCastTemps(TypeCheckKind type_check_kind)3914 static size_t NumberOfCheckCastTemps(TypeCheckKind type_check_kind) {
3915   if (type_check_kind == TypeCheckKind::kInterfaceCheck) {
3916     return 3;
3917   }
3918   return 1 + NumberOfInstanceOfTemps(type_check_kind);
3919 }
3920 
VisitInstanceOf(HInstanceOf * instruction)3921 void LocationsBuilderARM64::VisitInstanceOf(HInstanceOf* instruction) {
3922   LocationSummary::CallKind call_kind = LocationSummary::kNoCall;
3923   TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
3924   bool baker_read_barrier_slow_path = false;
3925   switch (type_check_kind) {
3926     case TypeCheckKind::kExactCheck:
3927     case TypeCheckKind::kAbstractClassCheck:
3928     case TypeCheckKind::kClassHierarchyCheck:
3929     case TypeCheckKind::kArrayObjectCheck: {
3930       bool needs_read_barrier = CodeGenerator::InstanceOfNeedsReadBarrier(instruction);
3931       call_kind = needs_read_barrier ? LocationSummary::kCallOnSlowPath : LocationSummary::kNoCall;
3932       baker_read_barrier_slow_path = kUseBakerReadBarrier && needs_read_barrier;
3933       break;
3934     }
3935     case TypeCheckKind::kArrayCheck:
3936     case TypeCheckKind::kUnresolvedCheck:
3937     case TypeCheckKind::kInterfaceCheck:
3938       call_kind = LocationSummary::kCallOnSlowPath;
3939       break;
3940     case TypeCheckKind::kBitstringCheck:
3941       break;
3942   }
3943 
3944   LocationSummary* locations =
3945       new (GetGraph()->GetAllocator()) LocationSummary(instruction, call_kind);
3946   if (baker_read_barrier_slow_path) {
3947     locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty());  // No caller-save registers.
3948   }
3949   locations->SetInAt(0, Location::RequiresRegister());
3950   if (type_check_kind == TypeCheckKind::kBitstringCheck) {
3951     locations->SetInAt(1, Location::ConstantLocation(instruction->InputAt(1)->AsConstant()));
3952     locations->SetInAt(2, Location::ConstantLocation(instruction->InputAt(2)->AsConstant()));
3953     locations->SetInAt(3, Location::ConstantLocation(instruction->InputAt(3)->AsConstant()));
3954   } else {
3955     locations->SetInAt(1, Location::RequiresRegister());
3956   }
3957   // The "out" register is used as a temporary, so it overlaps with the inputs.
3958   // Note that TypeCheckSlowPathARM64 uses this register too.
3959   locations->SetOut(Location::RequiresRegister(), Location::kOutputOverlap);
3960   // Add temps if necessary for read barriers.
3961   locations->AddRegisterTemps(NumberOfInstanceOfTemps(type_check_kind));
3962 }
3963 
VisitInstanceOf(HInstanceOf * instruction)3964 void InstructionCodeGeneratorARM64::VisitInstanceOf(HInstanceOf* instruction) {
3965   TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
3966   LocationSummary* locations = instruction->GetLocations();
3967   Location obj_loc = locations->InAt(0);
3968   Register obj = InputRegisterAt(instruction, 0);
3969   Register cls = (type_check_kind == TypeCheckKind::kBitstringCheck)
3970       ? Register()
3971       : InputRegisterAt(instruction, 1);
3972   Location out_loc = locations->Out();
3973   Register out = OutputRegister(instruction);
3974   const size_t num_temps = NumberOfInstanceOfTemps(type_check_kind);
3975   DCHECK_LE(num_temps, 1u);
3976   Location maybe_temp_loc = (num_temps >= 1) ? locations->GetTemp(0) : Location::NoLocation();
3977   uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
3978   uint32_t super_offset = mirror::Class::SuperClassOffset().Int32Value();
3979   uint32_t component_offset = mirror::Class::ComponentTypeOffset().Int32Value();
3980   uint32_t primitive_offset = mirror::Class::PrimitiveTypeOffset().Int32Value();
3981 
3982   vixl::aarch64::Label done, zero;
3983   SlowPathCodeARM64* slow_path = nullptr;
3984 
3985   // Return 0 if `obj` is null.
3986   // Avoid null check if we know `obj` is not null.
3987   if (instruction->MustDoNullCheck()) {
3988     __ Cbz(obj, &zero);
3989   }
3990 
3991   switch (type_check_kind) {
3992     case TypeCheckKind::kExactCheck: {
3993       ReadBarrierOption read_barrier_option =
3994           CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
3995       // /* HeapReference<Class> */ out = obj->klass_
3996       GenerateReferenceLoadTwoRegisters(instruction,
3997                                         out_loc,
3998                                         obj_loc,
3999                                         class_offset,
4000                                         maybe_temp_loc,
4001                                         read_barrier_option);
4002       __ Cmp(out, cls);
4003       __ Cset(out, eq);
4004       if (zero.IsLinked()) {
4005         __ B(&done);
4006       }
4007       break;
4008     }
4009 
4010     case TypeCheckKind::kAbstractClassCheck: {
4011       ReadBarrierOption read_barrier_option =
4012           CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
4013       // /* HeapReference<Class> */ out = obj->klass_
4014       GenerateReferenceLoadTwoRegisters(instruction,
4015                                         out_loc,
4016                                         obj_loc,
4017                                         class_offset,
4018                                         maybe_temp_loc,
4019                                         read_barrier_option);
4020       // If the class is abstract, we eagerly fetch the super class of the
4021       // object to avoid doing a comparison we know will fail.
4022       vixl::aarch64::Label loop, success;
4023       __ Bind(&loop);
4024       // /* HeapReference<Class> */ out = out->super_class_
4025       GenerateReferenceLoadOneRegister(instruction,
4026                                        out_loc,
4027                                        super_offset,
4028                                        maybe_temp_loc,
4029                                        read_barrier_option);
4030       // If `out` is null, we use it for the result, and jump to `done`.
4031       __ Cbz(out, &done);
4032       __ Cmp(out, cls);
4033       __ B(ne, &loop);
4034       __ Mov(out, 1);
4035       if (zero.IsLinked()) {
4036         __ B(&done);
4037       }
4038       break;
4039     }
4040 
4041     case TypeCheckKind::kClassHierarchyCheck: {
4042       ReadBarrierOption read_barrier_option =
4043           CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
4044       // /* HeapReference<Class> */ out = obj->klass_
4045       GenerateReferenceLoadTwoRegisters(instruction,
4046                                         out_loc,
4047                                         obj_loc,
4048                                         class_offset,
4049                                         maybe_temp_loc,
4050                                         read_barrier_option);
4051       // Walk over the class hierarchy to find a match.
4052       vixl::aarch64::Label loop, success;
4053       __ Bind(&loop);
4054       __ Cmp(out, cls);
4055       __ B(eq, &success);
4056       // /* HeapReference<Class> */ out = out->super_class_
4057       GenerateReferenceLoadOneRegister(instruction,
4058                                        out_loc,
4059                                        super_offset,
4060                                        maybe_temp_loc,
4061                                        read_barrier_option);
4062       __ Cbnz(out, &loop);
4063       // If `out` is null, we use it for the result, and jump to `done`.
4064       __ B(&done);
4065       __ Bind(&success);
4066       __ Mov(out, 1);
4067       if (zero.IsLinked()) {
4068         __ B(&done);
4069       }
4070       break;
4071     }
4072 
4073     case TypeCheckKind::kArrayObjectCheck: {
4074       ReadBarrierOption read_barrier_option =
4075           CodeGenerator::ReadBarrierOptionForInstanceOf(instruction);
4076       // /* HeapReference<Class> */ out = obj->klass_
4077       GenerateReferenceLoadTwoRegisters(instruction,
4078                                         out_loc,
4079                                         obj_loc,
4080                                         class_offset,
4081                                         maybe_temp_loc,
4082                                         read_barrier_option);
4083       // Do an exact check.
4084       vixl::aarch64::Label exact_check;
4085       __ Cmp(out, cls);
4086       __ B(eq, &exact_check);
4087       // Otherwise, we need to check that the object's class is a non-primitive array.
4088       // /* HeapReference<Class> */ out = out->component_type_
4089       GenerateReferenceLoadOneRegister(instruction,
4090                                        out_loc,
4091                                        component_offset,
4092                                        maybe_temp_loc,
4093                                        read_barrier_option);
4094       // If `out` is null, we use it for the result, and jump to `done`.
4095       __ Cbz(out, &done);
4096       __ Ldrh(out, HeapOperand(out, primitive_offset));
4097       static_assert(Primitive::kPrimNot == 0, "Expected 0 for kPrimNot");
4098       __ Cbnz(out, &zero);
4099       __ Bind(&exact_check);
4100       __ Mov(out, 1);
4101       __ B(&done);
4102       break;
4103     }
4104 
4105     case TypeCheckKind::kArrayCheck: {
4106       // No read barrier since the slow path will retry upon failure.
4107       // /* HeapReference<Class> */ out = obj->klass_
4108       GenerateReferenceLoadTwoRegisters(instruction,
4109                                         out_loc,
4110                                         obj_loc,
4111                                         class_offset,
4112                                         maybe_temp_loc,
4113                                         kWithoutReadBarrier);
4114       __ Cmp(out, cls);
4115       DCHECK(locations->OnlyCallsOnSlowPath());
4116       slow_path = new (codegen_->GetScopedAllocator()) TypeCheckSlowPathARM64(
4117           instruction, /* is_fatal= */ false);
4118       codegen_->AddSlowPath(slow_path);
4119       __ B(ne, slow_path->GetEntryLabel());
4120       __ Mov(out, 1);
4121       if (zero.IsLinked()) {
4122         __ B(&done);
4123       }
4124       break;
4125     }
4126 
4127     case TypeCheckKind::kUnresolvedCheck:
4128     case TypeCheckKind::kInterfaceCheck: {
4129       // Note that we indeed only call on slow path, but we always go
4130       // into the slow path for the unresolved and interface check
4131       // cases.
4132       //
4133       // We cannot directly call the InstanceofNonTrivial runtime
4134       // entry point without resorting to a type checking slow path
4135       // here (i.e. by calling InvokeRuntime directly), as it would
4136       // require to assign fixed registers for the inputs of this
4137       // HInstanceOf instruction (following the runtime calling
4138       // convention), which might be cluttered by the potential first
4139       // read barrier emission at the beginning of this method.
4140       //
4141       // TODO: Introduce a new runtime entry point taking the object
4142       // to test (instead of its class) as argument, and let it deal
4143       // with the read barrier issues. This will let us refactor this
4144       // case of the `switch` code as it was previously (with a direct
4145       // call to the runtime not using a type checking slow path).
4146       // This should also be beneficial for the other cases above.
4147       DCHECK(locations->OnlyCallsOnSlowPath());
4148       slow_path = new (codegen_->GetScopedAllocator()) TypeCheckSlowPathARM64(
4149           instruction, /* is_fatal= */ false);
4150       codegen_->AddSlowPath(slow_path);
4151       __ B(slow_path->GetEntryLabel());
4152       if (zero.IsLinked()) {
4153         __ B(&done);
4154       }
4155       break;
4156     }
4157 
4158     case TypeCheckKind::kBitstringCheck: {
4159       // /* HeapReference<Class> */ temp = obj->klass_
4160       GenerateReferenceLoadTwoRegisters(instruction,
4161                                         out_loc,
4162                                         obj_loc,
4163                                         class_offset,
4164                                         maybe_temp_loc,
4165                                         kWithoutReadBarrier);
4166 
4167       GenerateBitstringTypeCheckCompare(instruction, out);
4168       __ Cset(out, eq);
4169       if (zero.IsLinked()) {
4170         __ B(&done);
4171       }
4172       break;
4173     }
4174   }
4175 
4176   if (zero.IsLinked()) {
4177     __ Bind(&zero);
4178     __ Mov(out, 0);
4179   }
4180 
4181   if (done.IsLinked()) {
4182     __ Bind(&done);
4183   }
4184 
4185   if (slow_path != nullptr) {
4186     __ Bind(slow_path->GetExitLabel());
4187   }
4188 }
4189 
VisitCheckCast(HCheckCast * instruction)4190 void LocationsBuilderARM64::VisitCheckCast(HCheckCast* instruction) {
4191   TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
4192   LocationSummary::CallKind call_kind = CodeGenerator::GetCheckCastCallKind(instruction);
4193   LocationSummary* locations =
4194       new (GetGraph()->GetAllocator()) LocationSummary(instruction, call_kind);
4195   locations->SetInAt(0, Location::RequiresRegister());
4196   if (type_check_kind == TypeCheckKind::kBitstringCheck) {
4197     locations->SetInAt(1, Location::ConstantLocation(instruction->InputAt(1)->AsConstant()));
4198     locations->SetInAt(2, Location::ConstantLocation(instruction->InputAt(2)->AsConstant()));
4199     locations->SetInAt(3, Location::ConstantLocation(instruction->InputAt(3)->AsConstant()));
4200   } else {
4201     locations->SetInAt(1, Location::RequiresRegister());
4202   }
4203   // Add temps for read barriers and other uses. One is used by TypeCheckSlowPathARM64.
4204   locations->AddRegisterTemps(NumberOfCheckCastTemps(type_check_kind));
4205 }
4206 
VisitCheckCast(HCheckCast * instruction)4207 void InstructionCodeGeneratorARM64::VisitCheckCast(HCheckCast* instruction) {
4208   TypeCheckKind type_check_kind = instruction->GetTypeCheckKind();
4209   LocationSummary* locations = instruction->GetLocations();
4210   Location obj_loc = locations->InAt(0);
4211   Register obj = InputRegisterAt(instruction, 0);
4212   Register cls = (type_check_kind == TypeCheckKind::kBitstringCheck)
4213       ? Register()
4214       : InputRegisterAt(instruction, 1);
4215   const size_t num_temps = NumberOfCheckCastTemps(type_check_kind);
4216   DCHECK_GE(num_temps, 1u);
4217   DCHECK_LE(num_temps, 3u);
4218   Location temp_loc = locations->GetTemp(0);
4219   Location maybe_temp2_loc = (num_temps >= 2) ? locations->GetTemp(1) : Location::NoLocation();
4220   Location maybe_temp3_loc = (num_temps >= 3) ? locations->GetTemp(2) : Location::NoLocation();
4221   Register temp = WRegisterFrom(temp_loc);
4222   const uint32_t class_offset = mirror::Object::ClassOffset().Int32Value();
4223   const uint32_t super_offset = mirror::Class::SuperClassOffset().Int32Value();
4224   const uint32_t component_offset = mirror::Class::ComponentTypeOffset().Int32Value();
4225   const uint32_t primitive_offset = mirror::Class::PrimitiveTypeOffset().Int32Value();
4226   const uint32_t iftable_offset = mirror::Class::IfTableOffset().Uint32Value();
4227   const uint32_t array_length_offset = mirror::Array::LengthOffset().Uint32Value();
4228   const uint32_t object_array_data_offset =
4229       mirror::Array::DataOffset(kHeapReferenceSize).Uint32Value();
4230 
4231   bool is_type_check_slow_path_fatal = CodeGenerator::IsTypeCheckSlowPathFatal(instruction);
4232   SlowPathCodeARM64* type_check_slow_path =
4233       new (codegen_->GetScopedAllocator()) TypeCheckSlowPathARM64(
4234           instruction, is_type_check_slow_path_fatal);
4235   codegen_->AddSlowPath(type_check_slow_path);
4236 
4237   vixl::aarch64::Label done;
4238   // Avoid null check if we know obj is not null.
4239   if (instruction->MustDoNullCheck()) {
4240     __ Cbz(obj, &done);
4241   }
4242 
4243   switch (type_check_kind) {
4244     case TypeCheckKind::kExactCheck:
4245     case TypeCheckKind::kArrayCheck: {
4246       // /* HeapReference<Class> */ temp = obj->klass_
4247       GenerateReferenceLoadTwoRegisters(instruction,
4248                                         temp_loc,
4249                                         obj_loc,
4250                                         class_offset,
4251                                         maybe_temp2_loc,
4252                                         kWithoutReadBarrier);
4253 
4254       __ Cmp(temp, cls);
4255       // Jump to slow path for throwing the exception or doing a
4256       // more involved array check.
4257       __ B(ne, type_check_slow_path->GetEntryLabel());
4258       break;
4259     }
4260 
4261     case TypeCheckKind::kAbstractClassCheck: {
4262       // /* HeapReference<Class> */ temp = obj->klass_
4263       GenerateReferenceLoadTwoRegisters(instruction,
4264                                         temp_loc,
4265                                         obj_loc,
4266                                         class_offset,
4267                                         maybe_temp2_loc,
4268                                         kWithoutReadBarrier);
4269 
4270       // If the class is abstract, we eagerly fetch the super class of the
4271       // object to avoid doing a comparison we know will fail.
4272       vixl::aarch64::Label loop;
4273       __ Bind(&loop);
4274       // /* HeapReference<Class> */ temp = temp->super_class_
4275       GenerateReferenceLoadOneRegister(instruction,
4276                                        temp_loc,
4277                                        super_offset,
4278                                        maybe_temp2_loc,
4279                                        kWithoutReadBarrier);
4280 
4281       // If the class reference currently in `temp` is null, jump to the slow path to throw the
4282       // exception.
4283       __ Cbz(temp, type_check_slow_path->GetEntryLabel());
4284       // Otherwise, compare classes.
4285       __ Cmp(temp, cls);
4286       __ B(ne, &loop);
4287       break;
4288     }
4289 
4290     case TypeCheckKind::kClassHierarchyCheck: {
4291       // /* HeapReference<Class> */ temp = obj->klass_
4292       GenerateReferenceLoadTwoRegisters(instruction,
4293                                         temp_loc,
4294                                         obj_loc,
4295                                         class_offset,
4296                                         maybe_temp2_loc,
4297                                         kWithoutReadBarrier);
4298 
4299       // Walk over the class hierarchy to find a match.
4300       vixl::aarch64::Label loop;
4301       __ Bind(&loop);
4302       __ Cmp(temp, cls);
4303       __ B(eq, &done);
4304 
4305       // /* HeapReference<Class> */ temp = temp->super_class_
4306       GenerateReferenceLoadOneRegister(instruction,
4307                                        temp_loc,
4308                                        super_offset,
4309                                        maybe_temp2_loc,
4310                                        kWithoutReadBarrier);
4311 
4312       // If the class reference currently in `temp` is not null, jump
4313       // back at the beginning of the loop.
4314       __ Cbnz(temp, &loop);
4315       // Otherwise, jump to the slow path to throw the exception.
4316       __ B(type_check_slow_path->GetEntryLabel());
4317       break;
4318     }
4319 
4320     case TypeCheckKind::kArrayObjectCheck: {
4321       // /* HeapReference<Class> */ temp = obj->klass_
4322       GenerateReferenceLoadTwoRegisters(instruction,
4323                                         temp_loc,
4324                                         obj_loc,
4325                                         class_offset,
4326                                         maybe_temp2_loc,
4327                                         kWithoutReadBarrier);
4328 
4329       // Do an exact check.
4330       __ Cmp(temp, cls);
4331       __ B(eq, &done);
4332 
4333       // Otherwise, we need to check that the object's class is a non-primitive array.
4334       // /* HeapReference<Class> */ temp = temp->component_type_
4335       GenerateReferenceLoadOneRegister(instruction,
4336                                        temp_loc,
4337                                        component_offset,
4338                                        maybe_temp2_loc,
4339                                        kWithoutReadBarrier);
4340 
4341       // If the component type is null, jump to the slow path to throw the exception.
4342       __ Cbz(temp, type_check_slow_path->GetEntryLabel());
4343       // Otherwise, the object is indeed an array. Further check that this component type is not a
4344       // primitive type.
4345       __ Ldrh(temp, HeapOperand(temp, primitive_offset));
4346       static_assert(Primitive::kPrimNot == 0, "Expected 0 for kPrimNot");
4347       __ Cbnz(temp, type_check_slow_path->GetEntryLabel());
4348       break;
4349     }
4350 
4351     case TypeCheckKind::kUnresolvedCheck:
4352       // We always go into the type check slow path for the unresolved check cases.
4353       //
4354       // We cannot directly call the CheckCast runtime entry point
4355       // without resorting to a type checking slow path here (i.e. by
4356       // calling InvokeRuntime directly), as it would require to
4357       // assign fixed registers for the inputs of this HInstanceOf
4358       // instruction (following the runtime calling convention), which
4359       // might be cluttered by the potential first read barrier
4360       // emission at the beginning of this method.
4361       __ B(type_check_slow_path->GetEntryLabel());
4362       break;
4363     case TypeCheckKind::kInterfaceCheck: {
4364       // /* HeapReference<Class> */ temp = obj->klass_
4365       GenerateReferenceLoadTwoRegisters(instruction,
4366                                         temp_loc,
4367                                         obj_loc,
4368                                         class_offset,
4369                                         maybe_temp2_loc,
4370                                         kWithoutReadBarrier);
4371 
4372       // /* HeapReference<Class> */ temp = temp->iftable_
4373       GenerateReferenceLoadTwoRegisters(instruction,
4374                                         temp_loc,
4375                                         temp_loc,
4376                                         iftable_offset,
4377                                         maybe_temp2_loc,
4378                                         kWithoutReadBarrier);
4379       // Iftable is never null.
4380       __ Ldr(WRegisterFrom(maybe_temp2_loc), HeapOperand(temp.W(), array_length_offset));
4381       // Loop through the iftable and check if any class matches.
4382       vixl::aarch64::Label start_loop;
4383       __ Bind(&start_loop);
4384       __ Cbz(WRegisterFrom(maybe_temp2_loc), type_check_slow_path->GetEntryLabel());
4385       __ Ldr(WRegisterFrom(maybe_temp3_loc), HeapOperand(temp.W(), object_array_data_offset));
4386       GetAssembler()->MaybeUnpoisonHeapReference(WRegisterFrom(maybe_temp3_loc));
4387       // Go to next interface.
4388       __ Add(temp, temp, 2 * kHeapReferenceSize);
4389       __ Sub(WRegisterFrom(maybe_temp2_loc), WRegisterFrom(maybe_temp2_loc), 2);
4390       // Compare the classes and continue the loop if they do not match.
4391       __ Cmp(cls, WRegisterFrom(maybe_temp3_loc));
4392       __ B(ne, &start_loop);
4393       break;
4394     }
4395 
4396     case TypeCheckKind::kBitstringCheck: {
4397       // /* HeapReference<Class> */ temp = obj->klass_
4398       GenerateReferenceLoadTwoRegisters(instruction,
4399                                         temp_loc,
4400                                         obj_loc,
4401                                         class_offset,
4402                                         maybe_temp2_loc,
4403                                         kWithoutReadBarrier);
4404 
4405       GenerateBitstringTypeCheckCompare(instruction, temp);
4406       __ B(ne, type_check_slow_path->GetEntryLabel());
4407       break;
4408     }
4409   }
4410   __ Bind(&done);
4411 
4412   __ Bind(type_check_slow_path->GetExitLabel());
4413 }
4414 
VisitIntConstant(HIntConstant * constant)4415 void LocationsBuilderARM64::VisitIntConstant(HIntConstant* constant) {
4416   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(constant);
4417   locations->SetOut(Location::ConstantLocation(constant));
4418 }
4419 
VisitIntConstant(HIntConstant * constant ATTRIBUTE_UNUSED)4420 void InstructionCodeGeneratorARM64::VisitIntConstant(HIntConstant* constant ATTRIBUTE_UNUSED) {
4421   // Will be generated at use site.
4422 }
4423 
VisitNullConstant(HNullConstant * constant)4424 void LocationsBuilderARM64::VisitNullConstant(HNullConstant* constant) {
4425   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(constant);
4426   locations->SetOut(Location::ConstantLocation(constant));
4427 }
4428 
VisitNullConstant(HNullConstant * constant ATTRIBUTE_UNUSED)4429 void InstructionCodeGeneratorARM64::VisitNullConstant(HNullConstant* constant ATTRIBUTE_UNUSED) {
4430   // Will be generated at use site.
4431 }
4432 
VisitInvokeUnresolved(HInvokeUnresolved * invoke)4433 void LocationsBuilderARM64::VisitInvokeUnresolved(HInvokeUnresolved* invoke) {
4434   // The trampoline uses the same calling convention as dex calling conventions,
4435   // except instead of loading arg0/r0 with the target Method*, arg0/r0 will contain
4436   // the method_idx.
4437   HandleInvoke(invoke);
4438 }
4439 
VisitInvokeUnresolved(HInvokeUnresolved * invoke)4440 void InstructionCodeGeneratorARM64::VisitInvokeUnresolved(HInvokeUnresolved* invoke) {
4441   codegen_->GenerateInvokeUnresolvedRuntimeCall(invoke);
4442   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
4443 }
4444 
HandleInvoke(HInvoke * invoke)4445 void LocationsBuilderARM64::HandleInvoke(HInvoke* invoke) {
4446   InvokeDexCallingConventionVisitorARM64 calling_convention_visitor;
4447   CodeGenerator::CreateCommonInvokeLocationSummary(invoke, &calling_convention_visitor);
4448 }
4449 
VisitInvokeInterface(HInvokeInterface * invoke)4450 void LocationsBuilderARM64::VisitInvokeInterface(HInvokeInterface* invoke) {
4451   HandleInvoke(invoke);
4452   if (invoke->GetHiddenArgumentLoadKind() == MethodLoadKind::kRecursive) {
4453     // We cannot request ip1 as it's blocked by the register allocator.
4454     invoke->GetLocations()->SetInAt(invoke->GetNumberOfArguments() - 1, Location::Any());
4455   }
4456 }
4457 
MaybeGenerateInlineCacheCheck(HInstruction * instruction,Register klass)4458 void CodeGeneratorARM64::MaybeGenerateInlineCacheCheck(HInstruction* instruction,
4459                                                        Register klass) {
4460   DCHECK_EQ(klass.GetCode(), 0u);
4461   // We know the destination of an intrinsic, so no need to record inline
4462   // caches.
4463   if (!instruction->GetLocations()->Intrinsified() &&
4464       GetGraph()->IsCompilingBaseline() &&
4465       !Runtime::Current()->IsAotCompiler()) {
4466     DCHECK(!instruction->GetEnvironment()->IsFromInlinedInvoke());
4467     ProfilingInfo* info = GetGraph()->GetProfilingInfo();
4468     DCHECK(info != nullptr);
4469     InlineCache* cache = info->GetInlineCache(instruction->GetDexPc());
4470     uint64_t address = reinterpret_cast64<uint64_t>(cache);
4471     vixl::aarch64::Label done;
4472     __ Mov(x8, address);
4473     __ Ldr(x9, MemOperand(x8, InlineCache::ClassesOffset().Int32Value()));
4474     // Fast path for a monomorphic cache.
4475     __ Cmp(klass, x9);
4476     __ B(eq, &done);
4477     InvokeRuntime(kQuickUpdateInlineCache, instruction, instruction->GetDexPc());
4478     __ Bind(&done);
4479   }
4480 }
4481 
VisitInvokeInterface(HInvokeInterface * invoke)4482 void InstructionCodeGeneratorARM64::VisitInvokeInterface(HInvokeInterface* invoke) {
4483   // TODO: b/18116999, our IMTs can miss an IncompatibleClassChangeError.
4484   LocationSummary* locations = invoke->GetLocations();
4485   Register temp = XRegisterFrom(locations->GetTemp(0));
4486   Location receiver = locations->InAt(0);
4487   Offset class_offset = mirror::Object::ClassOffset();
4488   Offset entry_point = ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArm64PointerSize);
4489 
4490   // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
4491   if (receiver.IsStackSlot()) {
4492     __ Ldr(temp.W(), StackOperandFrom(receiver));
4493     {
4494       EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
4495       // /* HeapReference<Class> */ temp = temp->klass_
4496       __ Ldr(temp.W(), HeapOperand(temp.W(), class_offset));
4497       codegen_->MaybeRecordImplicitNullCheck(invoke);
4498     }
4499   } else {
4500     EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
4501     // /* HeapReference<Class> */ temp = receiver->klass_
4502     __ Ldr(temp.W(), HeapOperandFrom(receiver, class_offset));
4503     codegen_->MaybeRecordImplicitNullCheck(invoke);
4504   }
4505 
4506   // Instead of simply (possibly) unpoisoning `temp` here, we should
4507   // emit a read barrier for the previous class reference load.
4508   // However this is not required in practice, as this is an
4509   // intermediate/temporary reference and because the current
4510   // concurrent copying collector keeps the from-space memory
4511   // intact/accessible until the end of the marking phase (the
4512   // concurrent copying collector may not in the future).
4513   GetAssembler()->MaybeUnpoisonHeapReference(temp.W());
4514 
4515   // If we're compiling baseline, update the inline cache.
4516   codegen_->MaybeGenerateInlineCacheCheck(invoke, temp);
4517 
4518   // The register ip1 is required to be used for the hidden argument in
4519   // art_quick_imt_conflict_trampoline, so prevent VIXL from using it.
4520   MacroAssembler* masm = GetVIXLAssembler();
4521   UseScratchRegisterScope scratch_scope(masm);
4522   scratch_scope.Exclude(ip1);
4523   if (invoke->GetHiddenArgumentLoadKind() == MethodLoadKind::kRecursive) {
4524     Location interface_method = locations->InAt(invoke->GetNumberOfArguments() - 1);
4525     if (interface_method.IsStackSlot()) {
4526       __ Ldr(ip1, StackOperandFrom(interface_method));
4527     } else {
4528       __ Mov(ip1, XRegisterFrom(interface_method));
4529     }
4530   // If the load kind is through a runtime call, we will pass the method we
4531   // fetch the IMT, which will either be a no-op if we don't hit the conflict
4532   // stub, or will make us always go through the trampoline when there is a
4533   // conflict.
4534   } else if (invoke->GetHiddenArgumentLoadKind() != MethodLoadKind::kRuntimeCall) {
4535     codegen_->LoadMethod(
4536         invoke->GetHiddenArgumentLoadKind(), Location::RegisterLocation(ip1.GetCode()), invoke);
4537   }
4538 
4539   __ Ldr(temp,
4540       MemOperand(temp, mirror::Class::ImtPtrOffset(kArm64PointerSize).Uint32Value()));
4541   uint32_t method_offset = static_cast<uint32_t>(ImTable::OffsetOfElement(
4542       invoke->GetImtIndex(), kArm64PointerSize));
4543   // temp = temp->GetImtEntryAt(method_offset);
4544   __ Ldr(temp, MemOperand(temp, method_offset));
4545   if (invoke->GetHiddenArgumentLoadKind() == MethodLoadKind::kRuntimeCall) {
4546     // We pass the method from the IMT in case of a conflict. This will ensure
4547     // we go into the runtime to resolve the actual method.
4548     __ Mov(ip1, temp);
4549   }
4550   // lr = temp->GetEntryPoint();
4551   __ Ldr(lr, MemOperand(temp, entry_point.Int32Value()));
4552 
4553   {
4554     // Ensure the pc position is recorded immediately after the `blr` instruction.
4555     ExactAssemblyScope eas(GetVIXLAssembler(), kInstructionSize, CodeBufferCheckScope::kExactSize);
4556 
4557     // lr();
4558     __ blr(lr);
4559     DCHECK(!codegen_->IsLeafMethod());
4560     codegen_->RecordPcInfo(invoke, invoke->GetDexPc());
4561   }
4562 
4563   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
4564 }
4565 
VisitInvokeVirtual(HInvokeVirtual * invoke)4566 void LocationsBuilderARM64::VisitInvokeVirtual(HInvokeVirtual* invoke) {
4567   IntrinsicLocationsBuilderARM64 intrinsic(GetGraph()->GetAllocator(), codegen_);
4568   if (intrinsic.TryDispatch(invoke)) {
4569     return;
4570   }
4571 
4572   HandleInvoke(invoke);
4573 }
4574 
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)4575 void LocationsBuilderARM64::VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
4576   // Explicit clinit checks triggered by static invokes must have been pruned by
4577   // art::PrepareForRegisterAllocation.
4578   DCHECK(!invoke->IsStaticWithExplicitClinitCheck());
4579 
4580   IntrinsicLocationsBuilderARM64 intrinsic(GetGraph()->GetAllocator(), codegen_);
4581   if (intrinsic.TryDispatch(invoke)) {
4582     return;
4583   }
4584 
4585   if (invoke->GetCodePtrLocation() == CodePtrLocation::kCallCriticalNative) {
4586     CriticalNativeCallingConventionVisitorARM64 calling_convention_visitor(
4587         /*for_register_allocation=*/ true);
4588     CodeGenerator::CreateCommonInvokeLocationSummary(invoke, &calling_convention_visitor);
4589   } else {
4590     HandleInvoke(invoke);
4591   }
4592 }
4593 
TryGenerateIntrinsicCode(HInvoke * invoke,CodeGeneratorARM64 * codegen)4594 static bool TryGenerateIntrinsicCode(HInvoke* invoke, CodeGeneratorARM64* codegen) {
4595   if (invoke->GetLocations()->Intrinsified()) {
4596     IntrinsicCodeGeneratorARM64 intrinsic(codegen);
4597     intrinsic.Dispatch(invoke);
4598     return true;
4599   }
4600   return false;
4601 }
4602 
GetSupportedInvokeStaticOrDirectDispatch(const HInvokeStaticOrDirect::DispatchInfo & desired_dispatch_info,ArtMethod * method ATTRIBUTE_UNUSED)4603 HInvokeStaticOrDirect::DispatchInfo CodeGeneratorARM64::GetSupportedInvokeStaticOrDirectDispatch(
4604       const HInvokeStaticOrDirect::DispatchInfo& desired_dispatch_info,
4605       ArtMethod* method ATTRIBUTE_UNUSED) {
4606   // On ARM64 we support all dispatch types.
4607   return desired_dispatch_info;
4608 }
4609 
LoadMethod(MethodLoadKind load_kind,Location temp,HInvoke * invoke)4610 void CodeGeneratorARM64::LoadMethod(MethodLoadKind load_kind, Location temp, HInvoke* invoke) {
4611   switch (load_kind) {
4612     case MethodLoadKind::kBootImageLinkTimePcRelative: {
4613       DCHECK(GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension());
4614       // Add ADRP with its PC-relative method patch.
4615       vixl::aarch64::Label* adrp_label =
4616           NewBootImageMethodPatch(invoke->GetResolvedMethodReference());
4617       EmitAdrpPlaceholder(adrp_label, XRegisterFrom(temp));
4618       // Add ADD with its PC-relative method patch.
4619       vixl::aarch64::Label* add_label =
4620           NewBootImageMethodPatch(invoke->GetResolvedMethodReference(), adrp_label);
4621       EmitAddPlaceholder(add_label, XRegisterFrom(temp), XRegisterFrom(temp));
4622       break;
4623     }
4624     case MethodLoadKind::kBootImageRelRo: {
4625       // Note: Boot image is in the low 4GiB and the entry is 32-bit, so emit a 32-bit load.
4626       uint32_t boot_image_offset = GetBootImageOffset(invoke);
4627       LoadBootImageRelRoEntry(WRegisterFrom(temp), boot_image_offset);
4628       break;
4629     }
4630     case MethodLoadKind::kBssEntry: {
4631       // Add ADRP with its PC-relative .bss entry patch.
4632       vixl::aarch64::Label* adrp_label = NewMethodBssEntryPatch(invoke->GetMethodReference());
4633       EmitAdrpPlaceholder(adrp_label, XRegisterFrom(temp));
4634       // Add LDR with its PC-relative .bss entry patch.
4635       vixl::aarch64::Label* ldr_label =
4636           NewMethodBssEntryPatch(invoke->GetMethodReference(), adrp_label);
4637       // All aligned loads are implicitly atomic consume operations on ARM64.
4638       EmitLdrOffsetPlaceholder(ldr_label, XRegisterFrom(temp), XRegisterFrom(temp));
4639       break;
4640     }
4641     case MethodLoadKind::kJitDirectAddress: {
4642       // Load method address from literal pool.
4643       __ Ldr(XRegisterFrom(temp),
4644              DeduplicateUint64Literal(reinterpret_cast<uint64_t>(invoke->GetResolvedMethod())));
4645       break;
4646     }
4647     case MethodLoadKind::kRuntimeCall: {
4648       // Test situation, don't do anything.
4649       break;
4650     }
4651     default: {
4652       LOG(FATAL) << "Load kind should have already been handled " << load_kind;
4653       UNREACHABLE();
4654     }
4655   }
4656 }
4657 
GenerateStaticOrDirectCall(HInvokeStaticOrDirect * invoke,Location temp,SlowPathCode * slow_path)4658 void CodeGeneratorARM64::GenerateStaticOrDirectCall(
4659     HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path) {
4660   // Make sure that ArtMethod* is passed in kArtMethodRegister as per the calling convention.
4661   Location callee_method = temp;  // For all kinds except kRecursive, callee will be in temp.
4662   switch (invoke->GetMethodLoadKind()) {
4663     case MethodLoadKind::kStringInit: {
4664       uint32_t offset =
4665           GetThreadOffset<kArm64PointerSize>(invoke->GetStringInitEntryPoint()).Int32Value();
4666       // temp = thread->string_init_entrypoint
4667       __ Ldr(XRegisterFrom(temp), MemOperand(tr, offset));
4668       break;
4669     }
4670     case MethodLoadKind::kRecursive: {
4671       callee_method = invoke->GetLocations()->InAt(invoke->GetCurrentMethodIndex());
4672       break;
4673     }
4674     case MethodLoadKind::kRuntimeCall: {
4675       GenerateInvokeStaticOrDirectRuntimeCall(invoke, temp, slow_path);
4676       return;  // No code pointer retrieval; the runtime performs the call directly.
4677     }
4678     case MethodLoadKind::kBootImageLinkTimePcRelative:
4679       DCHECK(GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension());
4680       if (invoke->GetCodePtrLocation() == CodePtrLocation::kCallCriticalNative) {
4681         // Do not materialize the method pointer, load directly the entrypoint.
4682         // Add ADRP with its PC-relative JNI entrypoint patch.
4683         vixl::aarch64::Label* adrp_label =
4684             NewBootImageJniEntrypointPatch(invoke->GetResolvedMethodReference());
4685         EmitAdrpPlaceholder(adrp_label, lr);
4686         // Add the LDR with its PC-relative method patch.
4687         vixl::aarch64::Label* add_label =
4688             NewBootImageJniEntrypointPatch(invoke->GetResolvedMethodReference(), adrp_label);
4689         EmitLdrOffsetPlaceholder(add_label, lr, lr);
4690         break;
4691       }
4692       FALLTHROUGH_INTENDED;
4693     default: {
4694       LoadMethod(invoke->GetMethodLoadKind(), temp, invoke);
4695       break;
4696     }
4697   }
4698 
4699   auto call_lr = [&]() {
4700     // Use a scope to help guarantee that `RecordPcInfo()` records the correct pc.
4701     ExactAssemblyScope eas(GetVIXLAssembler(),
4702                            kInstructionSize,
4703                            CodeBufferCheckScope::kExactSize);
4704     // lr()
4705     __ blr(lr);
4706     RecordPcInfo(invoke, invoke->GetDexPc(), slow_path);
4707   };
4708   switch (invoke->GetCodePtrLocation()) {
4709     case CodePtrLocation::kCallSelf:
4710       {
4711         DCHECK(!GetGraph()->HasShouldDeoptimizeFlag());
4712         // Use a scope to help guarantee that `RecordPcInfo()` records the correct pc.
4713         ExactAssemblyScope eas(GetVIXLAssembler(),
4714                                kInstructionSize,
4715                                CodeBufferCheckScope::kExactSize);
4716         __ bl(&frame_entry_label_);
4717         RecordPcInfo(invoke, invoke->GetDexPc(), slow_path);
4718       }
4719       break;
4720     case CodePtrLocation::kCallCriticalNative: {
4721       size_t out_frame_size =
4722           PrepareCriticalNativeCall<CriticalNativeCallingConventionVisitorARM64,
4723                                     kAapcs64StackAlignment,
4724                                     GetCriticalNativeDirectCallFrameSize>(invoke);
4725       if (invoke->GetMethodLoadKind() == MethodLoadKind::kBootImageLinkTimePcRelative) {
4726         call_lr();
4727       } else {
4728         // LR = callee_method->ptr_sized_fields_.data_;  // EntryPointFromJni
4729         MemberOffset offset = ArtMethod::EntryPointFromJniOffset(kArm64PointerSize);
4730         __ Ldr(lr, MemOperand(XRegisterFrom(callee_method), offset.Int32Value()));
4731         // lr()
4732         call_lr();
4733       }
4734       // Zero-/sign-extend the result when needed due to native and managed ABI mismatch.
4735       switch (invoke->GetType()) {
4736         case DataType::Type::kBool:
4737           __ Ubfx(w0, w0, 0, 8);
4738           break;
4739         case DataType::Type::kInt8:
4740           __ Sbfx(w0, w0, 0, 8);
4741           break;
4742         case DataType::Type::kUint16:
4743           __ Ubfx(w0, w0, 0, 16);
4744           break;
4745         case DataType::Type::kInt16:
4746           __ Sbfx(w0, w0, 0, 16);
4747           break;
4748         case DataType::Type::kInt32:
4749         case DataType::Type::kInt64:
4750         case DataType::Type::kFloat32:
4751         case DataType::Type::kFloat64:
4752         case DataType::Type::kVoid:
4753           break;
4754         default:
4755           DCHECK(false) << invoke->GetType();
4756           break;
4757       }
4758       if (out_frame_size != 0u) {
4759         DecreaseFrame(out_frame_size);
4760       }
4761       break;
4762     }
4763     case CodePtrLocation::kCallArtMethod: {
4764       // LR = callee_method->ptr_sized_fields_.entry_point_from_quick_compiled_code_;
4765       MemberOffset offset = ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArm64PointerSize);
4766       __ Ldr(lr, MemOperand(XRegisterFrom(callee_method), offset.Int32Value()));
4767       // lr()
4768       call_lr();
4769       break;
4770     }
4771   }
4772 
4773   DCHECK(!IsLeafMethod());
4774 }
4775 
GenerateVirtualCall(HInvokeVirtual * invoke,Location temp_in,SlowPathCode * slow_path)4776 void CodeGeneratorARM64::GenerateVirtualCall(
4777     HInvokeVirtual* invoke, Location temp_in, SlowPathCode* slow_path) {
4778   // Use the calling convention instead of the location of the receiver, as
4779   // intrinsics may have put the receiver in a different register. In the intrinsics
4780   // slow path, the arguments have been moved to the right place, so here we are
4781   // guaranteed that the receiver is the first register of the calling convention.
4782   InvokeDexCallingConvention calling_convention;
4783   Register receiver = calling_convention.GetRegisterAt(0);
4784   Register temp = XRegisterFrom(temp_in);
4785   size_t method_offset = mirror::Class::EmbeddedVTableEntryOffset(
4786       invoke->GetVTableIndex(), kArm64PointerSize).SizeValue();
4787   Offset class_offset = mirror::Object::ClassOffset();
4788   Offset entry_point = ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArm64PointerSize);
4789 
4790   DCHECK(receiver.IsRegister());
4791 
4792   {
4793     // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted.
4794     EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
4795     // /* HeapReference<Class> */ temp = receiver->klass_
4796     __ Ldr(temp.W(), HeapOperandFrom(LocationFrom(receiver), class_offset));
4797     MaybeRecordImplicitNullCheck(invoke);
4798   }
4799   // Instead of simply (possibly) unpoisoning `temp` here, we should
4800   // emit a read barrier for the previous class reference load.
4801   // intermediate/temporary reference and because the current
4802   // concurrent copying collector keeps the from-space memory
4803   // intact/accessible until the end of the marking phase (the
4804   // concurrent copying collector may not in the future).
4805   GetAssembler()->MaybeUnpoisonHeapReference(temp.W());
4806 
4807   // If we're compiling baseline, update the inline cache.
4808   MaybeGenerateInlineCacheCheck(invoke, temp);
4809 
4810   // temp = temp->GetMethodAt(method_offset);
4811   __ Ldr(temp, MemOperand(temp, method_offset));
4812   // lr = temp->GetEntryPoint();
4813   __ Ldr(lr, MemOperand(temp, entry_point.SizeValue()));
4814   {
4815     // Use a scope to help guarantee that `RecordPcInfo()` records the correct pc.
4816     ExactAssemblyScope eas(GetVIXLAssembler(), kInstructionSize, CodeBufferCheckScope::kExactSize);
4817     // lr();
4818     __ blr(lr);
4819     RecordPcInfo(invoke, invoke->GetDexPc(), slow_path);
4820   }
4821 }
4822 
MoveFromReturnRegister(Location trg,DataType::Type type)4823 void CodeGeneratorARM64::MoveFromReturnRegister(Location trg, DataType::Type type) {
4824   if (!trg.IsValid()) {
4825     DCHECK(type == DataType::Type::kVoid);
4826     return;
4827   }
4828 
4829   DCHECK_NE(type, DataType::Type::kVoid);
4830 
4831   if (DataType::IsIntegralType(type) || type == DataType::Type::kReference) {
4832     Register trg_reg = RegisterFrom(trg, type);
4833     Register res_reg = RegisterFrom(ARM64ReturnLocation(type), type);
4834     __ Mov(trg_reg, res_reg, kDiscardForSameWReg);
4835   } else {
4836     VRegister trg_reg = FPRegisterFrom(trg, type);
4837     VRegister res_reg = FPRegisterFrom(ARM64ReturnLocation(type), type);
4838     __ Fmov(trg_reg, res_reg);
4839   }
4840 }
4841 
VisitInvokePolymorphic(HInvokePolymorphic * invoke)4842 void LocationsBuilderARM64::VisitInvokePolymorphic(HInvokePolymorphic* invoke) {
4843   IntrinsicLocationsBuilderARM64 intrinsic(GetGraph()->GetAllocator(), codegen_);
4844   if (intrinsic.TryDispatch(invoke)) {
4845     return;
4846   }
4847   HandleInvoke(invoke);
4848 }
4849 
VisitInvokePolymorphic(HInvokePolymorphic * invoke)4850 void InstructionCodeGeneratorARM64::VisitInvokePolymorphic(HInvokePolymorphic* invoke) {
4851   if (TryGenerateIntrinsicCode(invoke, codegen_)) {
4852     codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
4853     return;
4854   }
4855   codegen_->GenerateInvokePolymorphicCall(invoke);
4856   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
4857 }
4858 
VisitInvokeCustom(HInvokeCustom * invoke)4859 void LocationsBuilderARM64::VisitInvokeCustom(HInvokeCustom* invoke) {
4860   HandleInvoke(invoke);
4861 }
4862 
VisitInvokeCustom(HInvokeCustom * invoke)4863 void InstructionCodeGeneratorARM64::VisitInvokeCustom(HInvokeCustom* invoke) {
4864   codegen_->GenerateInvokeCustomCall(invoke);
4865   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
4866 }
4867 
NewBootImageIntrinsicPatch(uint32_t intrinsic_data,vixl::aarch64::Label * adrp_label)4868 vixl::aarch64::Label* CodeGeneratorARM64::NewBootImageIntrinsicPatch(
4869     uint32_t intrinsic_data,
4870     vixl::aarch64::Label* adrp_label) {
4871   return NewPcRelativePatch(
4872       /* dex_file= */ nullptr, intrinsic_data, adrp_label, &boot_image_other_patches_);
4873 }
4874 
NewBootImageRelRoPatch(uint32_t boot_image_offset,vixl::aarch64::Label * adrp_label)4875 vixl::aarch64::Label* CodeGeneratorARM64::NewBootImageRelRoPatch(
4876     uint32_t boot_image_offset,
4877     vixl::aarch64::Label* adrp_label) {
4878   return NewPcRelativePatch(
4879       /* dex_file= */ nullptr, boot_image_offset, adrp_label, &boot_image_other_patches_);
4880 }
4881 
NewBootImageMethodPatch(MethodReference target_method,vixl::aarch64::Label * adrp_label)4882 vixl::aarch64::Label* CodeGeneratorARM64::NewBootImageMethodPatch(
4883     MethodReference target_method,
4884     vixl::aarch64::Label* adrp_label) {
4885   return NewPcRelativePatch(
4886       target_method.dex_file, target_method.index, adrp_label, &boot_image_method_patches_);
4887 }
4888 
NewMethodBssEntryPatch(MethodReference target_method,vixl::aarch64::Label * adrp_label)4889 vixl::aarch64::Label* CodeGeneratorARM64::NewMethodBssEntryPatch(
4890     MethodReference target_method,
4891     vixl::aarch64::Label* adrp_label) {
4892   return NewPcRelativePatch(
4893       target_method.dex_file, target_method.index, adrp_label, &method_bss_entry_patches_);
4894 }
4895 
NewBootImageTypePatch(const DexFile & dex_file,dex::TypeIndex type_index,vixl::aarch64::Label * adrp_label)4896 vixl::aarch64::Label* CodeGeneratorARM64::NewBootImageTypePatch(
4897     const DexFile& dex_file,
4898     dex::TypeIndex type_index,
4899     vixl::aarch64::Label* adrp_label) {
4900   return NewPcRelativePatch(&dex_file, type_index.index_, adrp_label, &boot_image_type_patches_);
4901 }
4902 
NewBssEntryTypePatch(HLoadClass * load_class,vixl::aarch64::Label * adrp_label)4903 vixl::aarch64::Label* CodeGeneratorARM64::NewBssEntryTypePatch(
4904     HLoadClass* load_class,
4905     vixl::aarch64::Label* adrp_label) {
4906   const DexFile& dex_file = load_class->GetDexFile();
4907   dex::TypeIndex type_index = load_class->GetTypeIndex();
4908   ArenaDeque<PcRelativePatchInfo>* patches = nullptr;
4909   switch (load_class->GetLoadKind()) {
4910     case HLoadClass::LoadKind::kBssEntry:
4911       patches = &type_bss_entry_patches_;
4912       break;
4913     case HLoadClass::LoadKind::kBssEntryPublic:
4914       patches = &public_type_bss_entry_patches_;
4915       break;
4916     case HLoadClass::LoadKind::kBssEntryPackage:
4917       patches = &package_type_bss_entry_patches_;
4918       break;
4919     default:
4920       LOG(FATAL) << "Unexpected load kind: " << load_class->GetLoadKind();
4921       UNREACHABLE();
4922   }
4923   return NewPcRelativePatch(&dex_file, type_index.index_, adrp_label, patches);
4924 }
4925 
NewBootImageStringPatch(const DexFile & dex_file,dex::StringIndex string_index,vixl::aarch64::Label * adrp_label)4926 vixl::aarch64::Label* CodeGeneratorARM64::NewBootImageStringPatch(
4927     const DexFile& dex_file,
4928     dex::StringIndex string_index,
4929     vixl::aarch64::Label* adrp_label) {
4930   return NewPcRelativePatch(
4931       &dex_file, string_index.index_, adrp_label, &boot_image_string_patches_);
4932 }
4933 
NewStringBssEntryPatch(const DexFile & dex_file,dex::StringIndex string_index,vixl::aarch64::Label * adrp_label)4934 vixl::aarch64::Label* CodeGeneratorARM64::NewStringBssEntryPatch(
4935     const DexFile& dex_file,
4936     dex::StringIndex string_index,
4937     vixl::aarch64::Label* adrp_label) {
4938   return NewPcRelativePatch(&dex_file, string_index.index_, adrp_label, &string_bss_entry_patches_);
4939 }
4940 
NewBootImageJniEntrypointPatch(MethodReference target_method,vixl::aarch64::Label * adrp_label)4941 vixl::aarch64::Label* CodeGeneratorARM64::NewBootImageJniEntrypointPatch(
4942     MethodReference target_method,
4943     vixl::aarch64::Label* adrp_label) {
4944   return NewPcRelativePatch(
4945       target_method.dex_file, target_method.index, adrp_label, &boot_image_jni_entrypoint_patches_);
4946 }
4947 
EmitEntrypointThunkCall(ThreadOffset64 entrypoint_offset)4948 void CodeGeneratorARM64::EmitEntrypointThunkCall(ThreadOffset64 entrypoint_offset) {
4949   DCHECK(!__ AllowMacroInstructions());  // In ExactAssemblyScope.
4950   DCHECK(!GetCompilerOptions().IsJitCompiler());
4951   call_entrypoint_patches_.emplace_back(/*dex_file*/ nullptr, entrypoint_offset.Uint32Value());
4952   vixl::aarch64::Label* bl_label = &call_entrypoint_patches_.back().label;
4953   __ bind(bl_label);
4954   __ bl(static_cast<int64_t>(0));  // Placeholder, patched at link-time.
4955 }
4956 
EmitBakerReadBarrierCbnz(uint32_t custom_data)4957 void CodeGeneratorARM64::EmitBakerReadBarrierCbnz(uint32_t custom_data) {
4958   DCHECK(!__ AllowMacroInstructions());  // In ExactAssemblyScope.
4959   if (GetCompilerOptions().IsJitCompiler()) {
4960     auto it = jit_baker_read_barrier_slow_paths_.FindOrAdd(custom_data);
4961     vixl::aarch64::Label* slow_path_entry = &it->second.label;
4962     __ cbnz(mr, slow_path_entry);
4963   } else {
4964     baker_read_barrier_patches_.emplace_back(custom_data);
4965     vixl::aarch64::Label* cbnz_label = &baker_read_barrier_patches_.back().label;
4966     __ bind(cbnz_label);
4967     __ cbnz(mr, static_cast<int64_t>(0));  // Placeholder, patched at link-time.
4968   }
4969 }
4970 
NewPcRelativePatch(const DexFile * dex_file,uint32_t offset_or_index,vixl::aarch64::Label * adrp_label,ArenaDeque<PcRelativePatchInfo> * patches)4971 vixl::aarch64::Label* CodeGeneratorARM64::NewPcRelativePatch(
4972     const DexFile* dex_file,
4973     uint32_t offset_or_index,
4974     vixl::aarch64::Label* adrp_label,
4975     ArenaDeque<PcRelativePatchInfo>* patches) {
4976   // Add a patch entry and return the label.
4977   patches->emplace_back(dex_file, offset_or_index);
4978   PcRelativePatchInfo* info = &patches->back();
4979   vixl::aarch64::Label* label = &info->label;
4980   // If adrp_label is null, this is the ADRP patch and needs to point to its own label.
4981   info->pc_insn_label = (adrp_label != nullptr) ? adrp_label : label;
4982   return label;
4983 }
4984 
DeduplicateBootImageAddressLiteral(uint64_t address)4985 vixl::aarch64::Literal<uint32_t>* CodeGeneratorARM64::DeduplicateBootImageAddressLiteral(
4986     uint64_t address) {
4987   return DeduplicateUint32Literal(dchecked_integral_cast<uint32_t>(address));
4988 }
4989 
DeduplicateJitStringLiteral(const DexFile & dex_file,dex::StringIndex string_index,Handle<mirror::String> handle)4990 vixl::aarch64::Literal<uint32_t>* CodeGeneratorARM64::DeduplicateJitStringLiteral(
4991     const DexFile& dex_file, dex::StringIndex string_index, Handle<mirror::String> handle) {
4992   ReserveJitStringRoot(StringReference(&dex_file, string_index), handle);
4993   return jit_string_patches_.GetOrCreate(
4994       StringReference(&dex_file, string_index),
4995       [this]() { return __ CreateLiteralDestroyedWithPool<uint32_t>(/* value= */ 0u); });
4996 }
4997 
DeduplicateJitClassLiteral(const DexFile & dex_file,dex::TypeIndex type_index,Handle<mirror::Class> handle)4998 vixl::aarch64::Literal<uint32_t>* CodeGeneratorARM64::DeduplicateJitClassLiteral(
4999     const DexFile& dex_file, dex::TypeIndex type_index, Handle<mirror::Class> handle) {
5000   ReserveJitClassRoot(TypeReference(&dex_file, type_index), handle);
5001   return jit_class_patches_.GetOrCreate(
5002       TypeReference(&dex_file, type_index),
5003       [this]() { return __ CreateLiteralDestroyedWithPool<uint32_t>(/* value= */ 0u); });
5004 }
5005 
EmitAdrpPlaceholder(vixl::aarch64::Label * fixup_label,vixl::aarch64::Register reg)5006 void CodeGeneratorARM64::EmitAdrpPlaceholder(vixl::aarch64::Label* fixup_label,
5007                                              vixl::aarch64::Register reg) {
5008   DCHECK(reg.IsX());
5009   SingleEmissionCheckScope guard(GetVIXLAssembler());
5010   __ Bind(fixup_label);
5011   __ adrp(reg, /* offset placeholder */ static_cast<int64_t>(0));
5012 }
5013 
EmitAddPlaceholder(vixl::aarch64::Label * fixup_label,vixl::aarch64::Register out,vixl::aarch64::Register base)5014 void CodeGeneratorARM64::EmitAddPlaceholder(vixl::aarch64::Label* fixup_label,
5015                                             vixl::aarch64::Register out,
5016                                             vixl::aarch64::Register base) {
5017   DCHECK(out.IsX());
5018   DCHECK(base.IsX());
5019   SingleEmissionCheckScope guard(GetVIXLAssembler());
5020   __ Bind(fixup_label);
5021   __ add(out, base, Operand(/* offset placeholder */ 0));
5022 }
5023 
EmitLdrOffsetPlaceholder(vixl::aarch64::Label * fixup_label,vixl::aarch64::Register out,vixl::aarch64::Register base)5024 void CodeGeneratorARM64::EmitLdrOffsetPlaceholder(vixl::aarch64::Label* fixup_label,
5025                                                   vixl::aarch64::Register out,
5026                                                   vixl::aarch64::Register base) {
5027   DCHECK(base.IsX());
5028   SingleEmissionCheckScope guard(GetVIXLAssembler());
5029   __ Bind(fixup_label);
5030   __ ldr(out, MemOperand(base, /* offset placeholder */ 0));
5031 }
5032 
LoadBootImageRelRoEntry(vixl::aarch64::Register reg,uint32_t boot_image_offset)5033 void CodeGeneratorARM64::LoadBootImageRelRoEntry(vixl::aarch64::Register reg,
5034                                                  uint32_t boot_image_offset) {
5035   DCHECK(reg.IsW());
5036   // Add ADRP with its PC-relative .data.bimg.rel.ro patch.
5037   vixl::aarch64::Label* adrp_label = NewBootImageRelRoPatch(boot_image_offset);
5038   EmitAdrpPlaceholder(adrp_label, reg.X());
5039   // Add LDR with its PC-relative .data.bimg.rel.ro patch.
5040   vixl::aarch64::Label* ldr_label = NewBootImageRelRoPatch(boot_image_offset, adrp_label);
5041   EmitLdrOffsetPlaceholder(ldr_label, reg.W(), reg.X());
5042 }
5043 
LoadBootImageAddress(vixl::aarch64::Register reg,uint32_t boot_image_reference)5044 void CodeGeneratorARM64::LoadBootImageAddress(vixl::aarch64::Register reg,
5045                                               uint32_t boot_image_reference) {
5046   if (GetCompilerOptions().IsBootImage()) {
5047     // Add ADRP with its PC-relative type patch.
5048     vixl::aarch64::Label* adrp_label = NewBootImageIntrinsicPatch(boot_image_reference);
5049     EmitAdrpPlaceholder(adrp_label, reg.X());
5050     // Add ADD with its PC-relative type patch.
5051     vixl::aarch64::Label* add_label = NewBootImageIntrinsicPatch(boot_image_reference, adrp_label);
5052     EmitAddPlaceholder(add_label, reg.X(), reg.X());
5053   } else if (GetCompilerOptions().GetCompilePic()) {
5054     LoadBootImageRelRoEntry(reg, boot_image_reference);
5055   } else {
5056     DCHECK(GetCompilerOptions().IsJitCompiler());
5057     gc::Heap* heap = Runtime::Current()->GetHeap();
5058     DCHECK(!heap->GetBootImageSpaces().empty());
5059     const uint8_t* address = heap->GetBootImageSpaces()[0]->Begin() + boot_image_reference;
5060     __ Ldr(reg.W(), DeduplicateBootImageAddressLiteral(reinterpret_cast<uintptr_t>(address)));
5061   }
5062 }
5063 
LoadTypeForBootImageIntrinsic(vixl::aarch64::Register reg,TypeReference target_type)5064 void CodeGeneratorARM64::LoadTypeForBootImageIntrinsic(vixl::aarch64::Register reg,
5065                                                        TypeReference target_type) {
5066   // Load the class the same way as for HLoadClass::LoadKind::kBootImageLinkTimePcRelative.
5067   DCHECK(GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension());
5068   // Add ADRP with its PC-relative type patch.
5069   vixl::aarch64::Label* adrp_label =
5070       NewBootImageTypePatch(*target_type.dex_file, target_type.TypeIndex());
5071   EmitAdrpPlaceholder(adrp_label, reg.X());
5072   // Add ADD with its PC-relative type patch.
5073   vixl::aarch64::Label* add_label =
5074       NewBootImageTypePatch(*target_type.dex_file, target_type.TypeIndex(), adrp_label);
5075   EmitAddPlaceholder(add_label, reg.X(), reg.X());
5076 }
5077 
LoadIntrinsicDeclaringClass(vixl::aarch64::Register reg,HInvoke * invoke)5078 void CodeGeneratorARM64::LoadIntrinsicDeclaringClass(vixl::aarch64::Register reg, HInvoke* invoke) {
5079   DCHECK_NE(invoke->GetIntrinsic(), Intrinsics::kNone);
5080   if (GetCompilerOptions().IsBootImage()) {
5081     MethodReference target_method = invoke->GetResolvedMethodReference();
5082     dex::TypeIndex type_idx = target_method.dex_file->GetMethodId(target_method.index).class_idx_;
5083     LoadTypeForBootImageIntrinsic(reg, TypeReference(target_method.dex_file, type_idx));
5084   } else {
5085     uint32_t boot_image_offset = GetBootImageOffsetOfIntrinsicDeclaringClass(invoke);
5086     LoadBootImageAddress(reg, boot_image_offset);
5087   }
5088 }
5089 
LoadClassRootForIntrinsic(vixl::aarch64::Register reg,ClassRoot class_root)5090 void CodeGeneratorARM64::LoadClassRootForIntrinsic(vixl::aarch64::Register reg,
5091                                                    ClassRoot class_root) {
5092   if (GetCompilerOptions().IsBootImage()) {
5093     ScopedObjectAccess soa(Thread::Current());
5094     ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
5095     TypeReference target_type(&klass->GetDexFile(), klass->GetDexTypeIndex());
5096     LoadTypeForBootImageIntrinsic(reg, target_type);
5097   } else {
5098     uint32_t boot_image_offset = GetBootImageOffset(class_root);
5099     LoadBootImageAddress(reg, boot_image_offset);
5100   }
5101 }
5102 
5103 template <linker::LinkerPatch (*Factory)(size_t, const DexFile*, uint32_t, uint32_t)>
EmitPcRelativeLinkerPatches(const ArenaDeque<PcRelativePatchInfo> & infos,ArenaVector<linker::LinkerPatch> * linker_patches)5104 inline void CodeGeneratorARM64::EmitPcRelativeLinkerPatches(
5105     const ArenaDeque<PcRelativePatchInfo>& infos,
5106     ArenaVector<linker::LinkerPatch>* linker_patches) {
5107   for (const PcRelativePatchInfo& info : infos) {
5108     linker_patches->push_back(Factory(info.label.GetLocation(),
5109                                       info.target_dex_file,
5110                                       info.pc_insn_label->GetLocation(),
5111                                       info.offset_or_index));
5112   }
5113 }
5114 
5115 template <linker::LinkerPatch (*Factory)(size_t, uint32_t, uint32_t)>
NoDexFileAdapter(size_t literal_offset,const DexFile * target_dex_file,uint32_t pc_insn_offset,uint32_t boot_image_offset)5116 linker::LinkerPatch NoDexFileAdapter(size_t literal_offset,
5117                                      const DexFile* target_dex_file,
5118                                      uint32_t pc_insn_offset,
5119                                      uint32_t boot_image_offset) {
5120   DCHECK(target_dex_file == nullptr);  // Unused for these patches, should be null.
5121   return Factory(literal_offset, pc_insn_offset, boot_image_offset);
5122 }
5123 
EmitLinkerPatches(ArenaVector<linker::LinkerPatch> * linker_patches)5124 void CodeGeneratorARM64::EmitLinkerPatches(ArenaVector<linker::LinkerPatch>* linker_patches) {
5125   DCHECK(linker_patches->empty());
5126   size_t size =
5127       boot_image_method_patches_.size() +
5128       method_bss_entry_patches_.size() +
5129       boot_image_type_patches_.size() +
5130       type_bss_entry_patches_.size() +
5131       public_type_bss_entry_patches_.size() +
5132       package_type_bss_entry_patches_.size() +
5133       boot_image_string_patches_.size() +
5134       string_bss_entry_patches_.size() +
5135       boot_image_jni_entrypoint_patches_.size() +
5136       boot_image_other_patches_.size() +
5137       call_entrypoint_patches_.size() +
5138       baker_read_barrier_patches_.size();
5139   linker_patches->reserve(size);
5140   if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
5141     EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeMethodPatch>(
5142         boot_image_method_patches_, linker_patches);
5143     EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeTypePatch>(
5144         boot_image_type_patches_, linker_patches);
5145     EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeStringPatch>(
5146         boot_image_string_patches_, linker_patches);
5147   } else {
5148     DCHECK(boot_image_method_patches_.empty());
5149     DCHECK(boot_image_type_patches_.empty());
5150     DCHECK(boot_image_string_patches_.empty());
5151   }
5152   if (GetCompilerOptions().IsBootImage()) {
5153     EmitPcRelativeLinkerPatches<NoDexFileAdapter<linker::LinkerPatch::IntrinsicReferencePatch>>(
5154         boot_image_other_patches_, linker_patches);
5155   } else {
5156     EmitPcRelativeLinkerPatches<NoDexFileAdapter<linker::LinkerPatch::DataBimgRelRoPatch>>(
5157         boot_image_other_patches_, linker_patches);
5158   }
5159   EmitPcRelativeLinkerPatches<linker::LinkerPatch::MethodBssEntryPatch>(
5160       method_bss_entry_patches_, linker_patches);
5161   EmitPcRelativeLinkerPatches<linker::LinkerPatch::TypeBssEntryPatch>(
5162       type_bss_entry_patches_, linker_patches);
5163   EmitPcRelativeLinkerPatches<linker::LinkerPatch::PublicTypeBssEntryPatch>(
5164       public_type_bss_entry_patches_, linker_patches);
5165   EmitPcRelativeLinkerPatches<linker::LinkerPatch::PackageTypeBssEntryPatch>(
5166       package_type_bss_entry_patches_, linker_patches);
5167   EmitPcRelativeLinkerPatches<linker::LinkerPatch::StringBssEntryPatch>(
5168       string_bss_entry_patches_, linker_patches);
5169   EmitPcRelativeLinkerPatches<linker::LinkerPatch::RelativeJniEntrypointPatch>(
5170       boot_image_jni_entrypoint_patches_, linker_patches);
5171   for (const PatchInfo<vixl::aarch64::Label>& info : call_entrypoint_patches_) {
5172     DCHECK(info.target_dex_file == nullptr);
5173     linker_patches->push_back(linker::LinkerPatch::CallEntrypointPatch(
5174         info.label.GetLocation(), info.offset_or_index));
5175   }
5176   for (const BakerReadBarrierPatchInfo& info : baker_read_barrier_patches_) {
5177     linker_patches->push_back(linker::LinkerPatch::BakerReadBarrierBranchPatch(
5178         info.label.GetLocation(), info.custom_data));
5179   }
5180   DCHECK_EQ(size, linker_patches->size());
5181 }
5182 
NeedsThunkCode(const linker::LinkerPatch & patch) const5183 bool CodeGeneratorARM64::NeedsThunkCode(const linker::LinkerPatch& patch) const {
5184   return patch.GetType() == linker::LinkerPatch::Type::kCallEntrypoint ||
5185          patch.GetType() == linker::LinkerPatch::Type::kBakerReadBarrierBranch ||
5186          patch.GetType() == linker::LinkerPatch::Type::kCallRelative;
5187 }
5188 
EmitThunkCode(const linker::LinkerPatch & patch,ArenaVector<uint8_t> * code,std::string * debug_name)5189 void CodeGeneratorARM64::EmitThunkCode(const linker::LinkerPatch& patch,
5190                                        /*out*/ ArenaVector<uint8_t>* code,
5191                                        /*out*/ std::string* debug_name) {
5192   Arm64Assembler assembler(GetGraph()->GetAllocator());
5193   switch (patch.GetType()) {
5194     case linker::LinkerPatch::Type::kCallRelative: {
5195       // The thunk just uses the entry point in the ArtMethod. This works even for calls
5196       // to the generic JNI and interpreter trampolines.
5197       Offset offset(ArtMethod::EntryPointFromQuickCompiledCodeOffset(
5198           kArm64PointerSize).Int32Value());
5199       assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0));
5200       if (debug_name != nullptr && GetCompilerOptions().GenerateAnyDebugInfo()) {
5201         *debug_name = "MethodCallThunk";
5202       }
5203       break;
5204     }
5205     case linker::LinkerPatch::Type::kCallEntrypoint: {
5206       Offset offset(patch.EntrypointOffset());
5207       assembler.JumpTo(ManagedRegister(arm64::TR), offset, ManagedRegister(arm64::IP0));
5208       if (debug_name != nullptr && GetCompilerOptions().GenerateAnyDebugInfo()) {
5209         *debug_name = "EntrypointCallThunk_" + std::to_string(offset.Uint32Value());
5210       }
5211       break;
5212     }
5213     case linker::LinkerPatch::Type::kBakerReadBarrierBranch: {
5214       DCHECK_EQ(patch.GetBakerCustomValue2(), 0u);
5215       CompileBakerReadBarrierThunk(assembler, patch.GetBakerCustomValue1(), debug_name);
5216       break;
5217     }
5218     default:
5219       LOG(FATAL) << "Unexpected patch type " << patch.GetType();
5220       UNREACHABLE();
5221   }
5222 
5223   // Ensure we emit the literal pool if any.
5224   assembler.FinalizeCode();
5225   code->resize(assembler.CodeSize());
5226   MemoryRegion code_region(code->data(), code->size());
5227   assembler.FinalizeInstructions(code_region);
5228 }
5229 
DeduplicateUint32Literal(uint32_t value)5230 vixl::aarch64::Literal<uint32_t>* CodeGeneratorARM64::DeduplicateUint32Literal(uint32_t value) {
5231   return uint32_literals_.GetOrCreate(
5232       value,
5233       [this, value]() { return __ CreateLiteralDestroyedWithPool<uint32_t>(value); });
5234 }
5235 
DeduplicateUint64Literal(uint64_t value)5236 vixl::aarch64::Literal<uint64_t>* CodeGeneratorARM64::DeduplicateUint64Literal(uint64_t value) {
5237   return uint64_literals_.GetOrCreate(
5238       value,
5239       [this, value]() { return __ CreateLiteralDestroyedWithPool<uint64_t>(value); });
5240 }
5241 
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)5242 void InstructionCodeGeneratorARM64::VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
5243   // Explicit clinit checks triggered by static invokes must have been pruned by
5244   // art::PrepareForRegisterAllocation.
5245   DCHECK(!invoke->IsStaticWithExplicitClinitCheck());
5246 
5247   if (TryGenerateIntrinsicCode(invoke, codegen_)) {
5248     codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5249     return;
5250   }
5251 
5252   LocationSummary* locations = invoke->GetLocations();
5253   codegen_->GenerateStaticOrDirectCall(
5254       invoke, locations->HasTemps() ? locations->GetTemp(0) : Location::NoLocation());
5255 
5256   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5257 }
5258 
VisitInvokeVirtual(HInvokeVirtual * invoke)5259 void InstructionCodeGeneratorARM64::VisitInvokeVirtual(HInvokeVirtual* invoke) {
5260   if (TryGenerateIntrinsicCode(invoke, codegen_)) {
5261     codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5262     return;
5263   }
5264 
5265   {
5266     // Ensure that between the BLR (emitted by GenerateVirtualCall) and RecordPcInfo there
5267     // are no pools emitted.
5268     EmissionCheckScope guard(GetVIXLAssembler(), kInvokeCodeMarginSizeInBytes);
5269     codegen_->GenerateVirtualCall(invoke, invoke->GetLocations()->GetTemp(0));
5270     DCHECK(!codegen_->IsLeafMethod());
5271   }
5272 
5273   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5274 }
5275 
GetSupportedLoadClassKind(HLoadClass::LoadKind desired_class_load_kind)5276 HLoadClass::LoadKind CodeGeneratorARM64::GetSupportedLoadClassKind(
5277     HLoadClass::LoadKind desired_class_load_kind) {
5278   switch (desired_class_load_kind) {
5279     case HLoadClass::LoadKind::kInvalid:
5280       LOG(FATAL) << "UNREACHABLE";
5281       UNREACHABLE();
5282     case HLoadClass::LoadKind::kReferrersClass:
5283       break;
5284     case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
5285     case HLoadClass::LoadKind::kBootImageRelRo:
5286     case HLoadClass::LoadKind::kBssEntry:
5287     case HLoadClass::LoadKind::kBssEntryPublic:
5288     case HLoadClass::LoadKind::kBssEntryPackage:
5289       DCHECK(!GetCompilerOptions().IsJitCompiler());
5290       break;
5291     case HLoadClass::LoadKind::kJitBootImageAddress:
5292     case HLoadClass::LoadKind::kJitTableAddress:
5293       DCHECK(GetCompilerOptions().IsJitCompiler());
5294       break;
5295     case HLoadClass::LoadKind::kRuntimeCall:
5296       break;
5297   }
5298   return desired_class_load_kind;
5299 }
5300 
VisitLoadClass(HLoadClass * cls)5301 void LocationsBuilderARM64::VisitLoadClass(HLoadClass* cls) {
5302   HLoadClass::LoadKind load_kind = cls->GetLoadKind();
5303   if (load_kind == HLoadClass::LoadKind::kRuntimeCall) {
5304     InvokeRuntimeCallingConvention calling_convention;
5305     CodeGenerator::CreateLoadClassRuntimeCallLocationSummary(
5306         cls,
5307         LocationFrom(calling_convention.GetRegisterAt(0)),
5308         LocationFrom(vixl::aarch64::x0));
5309     DCHECK(calling_convention.GetRegisterAt(0).Is(vixl::aarch64::x0));
5310     return;
5311   }
5312   DCHECK_EQ(cls->NeedsAccessCheck(),
5313             load_kind == HLoadClass::LoadKind::kBssEntryPublic ||
5314                 load_kind == HLoadClass::LoadKind::kBssEntryPackage);
5315 
5316   const bool requires_read_barrier = kEmitCompilerReadBarrier && !cls->IsInBootImage();
5317   LocationSummary::CallKind call_kind = (cls->NeedsEnvironment() || requires_read_barrier)
5318       ? LocationSummary::kCallOnSlowPath
5319       : LocationSummary::kNoCall;
5320   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(cls, call_kind);
5321   if (kUseBakerReadBarrier && requires_read_barrier && !cls->NeedsEnvironment()) {
5322     locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty());  // No caller-save registers.
5323   }
5324 
5325   if (load_kind == HLoadClass::LoadKind::kReferrersClass) {
5326     locations->SetInAt(0, Location::RequiresRegister());
5327   }
5328   locations->SetOut(Location::RequiresRegister());
5329   if (cls->GetLoadKind() == HLoadClass::LoadKind::kBssEntry) {
5330     if (!kUseReadBarrier || kUseBakerReadBarrier) {
5331       // Rely on the type resolution or initialization and marking to save everything we need.
5332       locations->SetCustomSlowPathCallerSaves(OneRegInReferenceOutSaveEverythingCallerSaves());
5333     } else {
5334       // For non-Baker read barrier we have a temp-clobbering call.
5335     }
5336   }
5337 }
5338 
5339 // NO_THREAD_SAFETY_ANALYSIS as we manipulate handles whose internal object we know does not
5340 // move.
VisitLoadClass(HLoadClass * cls)5341 void InstructionCodeGeneratorARM64::VisitLoadClass(HLoadClass* cls) NO_THREAD_SAFETY_ANALYSIS {
5342   HLoadClass::LoadKind load_kind = cls->GetLoadKind();
5343   if (load_kind == HLoadClass::LoadKind::kRuntimeCall) {
5344     codegen_->GenerateLoadClassRuntimeCall(cls);
5345     codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5346     return;
5347   }
5348   DCHECK_EQ(cls->NeedsAccessCheck(),
5349             load_kind == HLoadClass::LoadKind::kBssEntryPublic ||
5350                 load_kind == HLoadClass::LoadKind::kBssEntryPackage);
5351 
5352   Location out_loc = cls->GetLocations()->Out();
5353   Register out = OutputRegister(cls);
5354 
5355   const ReadBarrierOption read_barrier_option = cls->IsInBootImage()
5356       ? kWithoutReadBarrier
5357       : kCompilerReadBarrierOption;
5358   bool generate_null_check = false;
5359   switch (load_kind) {
5360     case HLoadClass::LoadKind::kReferrersClass: {
5361       DCHECK(!cls->CanCallRuntime());
5362       DCHECK(!cls->MustGenerateClinitCheck());
5363       // /* GcRoot<mirror::Class> */ out = current_method->declaring_class_
5364       Register current_method = InputRegisterAt(cls, 0);
5365       codegen_->GenerateGcRootFieldLoad(cls,
5366                                         out_loc,
5367                                         current_method,
5368                                         ArtMethod::DeclaringClassOffset().Int32Value(),
5369                                         /* fixup_label= */ nullptr,
5370                                         read_barrier_option);
5371       break;
5372     }
5373     case HLoadClass::LoadKind::kBootImageLinkTimePcRelative: {
5374       DCHECK(codegen_->GetCompilerOptions().IsBootImage() ||
5375              codegen_->GetCompilerOptions().IsBootImageExtension());
5376       DCHECK_EQ(read_barrier_option, kWithoutReadBarrier);
5377       // Add ADRP with its PC-relative type patch.
5378       const DexFile& dex_file = cls->GetDexFile();
5379       dex::TypeIndex type_index = cls->GetTypeIndex();
5380       vixl::aarch64::Label* adrp_label = codegen_->NewBootImageTypePatch(dex_file, type_index);
5381       codegen_->EmitAdrpPlaceholder(adrp_label, out.X());
5382       // Add ADD with its PC-relative type patch.
5383       vixl::aarch64::Label* add_label =
5384           codegen_->NewBootImageTypePatch(dex_file, type_index, adrp_label);
5385       codegen_->EmitAddPlaceholder(add_label, out.X(), out.X());
5386       break;
5387     }
5388     case HLoadClass::LoadKind::kBootImageRelRo: {
5389       DCHECK(!codegen_->GetCompilerOptions().IsBootImage());
5390       uint32_t boot_image_offset = CodeGenerator::GetBootImageOffset(cls);
5391       codegen_->LoadBootImageRelRoEntry(out.W(), boot_image_offset);
5392       break;
5393     }
5394     case HLoadClass::LoadKind::kBssEntry:
5395     case HLoadClass::LoadKind::kBssEntryPublic:
5396     case HLoadClass::LoadKind::kBssEntryPackage: {
5397       // Add ADRP with its PC-relative Class .bss entry patch.
5398       vixl::aarch64::Register temp = XRegisterFrom(out_loc);
5399       vixl::aarch64::Label* adrp_label = codegen_->NewBssEntryTypePatch(cls);
5400       codegen_->EmitAdrpPlaceholder(adrp_label, temp);
5401       // Add LDR with its PC-relative Class .bss entry patch.
5402       vixl::aarch64::Label* ldr_label = codegen_->NewBssEntryTypePatch(cls, adrp_label);
5403       // /* GcRoot<mirror::Class> */ out = *(base_address + offset)  /* PC-relative */
5404       // All aligned loads are implicitly atomic consume operations on ARM64.
5405       codegen_->GenerateGcRootFieldLoad(cls,
5406                                         out_loc,
5407                                         temp,
5408                                         /* offset placeholder */ 0u,
5409                                         ldr_label,
5410                                         read_barrier_option);
5411       generate_null_check = true;
5412       break;
5413     }
5414     case HLoadClass::LoadKind::kJitBootImageAddress: {
5415       DCHECK_EQ(read_barrier_option, kWithoutReadBarrier);
5416       uint32_t address = reinterpret_cast32<uint32_t>(cls->GetClass().Get());
5417       DCHECK_NE(address, 0u);
5418       __ Ldr(out.W(), codegen_->DeduplicateBootImageAddressLiteral(address));
5419       break;
5420     }
5421     case HLoadClass::LoadKind::kJitTableAddress: {
5422       __ Ldr(out, codegen_->DeduplicateJitClassLiteral(cls->GetDexFile(),
5423                                                        cls->GetTypeIndex(),
5424                                                        cls->GetClass()));
5425       codegen_->GenerateGcRootFieldLoad(cls,
5426                                         out_loc,
5427                                         out.X(),
5428                                         /* offset= */ 0,
5429                                         /* fixup_label= */ nullptr,
5430                                         read_barrier_option);
5431       break;
5432     }
5433     case HLoadClass::LoadKind::kRuntimeCall:
5434     case HLoadClass::LoadKind::kInvalid:
5435       LOG(FATAL) << "UNREACHABLE";
5436       UNREACHABLE();
5437   }
5438 
5439   bool do_clinit = cls->MustGenerateClinitCheck();
5440   if (generate_null_check || do_clinit) {
5441     DCHECK(cls->CanCallRuntime());
5442     SlowPathCodeARM64* slow_path =
5443         new (codegen_->GetScopedAllocator()) LoadClassSlowPathARM64(cls, cls);
5444     codegen_->AddSlowPath(slow_path);
5445     if (generate_null_check) {
5446       __ Cbz(out, slow_path->GetEntryLabel());
5447     }
5448     if (cls->MustGenerateClinitCheck()) {
5449       GenerateClassInitializationCheck(slow_path, out);
5450     } else {
5451       __ Bind(slow_path->GetExitLabel());
5452     }
5453     codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5454   }
5455 }
5456 
VisitLoadMethodHandle(HLoadMethodHandle * load)5457 void LocationsBuilderARM64::VisitLoadMethodHandle(HLoadMethodHandle* load) {
5458   InvokeRuntimeCallingConvention calling_convention;
5459   Location location = LocationFrom(calling_convention.GetRegisterAt(0));
5460   CodeGenerator::CreateLoadMethodHandleRuntimeCallLocationSummary(load, location, location);
5461 }
5462 
VisitLoadMethodHandle(HLoadMethodHandle * load)5463 void InstructionCodeGeneratorARM64::VisitLoadMethodHandle(HLoadMethodHandle* load) {
5464   codegen_->GenerateLoadMethodHandleRuntimeCall(load);
5465 }
5466 
VisitLoadMethodType(HLoadMethodType * load)5467 void LocationsBuilderARM64::VisitLoadMethodType(HLoadMethodType* load) {
5468   InvokeRuntimeCallingConvention calling_convention;
5469   Location location = LocationFrom(calling_convention.GetRegisterAt(0));
5470   CodeGenerator::CreateLoadMethodTypeRuntimeCallLocationSummary(load, location, location);
5471 }
5472 
VisitLoadMethodType(HLoadMethodType * load)5473 void InstructionCodeGeneratorARM64::VisitLoadMethodType(HLoadMethodType* load) {
5474   codegen_->GenerateLoadMethodTypeRuntimeCall(load);
5475 }
5476 
GetExceptionTlsAddress()5477 static MemOperand GetExceptionTlsAddress() {
5478   return MemOperand(tr, Thread::ExceptionOffset<kArm64PointerSize>().Int32Value());
5479 }
5480 
VisitLoadException(HLoadException * load)5481 void LocationsBuilderARM64::VisitLoadException(HLoadException* load) {
5482   LocationSummary* locations =
5483       new (GetGraph()->GetAllocator()) LocationSummary(load, LocationSummary::kNoCall);
5484   locations->SetOut(Location::RequiresRegister());
5485 }
5486 
VisitLoadException(HLoadException * instruction)5487 void InstructionCodeGeneratorARM64::VisitLoadException(HLoadException* instruction) {
5488   __ Ldr(OutputRegister(instruction), GetExceptionTlsAddress());
5489 }
5490 
VisitClearException(HClearException * clear)5491 void LocationsBuilderARM64::VisitClearException(HClearException* clear) {
5492   new (GetGraph()->GetAllocator()) LocationSummary(clear, LocationSummary::kNoCall);
5493 }
5494 
VisitClearException(HClearException * clear ATTRIBUTE_UNUSED)5495 void InstructionCodeGeneratorARM64::VisitClearException(HClearException* clear ATTRIBUTE_UNUSED) {
5496   __ Str(wzr, GetExceptionTlsAddress());
5497 }
5498 
GetSupportedLoadStringKind(HLoadString::LoadKind desired_string_load_kind)5499 HLoadString::LoadKind CodeGeneratorARM64::GetSupportedLoadStringKind(
5500     HLoadString::LoadKind desired_string_load_kind) {
5501   switch (desired_string_load_kind) {
5502     case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
5503     case HLoadString::LoadKind::kBootImageRelRo:
5504     case HLoadString::LoadKind::kBssEntry:
5505       DCHECK(!GetCompilerOptions().IsJitCompiler());
5506       break;
5507     case HLoadString::LoadKind::kJitBootImageAddress:
5508     case HLoadString::LoadKind::kJitTableAddress:
5509       DCHECK(GetCompilerOptions().IsJitCompiler());
5510       break;
5511     case HLoadString::LoadKind::kRuntimeCall:
5512       break;
5513   }
5514   return desired_string_load_kind;
5515 }
5516 
VisitLoadString(HLoadString * load)5517 void LocationsBuilderARM64::VisitLoadString(HLoadString* load) {
5518   LocationSummary::CallKind call_kind = CodeGenerator::GetLoadStringCallKind(load);
5519   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(load, call_kind);
5520   if (load->GetLoadKind() == HLoadString::LoadKind::kRuntimeCall) {
5521     InvokeRuntimeCallingConvention calling_convention;
5522     locations->SetOut(calling_convention.GetReturnLocation(load->GetType()));
5523   } else {
5524     locations->SetOut(Location::RequiresRegister());
5525     if (load->GetLoadKind() == HLoadString::LoadKind::kBssEntry) {
5526       if (!kUseReadBarrier || kUseBakerReadBarrier) {
5527         // Rely on the pResolveString and marking to save everything we need.
5528         locations->SetCustomSlowPathCallerSaves(OneRegInReferenceOutSaveEverythingCallerSaves());
5529       } else {
5530         // For non-Baker read barrier we have a temp-clobbering call.
5531       }
5532     }
5533   }
5534 }
5535 
5536 // NO_THREAD_SAFETY_ANALYSIS as we manipulate handles whose internal object we know does not
5537 // move.
VisitLoadString(HLoadString * load)5538 void InstructionCodeGeneratorARM64::VisitLoadString(HLoadString* load) NO_THREAD_SAFETY_ANALYSIS {
5539   Register out = OutputRegister(load);
5540   Location out_loc = load->GetLocations()->Out();
5541 
5542   switch (load->GetLoadKind()) {
5543     case HLoadString::LoadKind::kBootImageLinkTimePcRelative: {
5544       DCHECK(codegen_->GetCompilerOptions().IsBootImage() ||
5545              codegen_->GetCompilerOptions().IsBootImageExtension());
5546       // Add ADRP with its PC-relative String patch.
5547       const DexFile& dex_file = load->GetDexFile();
5548       const dex::StringIndex string_index = load->GetStringIndex();
5549       vixl::aarch64::Label* adrp_label = codegen_->NewBootImageStringPatch(dex_file, string_index);
5550       codegen_->EmitAdrpPlaceholder(adrp_label, out.X());
5551       // Add ADD with its PC-relative String patch.
5552       vixl::aarch64::Label* add_label =
5553           codegen_->NewBootImageStringPatch(dex_file, string_index, adrp_label);
5554       codegen_->EmitAddPlaceholder(add_label, out.X(), out.X());
5555       return;
5556     }
5557     case HLoadString::LoadKind::kBootImageRelRo: {
5558       DCHECK(!codegen_->GetCompilerOptions().IsBootImage());
5559       uint32_t boot_image_offset = CodeGenerator::GetBootImageOffset(load);
5560       codegen_->LoadBootImageRelRoEntry(out.W(), boot_image_offset);
5561       return;
5562     }
5563     case HLoadString::LoadKind::kBssEntry: {
5564       // Add ADRP with its PC-relative String .bss entry patch.
5565       const DexFile& dex_file = load->GetDexFile();
5566       const dex::StringIndex string_index = load->GetStringIndex();
5567       Register temp = XRegisterFrom(out_loc);
5568       vixl::aarch64::Label* adrp_label = codegen_->NewStringBssEntryPatch(dex_file, string_index);
5569       codegen_->EmitAdrpPlaceholder(adrp_label, temp);
5570       // Add LDR with its PC-relative String .bss entry patch.
5571       vixl::aarch64::Label* ldr_label =
5572           codegen_->NewStringBssEntryPatch(dex_file, string_index, adrp_label);
5573       // /* GcRoot<mirror::String> */ out = *(base_address + offset)  /* PC-relative */
5574       // All aligned loads are implicitly atomic consume operations on ARM64.
5575       codegen_->GenerateGcRootFieldLoad(load,
5576                                         out_loc,
5577                                         temp,
5578                                         /* offset placeholder */ 0u,
5579                                         ldr_label,
5580                                         kCompilerReadBarrierOption);
5581       SlowPathCodeARM64* slow_path =
5582           new (codegen_->GetScopedAllocator()) LoadStringSlowPathARM64(load);
5583       codegen_->AddSlowPath(slow_path);
5584       __ Cbz(out.X(), slow_path->GetEntryLabel());
5585       __ Bind(slow_path->GetExitLabel());
5586       codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5587       return;
5588     }
5589     case HLoadString::LoadKind::kJitBootImageAddress: {
5590       uint32_t address = reinterpret_cast32<uint32_t>(load->GetString().Get());
5591       DCHECK_NE(address, 0u);
5592       __ Ldr(out.W(), codegen_->DeduplicateBootImageAddressLiteral(address));
5593       return;
5594     }
5595     case HLoadString::LoadKind::kJitTableAddress: {
5596       __ Ldr(out, codegen_->DeduplicateJitStringLiteral(load->GetDexFile(),
5597                                                         load->GetStringIndex(),
5598                                                         load->GetString()));
5599       codegen_->GenerateGcRootFieldLoad(load,
5600                                         out_loc,
5601                                         out.X(),
5602                                         /* offset= */ 0,
5603                                         /* fixup_label= */ nullptr,
5604                                         kCompilerReadBarrierOption);
5605       return;
5606     }
5607     default:
5608       break;
5609   }
5610 
5611   // TODO: Re-add the compiler code to do string dex cache lookup again.
5612   InvokeRuntimeCallingConvention calling_convention;
5613   DCHECK_EQ(calling_convention.GetRegisterAt(0).GetCode(), out.GetCode());
5614   __ Mov(calling_convention.GetRegisterAt(0).W(), load->GetStringIndex().index_);
5615   codegen_->InvokeRuntime(kQuickResolveString, load, load->GetDexPc());
5616   CheckEntrypointTypes<kQuickResolveString, void*, uint32_t>();
5617   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5618 }
5619 
VisitLongConstant(HLongConstant * constant)5620 void LocationsBuilderARM64::VisitLongConstant(HLongConstant* constant) {
5621   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(constant);
5622   locations->SetOut(Location::ConstantLocation(constant));
5623 }
5624 
VisitLongConstant(HLongConstant * constant ATTRIBUTE_UNUSED)5625 void InstructionCodeGeneratorARM64::VisitLongConstant(HLongConstant* constant ATTRIBUTE_UNUSED) {
5626   // Will be generated at use site.
5627 }
5628 
VisitMonitorOperation(HMonitorOperation * instruction)5629 void LocationsBuilderARM64::VisitMonitorOperation(HMonitorOperation* instruction) {
5630   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
5631       instruction, LocationSummary::kCallOnMainOnly);
5632   InvokeRuntimeCallingConvention calling_convention;
5633   locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
5634 }
5635 
VisitMonitorOperation(HMonitorOperation * instruction)5636 void InstructionCodeGeneratorARM64::VisitMonitorOperation(HMonitorOperation* instruction) {
5637   codegen_->InvokeRuntime(instruction->IsEnter() ? kQuickLockObject : kQuickUnlockObject,
5638                           instruction,
5639                           instruction->GetDexPc());
5640   if (instruction->IsEnter()) {
5641     CheckEntrypointTypes<kQuickLockObject, void, mirror::Object*>();
5642   } else {
5643     CheckEntrypointTypes<kQuickUnlockObject, void, mirror::Object*>();
5644   }
5645   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5646 }
5647 
VisitMul(HMul * mul)5648 void LocationsBuilderARM64::VisitMul(HMul* mul) {
5649   LocationSummary* locations =
5650       new (GetGraph()->GetAllocator()) LocationSummary(mul, LocationSummary::kNoCall);
5651   switch (mul->GetResultType()) {
5652     case DataType::Type::kInt32:
5653     case DataType::Type::kInt64:
5654       locations->SetInAt(0, Location::RequiresRegister());
5655       locations->SetInAt(1, Location::RequiresRegister());
5656       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5657       break;
5658 
5659     case DataType::Type::kFloat32:
5660     case DataType::Type::kFloat64:
5661       locations->SetInAt(0, Location::RequiresFpuRegister());
5662       locations->SetInAt(1, Location::RequiresFpuRegister());
5663       locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
5664       break;
5665 
5666     default:
5667       LOG(FATAL) << "Unexpected mul type " << mul->GetResultType();
5668   }
5669 }
5670 
VisitMul(HMul * mul)5671 void InstructionCodeGeneratorARM64::VisitMul(HMul* mul) {
5672   switch (mul->GetResultType()) {
5673     case DataType::Type::kInt32:
5674     case DataType::Type::kInt64:
5675       __ Mul(OutputRegister(mul), InputRegisterAt(mul, 0), InputRegisterAt(mul, 1));
5676       break;
5677 
5678     case DataType::Type::kFloat32:
5679     case DataType::Type::kFloat64:
5680       __ Fmul(OutputFPRegister(mul), InputFPRegisterAt(mul, 0), InputFPRegisterAt(mul, 1));
5681       break;
5682 
5683     default:
5684       LOG(FATAL) << "Unexpected mul type " << mul->GetResultType();
5685   }
5686 }
5687 
VisitNeg(HNeg * neg)5688 void LocationsBuilderARM64::VisitNeg(HNeg* neg) {
5689   LocationSummary* locations =
5690       new (GetGraph()->GetAllocator()) LocationSummary(neg, LocationSummary::kNoCall);
5691   switch (neg->GetResultType()) {
5692     case DataType::Type::kInt32:
5693     case DataType::Type::kInt64:
5694       locations->SetInAt(0, ARM64EncodableConstantOrRegister(neg->InputAt(0), neg));
5695       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5696       break;
5697 
5698     case DataType::Type::kFloat32:
5699     case DataType::Type::kFloat64:
5700       locations->SetInAt(0, Location::RequiresFpuRegister());
5701       locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
5702       break;
5703 
5704     default:
5705       LOG(FATAL) << "Unexpected neg type " << neg->GetResultType();
5706   }
5707 }
5708 
VisitNeg(HNeg * neg)5709 void InstructionCodeGeneratorARM64::VisitNeg(HNeg* neg) {
5710   switch (neg->GetResultType()) {
5711     case DataType::Type::kInt32:
5712     case DataType::Type::kInt64:
5713       __ Neg(OutputRegister(neg), InputOperandAt(neg, 0));
5714       break;
5715 
5716     case DataType::Type::kFloat32:
5717     case DataType::Type::kFloat64:
5718       __ Fneg(OutputFPRegister(neg), InputFPRegisterAt(neg, 0));
5719       break;
5720 
5721     default:
5722       LOG(FATAL) << "Unexpected neg type " << neg->GetResultType();
5723   }
5724 }
5725 
VisitNewArray(HNewArray * instruction)5726 void LocationsBuilderARM64::VisitNewArray(HNewArray* instruction) {
5727   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
5728       instruction, LocationSummary::kCallOnMainOnly);
5729   InvokeRuntimeCallingConvention calling_convention;
5730   locations->SetOut(LocationFrom(x0));
5731   locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
5732   locations->SetInAt(1, LocationFrom(calling_convention.GetRegisterAt(1)));
5733 }
5734 
VisitNewArray(HNewArray * instruction)5735 void InstructionCodeGeneratorARM64::VisitNewArray(HNewArray* instruction) {
5736   // Note: if heap poisoning is enabled, the entry point takes care of poisoning the reference.
5737   QuickEntrypointEnum entrypoint = CodeGenerator::GetArrayAllocationEntrypoint(instruction);
5738   codegen_->InvokeRuntime(entrypoint, instruction, instruction->GetDexPc());
5739   CheckEntrypointTypes<kQuickAllocArrayResolved, void*, mirror::Class*, int32_t>();
5740   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5741 }
5742 
VisitNewInstance(HNewInstance * instruction)5743 void LocationsBuilderARM64::VisitNewInstance(HNewInstance* instruction) {
5744   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
5745       instruction, LocationSummary::kCallOnMainOnly);
5746   InvokeRuntimeCallingConvention calling_convention;
5747   locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
5748   locations->SetOut(calling_convention.GetReturnLocation(DataType::Type::kReference));
5749 }
5750 
VisitNewInstance(HNewInstance * instruction)5751 void InstructionCodeGeneratorARM64::VisitNewInstance(HNewInstance* instruction) {
5752   codegen_->InvokeRuntime(instruction->GetEntrypoint(), instruction, instruction->GetDexPc());
5753   CheckEntrypointTypes<kQuickAllocObjectWithChecks, void*, mirror::Class*>();
5754   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
5755 }
5756 
VisitNot(HNot * instruction)5757 void LocationsBuilderARM64::VisitNot(HNot* instruction) {
5758   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
5759   locations->SetInAt(0, Location::RequiresRegister());
5760   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5761 }
5762 
VisitNot(HNot * instruction)5763 void InstructionCodeGeneratorARM64::VisitNot(HNot* instruction) {
5764   switch (instruction->GetResultType()) {
5765     case DataType::Type::kInt32:
5766     case DataType::Type::kInt64:
5767       __ Mvn(OutputRegister(instruction), InputOperandAt(instruction, 0));
5768       break;
5769 
5770     default:
5771       LOG(FATAL) << "Unexpected type for not operation " << instruction->GetResultType();
5772   }
5773 }
5774 
VisitBooleanNot(HBooleanNot * instruction)5775 void LocationsBuilderARM64::VisitBooleanNot(HBooleanNot* instruction) {
5776   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
5777   locations->SetInAt(0, Location::RequiresRegister());
5778   locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5779 }
5780 
VisitBooleanNot(HBooleanNot * instruction)5781 void InstructionCodeGeneratorARM64::VisitBooleanNot(HBooleanNot* instruction) {
5782   __ Eor(OutputRegister(instruction), InputRegisterAt(instruction, 0), vixl::aarch64::Operand(1));
5783 }
5784 
VisitNullCheck(HNullCheck * instruction)5785 void LocationsBuilderARM64::VisitNullCheck(HNullCheck* instruction) {
5786   LocationSummary* locations = codegen_->CreateThrowingSlowPathLocations(instruction);
5787   locations->SetInAt(0, Location::RequiresRegister());
5788 }
5789 
GenerateImplicitNullCheck(HNullCheck * instruction)5790 void CodeGeneratorARM64::GenerateImplicitNullCheck(HNullCheck* instruction) {
5791   if (CanMoveNullCheckToUser(instruction)) {
5792     return;
5793   }
5794   {
5795     // Ensure that between load and RecordPcInfo there are no pools emitted.
5796     EmissionCheckScope guard(GetVIXLAssembler(), kMaxMacroInstructionSizeInBytes);
5797     Location obj = instruction->GetLocations()->InAt(0);
5798     __ Ldr(wzr, HeapOperandFrom(obj, Offset(0)));
5799     RecordPcInfo(instruction, instruction->GetDexPc());
5800   }
5801 }
5802 
GenerateExplicitNullCheck(HNullCheck * instruction)5803 void CodeGeneratorARM64::GenerateExplicitNullCheck(HNullCheck* instruction) {
5804   SlowPathCodeARM64* slow_path = new (GetScopedAllocator()) NullCheckSlowPathARM64(instruction);
5805   AddSlowPath(slow_path);
5806 
5807   LocationSummary* locations = instruction->GetLocations();
5808   Location obj = locations->InAt(0);
5809 
5810   __ Cbz(RegisterFrom(obj, instruction->InputAt(0)->GetType()), slow_path->GetEntryLabel());
5811 }
5812 
VisitNullCheck(HNullCheck * instruction)5813 void InstructionCodeGeneratorARM64::VisitNullCheck(HNullCheck* instruction) {
5814   codegen_->GenerateNullCheck(instruction);
5815 }
5816 
VisitOr(HOr * instruction)5817 void LocationsBuilderARM64::VisitOr(HOr* instruction) {
5818   HandleBinaryOp(instruction);
5819 }
5820 
VisitOr(HOr * instruction)5821 void InstructionCodeGeneratorARM64::VisitOr(HOr* instruction) {
5822   HandleBinaryOp(instruction);
5823 }
5824 
VisitParallelMove(HParallelMove * instruction ATTRIBUTE_UNUSED)5825 void LocationsBuilderARM64::VisitParallelMove(HParallelMove* instruction ATTRIBUTE_UNUSED) {
5826   LOG(FATAL) << "Unreachable";
5827 }
5828 
VisitParallelMove(HParallelMove * instruction)5829 void InstructionCodeGeneratorARM64::VisitParallelMove(HParallelMove* instruction) {
5830   if (instruction->GetNext()->IsSuspendCheck() &&
5831       instruction->GetBlock()->GetLoopInformation() != nullptr) {
5832     HSuspendCheck* suspend_check = instruction->GetNext()->AsSuspendCheck();
5833     // The back edge will generate the suspend check.
5834     codegen_->ClearSpillSlotsFromLoopPhisInStackMap(suspend_check, instruction);
5835   }
5836 
5837   codegen_->GetMoveResolver()->EmitNativeCode(instruction);
5838 }
5839 
VisitParameterValue(HParameterValue * instruction)5840 void LocationsBuilderARM64::VisitParameterValue(HParameterValue* instruction) {
5841   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
5842   Location location = parameter_visitor_.GetNextLocation(instruction->GetType());
5843   if (location.IsStackSlot()) {
5844     location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
5845   } else if (location.IsDoubleStackSlot()) {
5846     location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
5847   }
5848   locations->SetOut(location);
5849 }
5850 
VisitParameterValue(HParameterValue * instruction ATTRIBUTE_UNUSED)5851 void InstructionCodeGeneratorARM64::VisitParameterValue(
5852     HParameterValue* instruction ATTRIBUTE_UNUSED) {
5853   // Nothing to do, the parameter is already at its location.
5854 }
5855 
VisitCurrentMethod(HCurrentMethod * instruction)5856 void LocationsBuilderARM64::VisitCurrentMethod(HCurrentMethod* instruction) {
5857   LocationSummary* locations =
5858       new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
5859   locations->SetOut(LocationFrom(kArtMethodRegister));
5860 }
5861 
VisitCurrentMethod(HCurrentMethod * instruction ATTRIBUTE_UNUSED)5862 void InstructionCodeGeneratorARM64::VisitCurrentMethod(
5863     HCurrentMethod* instruction ATTRIBUTE_UNUSED) {
5864   // Nothing to do, the method is already at its location.
5865 }
5866 
VisitPhi(HPhi * instruction)5867 void LocationsBuilderARM64::VisitPhi(HPhi* instruction) {
5868   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
5869   for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
5870     locations->SetInAt(i, Location::Any());
5871   }
5872   locations->SetOut(Location::Any());
5873 }
5874 
VisitPhi(HPhi * instruction ATTRIBUTE_UNUSED)5875 void InstructionCodeGeneratorARM64::VisitPhi(HPhi* instruction ATTRIBUTE_UNUSED) {
5876   LOG(FATAL) << "Unreachable";
5877 }
5878 
VisitRem(HRem * rem)5879 void LocationsBuilderARM64::VisitRem(HRem* rem) {
5880   DataType::Type type = rem->GetResultType();
5881   LocationSummary::CallKind call_kind =
5882       DataType::IsFloatingPointType(type) ? LocationSummary::kCallOnMainOnly
5883                                            : LocationSummary::kNoCall;
5884   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(rem, call_kind);
5885 
5886   switch (type) {
5887     case DataType::Type::kInt32:
5888     case DataType::Type::kInt64:
5889       locations->SetInAt(0, Location::RequiresRegister());
5890       locations->SetInAt(1, Location::RegisterOrConstant(rem->InputAt(1)));
5891       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
5892       break;
5893 
5894     case DataType::Type::kFloat32:
5895     case DataType::Type::kFloat64: {
5896       InvokeRuntimeCallingConvention calling_convention;
5897       locations->SetInAt(0, LocationFrom(calling_convention.GetFpuRegisterAt(0)));
5898       locations->SetInAt(1, LocationFrom(calling_convention.GetFpuRegisterAt(1)));
5899       locations->SetOut(calling_convention.GetReturnLocation(type));
5900 
5901       break;
5902     }
5903 
5904     default:
5905       LOG(FATAL) << "Unexpected rem type " << type;
5906   }
5907 }
5908 
GenerateIntRemForPower2Denom(HRem * instruction)5909 void InstructionCodeGeneratorARM64::GenerateIntRemForPower2Denom(HRem *instruction) {
5910   int64_t imm = Int64FromLocation(instruction->GetLocations()->InAt(1));
5911   uint64_t abs_imm = static_cast<uint64_t>(AbsOrMin(imm));
5912   DCHECK(IsPowerOfTwo(abs_imm)) << abs_imm;
5913 
5914   Register out = OutputRegister(instruction);
5915   Register dividend = InputRegisterAt(instruction, 0);
5916 
5917   if (HasNonNegativeOrMinIntInputAt(instruction, 0)) {
5918     // No need to adjust the result for non-negative dividends or the INT32_MIN/INT64_MIN dividends.
5919     // NOTE: The generated code for HRem correctly works for the INT32_MIN/INT64_MIN dividends.
5920     // INT*_MIN % imm must be 0 for any imm of power 2. 'and' works only with bits
5921     // 0..30 (Int32 case)/0..62 (Int64 case) of a dividend. For INT32_MIN/INT64_MIN they are zeros.
5922     // So 'and' always produces zero.
5923     __ And(out, dividend, abs_imm - 1);
5924   } else {
5925     if (abs_imm == 2) {
5926       __ Cmp(dividend, 0);
5927       __ And(out, dividend, 1);
5928       __ Csneg(out, out, out, ge);
5929     } else {
5930       UseScratchRegisterScope temps(GetVIXLAssembler());
5931       Register temp = temps.AcquireSameSizeAs(out);
5932 
5933       __ Negs(temp, dividend);
5934       __ And(out, dividend, abs_imm - 1);
5935       __ And(temp, temp, abs_imm - 1);
5936       __ Csneg(out, out, temp, mi);
5937     }
5938   }
5939 }
5940 
GenerateIntRemForConstDenom(HRem * instruction)5941 void InstructionCodeGeneratorARM64::GenerateIntRemForConstDenom(HRem *instruction) {
5942   int64_t imm = Int64FromLocation(instruction->GetLocations()->InAt(1));
5943 
5944   if (imm == 0) {
5945     // Do not generate anything.
5946     // DivZeroCheck would prevent any code to be executed.
5947     return;
5948   }
5949 
5950   if (IsPowerOfTwo(AbsOrMin(imm))) {
5951     // Cases imm == -1 or imm == 1 are handled in constant folding by
5952     // InstructionWithAbsorbingInputSimplifier.
5953     // If the cases have survided till code generation they are handled in
5954     // GenerateIntRemForPower2Denom becauses -1 and 1 are the power of 2 (2^0).
5955     // The correct code is generated for them, just more instructions.
5956     GenerateIntRemForPower2Denom(instruction);
5957   } else {
5958     DCHECK(imm < -2 || imm > 2) << imm;
5959     GenerateDivRemWithAnyConstant(instruction, imm);
5960   }
5961 }
5962 
GenerateIntRem(HRem * instruction)5963 void InstructionCodeGeneratorARM64::GenerateIntRem(HRem* instruction) {
5964   DCHECK(DataType::IsIntOrLongType(instruction->GetResultType()))
5965          << instruction->GetResultType();
5966 
5967   if (instruction->GetLocations()->InAt(1).IsConstant()) {
5968     GenerateIntRemForConstDenom(instruction);
5969   } else {
5970     Register out = OutputRegister(instruction);
5971     Register dividend = InputRegisterAt(instruction, 0);
5972     Register divisor = InputRegisterAt(instruction, 1);
5973     UseScratchRegisterScope temps(GetVIXLAssembler());
5974     Register temp = temps.AcquireSameSizeAs(out);
5975     __ Sdiv(temp, dividend, divisor);
5976     __ Msub(out, temp, divisor, dividend);
5977   }
5978 }
5979 
VisitRem(HRem * rem)5980 void InstructionCodeGeneratorARM64::VisitRem(HRem* rem) {
5981   DataType::Type type = rem->GetResultType();
5982 
5983   switch (type) {
5984     case DataType::Type::kInt32:
5985     case DataType::Type::kInt64: {
5986       GenerateIntRem(rem);
5987       break;
5988     }
5989 
5990     case DataType::Type::kFloat32:
5991     case DataType::Type::kFloat64: {
5992       QuickEntrypointEnum entrypoint =
5993           (type == DataType::Type::kFloat32) ? kQuickFmodf : kQuickFmod;
5994       codegen_->InvokeRuntime(entrypoint, rem, rem->GetDexPc());
5995       if (type == DataType::Type::kFloat32) {
5996         CheckEntrypointTypes<kQuickFmodf, float, float, float>();
5997       } else {
5998         CheckEntrypointTypes<kQuickFmod, double, double, double>();
5999       }
6000       break;
6001     }
6002 
6003     default:
6004       LOG(FATAL) << "Unexpected rem type " << type;
6005       UNREACHABLE();
6006   }
6007 }
6008 
VisitMin(HMin * min)6009 void LocationsBuilderARM64::VisitMin(HMin* min) {
6010   HandleBinaryOp(min);
6011 }
6012 
VisitMin(HMin * min)6013 void InstructionCodeGeneratorARM64::VisitMin(HMin* min) {
6014   HandleBinaryOp(min);
6015 }
6016 
VisitMax(HMax * max)6017 void LocationsBuilderARM64::VisitMax(HMax* max) {
6018   HandleBinaryOp(max);
6019 }
6020 
VisitMax(HMax * max)6021 void InstructionCodeGeneratorARM64::VisitMax(HMax* max) {
6022   HandleBinaryOp(max);
6023 }
6024 
VisitAbs(HAbs * abs)6025 void LocationsBuilderARM64::VisitAbs(HAbs* abs) {
6026   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(abs);
6027   switch (abs->GetResultType()) {
6028     case DataType::Type::kInt32:
6029     case DataType::Type::kInt64:
6030       locations->SetInAt(0, Location::RequiresRegister());
6031       locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
6032       break;
6033     case DataType::Type::kFloat32:
6034     case DataType::Type::kFloat64:
6035       locations->SetInAt(0, Location::RequiresFpuRegister());
6036       locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
6037       break;
6038     default:
6039       LOG(FATAL) << "Unexpected type for abs operation " << abs->GetResultType();
6040   }
6041 }
6042 
VisitAbs(HAbs * abs)6043 void InstructionCodeGeneratorARM64::VisitAbs(HAbs* abs) {
6044   switch (abs->GetResultType()) {
6045     case DataType::Type::kInt32:
6046     case DataType::Type::kInt64: {
6047       Register in_reg = InputRegisterAt(abs, 0);
6048       Register out_reg = OutputRegister(abs);
6049       __ Cmp(in_reg, Operand(0));
6050       __ Cneg(out_reg, in_reg, lt);
6051       break;
6052     }
6053     case DataType::Type::kFloat32:
6054     case DataType::Type::kFloat64: {
6055       VRegister in_reg = InputFPRegisterAt(abs, 0);
6056       VRegister out_reg = OutputFPRegister(abs);
6057       __ Fabs(out_reg, in_reg);
6058       break;
6059     }
6060     default:
6061       LOG(FATAL) << "Unexpected type for abs operation " << abs->GetResultType();
6062   }
6063 }
6064 
VisitConstructorFence(HConstructorFence * constructor_fence)6065 void LocationsBuilderARM64::VisitConstructorFence(HConstructorFence* constructor_fence) {
6066   constructor_fence->SetLocations(nullptr);
6067 }
6068 
VisitConstructorFence(HConstructorFence * constructor_fence ATTRIBUTE_UNUSED)6069 void InstructionCodeGeneratorARM64::VisitConstructorFence(
6070     HConstructorFence* constructor_fence ATTRIBUTE_UNUSED) {
6071   codegen_->GenerateMemoryBarrier(MemBarrierKind::kStoreStore);
6072 }
6073 
VisitMemoryBarrier(HMemoryBarrier * memory_barrier)6074 void LocationsBuilderARM64::VisitMemoryBarrier(HMemoryBarrier* memory_barrier) {
6075   memory_barrier->SetLocations(nullptr);
6076 }
6077 
VisitMemoryBarrier(HMemoryBarrier * memory_barrier)6078 void InstructionCodeGeneratorARM64::VisitMemoryBarrier(HMemoryBarrier* memory_barrier) {
6079   codegen_->GenerateMemoryBarrier(memory_barrier->GetBarrierKind());
6080 }
6081 
VisitReturn(HReturn * instruction)6082 void LocationsBuilderARM64::VisitReturn(HReturn* instruction) {
6083   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(instruction);
6084   DataType::Type return_type = instruction->InputAt(0)->GetType();
6085   locations->SetInAt(0, ARM64ReturnLocation(return_type));
6086 }
6087 
VisitReturn(HReturn * ret)6088 void InstructionCodeGeneratorARM64::VisitReturn(HReturn* ret) {
6089   if (GetGraph()->IsCompilingOsr()) {
6090     // To simplify callers of an OSR method, we put the return value in both
6091     // floating point and core register.
6092     switch (ret->InputAt(0)->GetType()) {
6093       case DataType::Type::kFloat32:
6094         __ Fmov(w0, s0);
6095         break;
6096       case DataType::Type::kFloat64:
6097         __ Fmov(x0, d0);
6098         break;
6099       default:
6100         break;
6101     }
6102   }
6103   codegen_->GenerateFrameExit();
6104 }
6105 
VisitReturnVoid(HReturnVoid * instruction)6106 void LocationsBuilderARM64::VisitReturnVoid(HReturnVoid* instruction) {
6107   instruction->SetLocations(nullptr);
6108 }
6109 
VisitReturnVoid(HReturnVoid * instruction ATTRIBUTE_UNUSED)6110 void InstructionCodeGeneratorARM64::VisitReturnVoid(HReturnVoid* instruction ATTRIBUTE_UNUSED) {
6111   codegen_->GenerateFrameExit();
6112 }
6113 
VisitRor(HRor * ror)6114 void LocationsBuilderARM64::VisitRor(HRor* ror) {
6115   HandleBinaryOp(ror);
6116 }
6117 
VisitRor(HRor * ror)6118 void InstructionCodeGeneratorARM64::VisitRor(HRor* ror) {
6119   HandleBinaryOp(ror);
6120 }
6121 
VisitShl(HShl * shl)6122 void LocationsBuilderARM64::VisitShl(HShl* shl) {
6123   HandleShift(shl);
6124 }
6125 
VisitShl(HShl * shl)6126 void InstructionCodeGeneratorARM64::VisitShl(HShl* shl) {
6127   HandleShift(shl);
6128 }
6129 
VisitShr(HShr * shr)6130 void LocationsBuilderARM64::VisitShr(HShr* shr) {
6131   HandleShift(shr);
6132 }
6133 
VisitShr(HShr * shr)6134 void InstructionCodeGeneratorARM64::VisitShr(HShr* shr) {
6135   HandleShift(shr);
6136 }
6137 
VisitSub(HSub * instruction)6138 void LocationsBuilderARM64::VisitSub(HSub* instruction) {
6139   HandleBinaryOp(instruction);
6140 }
6141 
VisitSub(HSub * instruction)6142 void InstructionCodeGeneratorARM64::VisitSub(HSub* instruction) {
6143   HandleBinaryOp(instruction);
6144 }
6145 
VisitStaticFieldGet(HStaticFieldGet * instruction)6146 void LocationsBuilderARM64::VisitStaticFieldGet(HStaticFieldGet* instruction) {
6147   HandleFieldGet(instruction, instruction->GetFieldInfo());
6148 }
6149 
VisitStaticFieldGet(HStaticFieldGet * instruction)6150 void InstructionCodeGeneratorARM64::VisitStaticFieldGet(HStaticFieldGet* instruction) {
6151   HandleFieldGet(instruction, instruction->GetFieldInfo());
6152 }
6153 
VisitStaticFieldSet(HStaticFieldSet * instruction)6154 void LocationsBuilderARM64::VisitStaticFieldSet(HStaticFieldSet* instruction) {
6155   HandleFieldSet(instruction);
6156 }
6157 
VisitStaticFieldSet(HStaticFieldSet * instruction)6158 void InstructionCodeGeneratorARM64::VisitStaticFieldSet(HStaticFieldSet* instruction) {
6159   HandleFieldSet(instruction, instruction->GetFieldInfo(), instruction->GetValueCanBeNull());
6160 }
6161 
VisitStringBuilderAppend(HStringBuilderAppend * instruction)6162 void LocationsBuilderARM64::VisitStringBuilderAppend(HStringBuilderAppend* instruction) {
6163   codegen_->CreateStringBuilderAppendLocations(instruction, LocationFrom(x0));
6164 }
6165 
VisitStringBuilderAppend(HStringBuilderAppend * instruction)6166 void InstructionCodeGeneratorARM64::VisitStringBuilderAppend(HStringBuilderAppend* instruction) {
6167   __ Mov(w0, instruction->GetFormat()->GetValue());
6168   codegen_->InvokeRuntime(kQuickStringBuilderAppend, instruction, instruction->GetDexPc());
6169 }
6170 
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * instruction)6171 void LocationsBuilderARM64::VisitUnresolvedInstanceFieldGet(
6172     HUnresolvedInstanceFieldGet* instruction) {
6173   FieldAccessCallingConventionARM64 calling_convention;
6174   codegen_->CreateUnresolvedFieldLocationSummary(
6175       instruction, instruction->GetFieldType(), calling_convention);
6176 }
6177 
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * instruction)6178 void InstructionCodeGeneratorARM64::VisitUnresolvedInstanceFieldGet(
6179     HUnresolvedInstanceFieldGet* instruction) {
6180   FieldAccessCallingConventionARM64 calling_convention;
6181   codegen_->GenerateUnresolvedFieldAccess(instruction,
6182                                           instruction->GetFieldType(),
6183                                           instruction->GetFieldIndex(),
6184                                           instruction->GetDexPc(),
6185                                           calling_convention);
6186 }
6187 
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * instruction)6188 void LocationsBuilderARM64::VisitUnresolvedInstanceFieldSet(
6189     HUnresolvedInstanceFieldSet* instruction) {
6190   FieldAccessCallingConventionARM64 calling_convention;
6191   codegen_->CreateUnresolvedFieldLocationSummary(
6192       instruction, instruction->GetFieldType(), calling_convention);
6193 }
6194 
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * instruction)6195 void InstructionCodeGeneratorARM64::VisitUnresolvedInstanceFieldSet(
6196     HUnresolvedInstanceFieldSet* instruction) {
6197   FieldAccessCallingConventionARM64 calling_convention;
6198   codegen_->GenerateUnresolvedFieldAccess(instruction,
6199                                           instruction->GetFieldType(),
6200                                           instruction->GetFieldIndex(),
6201                                           instruction->GetDexPc(),
6202                                           calling_convention);
6203 }
6204 
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * instruction)6205 void LocationsBuilderARM64::VisitUnresolvedStaticFieldGet(
6206     HUnresolvedStaticFieldGet* instruction) {
6207   FieldAccessCallingConventionARM64 calling_convention;
6208   codegen_->CreateUnresolvedFieldLocationSummary(
6209       instruction, instruction->GetFieldType(), calling_convention);
6210 }
6211 
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * instruction)6212 void InstructionCodeGeneratorARM64::VisitUnresolvedStaticFieldGet(
6213     HUnresolvedStaticFieldGet* instruction) {
6214   FieldAccessCallingConventionARM64 calling_convention;
6215   codegen_->GenerateUnresolvedFieldAccess(instruction,
6216                                           instruction->GetFieldType(),
6217                                           instruction->GetFieldIndex(),
6218                                           instruction->GetDexPc(),
6219                                           calling_convention);
6220 }
6221 
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * instruction)6222 void LocationsBuilderARM64::VisitUnresolvedStaticFieldSet(
6223     HUnresolvedStaticFieldSet* instruction) {
6224   FieldAccessCallingConventionARM64 calling_convention;
6225   codegen_->CreateUnresolvedFieldLocationSummary(
6226       instruction, instruction->GetFieldType(), calling_convention);
6227 }
6228 
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * instruction)6229 void InstructionCodeGeneratorARM64::VisitUnresolvedStaticFieldSet(
6230     HUnresolvedStaticFieldSet* instruction) {
6231   FieldAccessCallingConventionARM64 calling_convention;
6232   codegen_->GenerateUnresolvedFieldAccess(instruction,
6233                                           instruction->GetFieldType(),
6234                                           instruction->GetFieldIndex(),
6235                                           instruction->GetDexPc(),
6236                                           calling_convention);
6237 }
6238 
VisitSuspendCheck(HSuspendCheck * instruction)6239 void LocationsBuilderARM64::VisitSuspendCheck(HSuspendCheck* instruction) {
6240   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
6241       instruction, LocationSummary::kCallOnSlowPath);
6242   // In suspend check slow path, usually there are no caller-save registers at all.
6243   // If SIMD instructions are present, however, we force spilling all live SIMD
6244   // registers in full width (since the runtime only saves/restores lower part).
6245   locations->SetCustomSlowPathCallerSaves(
6246       GetGraph()->HasSIMD() ? RegisterSet::AllFpu() : RegisterSet::Empty());
6247 }
6248 
VisitSuspendCheck(HSuspendCheck * instruction)6249 void InstructionCodeGeneratorARM64::VisitSuspendCheck(HSuspendCheck* instruction) {
6250   HBasicBlock* block = instruction->GetBlock();
6251   if (block->GetLoopInformation() != nullptr) {
6252     DCHECK(block->GetLoopInformation()->GetSuspendCheck() == instruction);
6253     // The back edge will generate the suspend check.
6254     return;
6255   }
6256   if (block->IsEntryBlock() && instruction->GetNext()->IsGoto()) {
6257     // The goto will generate the suspend check.
6258     return;
6259   }
6260   GenerateSuspendCheck(instruction, nullptr);
6261   codegen_->MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
6262 }
6263 
VisitThrow(HThrow * instruction)6264 void LocationsBuilderARM64::VisitThrow(HThrow* instruction) {
6265   LocationSummary* locations = new (GetGraph()->GetAllocator()) LocationSummary(
6266       instruction, LocationSummary::kCallOnMainOnly);
6267   InvokeRuntimeCallingConvention calling_convention;
6268   locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
6269 }
6270 
VisitThrow(HThrow * instruction)6271 void InstructionCodeGeneratorARM64::VisitThrow(HThrow* instruction) {
6272   codegen_->InvokeRuntime(kQuickDeliverException, instruction, instruction->GetDexPc());
6273   CheckEntrypointTypes<kQuickDeliverException, void, mirror::Object*>();
6274 }
6275 
VisitTypeConversion(HTypeConversion * conversion)6276 void LocationsBuilderARM64::VisitTypeConversion(HTypeConversion* conversion) {
6277   LocationSummary* locations =
6278       new (GetGraph()->GetAllocator()) LocationSummary(conversion, LocationSummary::kNoCall);
6279   DataType::Type input_type = conversion->GetInputType();
6280   DataType::Type result_type = conversion->GetResultType();
6281   DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
6282       << input_type << " -> " << result_type;
6283   if ((input_type == DataType::Type::kReference) || (input_type == DataType::Type::kVoid) ||
6284       (result_type == DataType::Type::kReference) || (result_type == DataType::Type::kVoid)) {
6285     LOG(FATAL) << "Unexpected type conversion from " << input_type << " to " << result_type;
6286   }
6287 
6288   if (DataType::IsFloatingPointType(input_type)) {
6289     locations->SetInAt(0, Location::RequiresFpuRegister());
6290   } else {
6291     locations->SetInAt(0, Location::RequiresRegister());
6292   }
6293 
6294   if (DataType::IsFloatingPointType(result_type)) {
6295     locations->SetOut(Location::RequiresFpuRegister(), Location::kNoOutputOverlap);
6296   } else {
6297     locations->SetOut(Location::RequiresRegister(), Location::kNoOutputOverlap);
6298   }
6299 }
6300 
VisitTypeConversion(HTypeConversion * conversion)6301 void InstructionCodeGeneratorARM64::VisitTypeConversion(HTypeConversion* conversion) {
6302   DataType::Type result_type = conversion->GetResultType();
6303   DataType::Type input_type = conversion->GetInputType();
6304 
6305   DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
6306       << input_type << " -> " << result_type;
6307 
6308   if (DataType::IsIntegralType(result_type) && DataType::IsIntegralType(input_type)) {
6309     int result_size = DataType::Size(result_type);
6310     int input_size = DataType::Size(input_type);
6311     int min_size = std::min(result_size, input_size);
6312     Register output = OutputRegister(conversion);
6313     Register source = InputRegisterAt(conversion, 0);
6314     if (result_type == DataType::Type::kInt32 && input_type == DataType::Type::kInt64) {
6315       // 'int' values are used directly as W registers, discarding the top
6316       // bits, so we don't need to sign-extend and can just perform a move.
6317       // We do not pass the `kDiscardForSameWReg` argument to force clearing the
6318       // top 32 bits of the target register. We theoretically could leave those
6319       // bits unchanged, but we would have to make sure that no code uses a
6320       // 32bit input value as a 64bit value assuming that the top 32 bits are
6321       // zero.
6322       __ Mov(output.W(), source.W());
6323     } else if (DataType::IsUnsignedType(result_type) ||
6324                (DataType::IsUnsignedType(input_type) && input_size < result_size)) {
6325       __ Ubfx(output, output.IsX() ? source.X() : source.W(), 0, result_size * kBitsPerByte);
6326     } else {
6327       __ Sbfx(output, output.IsX() ? source.X() : source.W(), 0, min_size * kBitsPerByte);
6328     }
6329   } else if (DataType::IsFloatingPointType(result_type) && DataType::IsIntegralType(input_type)) {
6330     __ Scvtf(OutputFPRegister(conversion), InputRegisterAt(conversion, 0));
6331   } else if (DataType::IsIntegralType(result_type) && DataType::IsFloatingPointType(input_type)) {
6332     CHECK(result_type == DataType::Type::kInt32 || result_type == DataType::Type::kInt64);
6333     __ Fcvtzs(OutputRegister(conversion), InputFPRegisterAt(conversion, 0));
6334   } else if (DataType::IsFloatingPointType(result_type) &&
6335              DataType::IsFloatingPointType(input_type)) {
6336     __ Fcvt(OutputFPRegister(conversion), InputFPRegisterAt(conversion, 0));
6337   } else {
6338     LOG(FATAL) << "Unexpected or unimplemented type conversion from " << input_type
6339                 << " to " << result_type;
6340   }
6341 }
6342 
VisitUShr(HUShr * ushr)6343 void LocationsBuilderARM64::VisitUShr(HUShr* ushr) {
6344   HandleShift(ushr);
6345 }
6346 
VisitUShr(HUShr * ushr)6347 void InstructionCodeGeneratorARM64::VisitUShr(HUShr* ushr) {
6348   HandleShift(ushr);
6349 }
6350 
VisitXor(HXor * instruction)6351 void LocationsBuilderARM64::VisitXor(HXor* instruction) {
6352   HandleBinaryOp(instruction);
6353 }
6354 
VisitXor(HXor * instruction)6355 void InstructionCodeGeneratorARM64::VisitXor(HXor* instruction) {
6356   HandleBinaryOp(instruction);
6357 }
6358 
VisitBoundType(HBoundType * instruction ATTRIBUTE_UNUSED)6359 void LocationsBuilderARM64::VisitBoundType(HBoundType* instruction ATTRIBUTE_UNUSED) {
6360   // Nothing to do, this should be removed during prepare for register allocator.
6361   LOG(FATAL) << "Unreachable";
6362 }
6363 
VisitBoundType(HBoundType * instruction ATTRIBUTE_UNUSED)6364 void InstructionCodeGeneratorARM64::VisitBoundType(HBoundType* instruction ATTRIBUTE_UNUSED) {
6365   // Nothing to do, this should be removed during prepare for register allocator.
6366   LOG(FATAL) << "Unreachable";
6367 }
6368 
6369 // Simple implementation of packed switch - generate cascaded compare/jumps.
VisitPackedSwitch(HPackedSwitch * switch_instr)6370 void LocationsBuilderARM64::VisitPackedSwitch(HPackedSwitch* switch_instr) {
6371   LocationSummary* locations =
6372       new (GetGraph()->GetAllocator()) LocationSummary(switch_instr, LocationSummary::kNoCall);
6373   locations->SetInAt(0, Location::RequiresRegister());
6374 }
6375 
VisitPackedSwitch(HPackedSwitch * switch_instr)6376 void InstructionCodeGeneratorARM64::VisitPackedSwitch(HPackedSwitch* switch_instr) {
6377   int32_t lower_bound = switch_instr->GetStartValue();
6378   uint32_t num_entries = switch_instr->GetNumEntries();
6379   Register value_reg = InputRegisterAt(switch_instr, 0);
6380   HBasicBlock* default_block = switch_instr->GetDefaultBlock();
6381 
6382   // Roughly set 16 as max average assemblies generated per HIR in a graph.
6383   static constexpr int32_t kMaxExpectedSizePerHInstruction = 16 * kInstructionSize;
6384   // ADR has a limited range(+/-1MB), so we set a threshold for the number of HIRs in the graph to
6385   // make sure we don't emit it if the target may run out of range.
6386   // TODO: Instead of emitting all jump tables at the end of the code, we could keep track of ADR
6387   // ranges and emit the tables only as required.
6388   static constexpr int32_t kJumpTableInstructionThreshold = 1* MB / kMaxExpectedSizePerHInstruction;
6389 
6390   if (num_entries <= kPackedSwitchCompareJumpThreshold ||
6391       // Current instruction id is an upper bound of the number of HIRs in the graph.
6392       GetGraph()->GetCurrentInstructionId() > kJumpTableInstructionThreshold) {
6393     // Create a series of compare/jumps.
6394     UseScratchRegisterScope temps(codegen_->GetVIXLAssembler());
6395     Register temp = temps.AcquireW();
6396     __ Subs(temp, value_reg, Operand(lower_bound));
6397 
6398     const ArenaVector<HBasicBlock*>& successors = switch_instr->GetBlock()->GetSuccessors();
6399     // Jump to successors[0] if value == lower_bound.
6400     __ B(eq, codegen_->GetLabelOf(successors[0]));
6401     int32_t last_index = 0;
6402     for (; num_entries - last_index > 2; last_index += 2) {
6403       __ Subs(temp, temp, Operand(2));
6404       // Jump to successors[last_index + 1] if value < case_value[last_index + 2].
6405       __ B(lo, codegen_->GetLabelOf(successors[last_index + 1]));
6406       // Jump to successors[last_index + 2] if value == case_value[last_index + 2].
6407       __ B(eq, codegen_->GetLabelOf(successors[last_index + 2]));
6408     }
6409     if (num_entries - last_index == 2) {
6410       // The last missing case_value.
6411       __ Cmp(temp, Operand(1));
6412       __ B(eq, codegen_->GetLabelOf(successors[last_index + 1]));
6413     }
6414 
6415     // And the default for any other value.
6416     if (!codegen_->GoesToNextBlock(switch_instr->GetBlock(), default_block)) {
6417       __ B(codegen_->GetLabelOf(default_block));
6418     }
6419   } else {
6420     JumpTableARM64* jump_table = codegen_->CreateJumpTable(switch_instr);
6421 
6422     UseScratchRegisterScope temps(codegen_->GetVIXLAssembler());
6423 
6424     // Below instructions should use at most one blocked register. Since there are two blocked
6425     // registers, we are free to block one.
6426     Register temp_w = temps.AcquireW();
6427     Register index;
6428     // Remove the bias.
6429     if (lower_bound != 0) {
6430       index = temp_w;
6431       __ Sub(index, value_reg, Operand(lower_bound));
6432     } else {
6433       index = value_reg;
6434     }
6435 
6436     // Jump to default block if index is out of the range.
6437     __ Cmp(index, Operand(num_entries));
6438     __ B(hs, codegen_->GetLabelOf(default_block));
6439 
6440     // In current VIXL implementation, it won't require any blocked registers to encode the
6441     // immediate value for Adr. So we are free to use both VIXL blocked registers to reduce the
6442     // register pressure.
6443     Register table_base = temps.AcquireX();
6444     // Load jump offset from the table.
6445     __ Adr(table_base, jump_table->GetTableStartLabel());
6446     Register jump_offset = temp_w;
6447     __ Ldr(jump_offset, MemOperand(table_base, index, UXTW, 2));
6448 
6449     // Jump to target block by branching to table_base(pc related) + offset.
6450     Register target_address = table_base;
6451     __ Add(target_address, table_base, Operand(jump_offset, SXTW));
6452     __ Br(target_address);
6453   }
6454 }
6455 
GenerateReferenceLoadOneRegister(HInstruction * instruction,Location out,uint32_t offset,Location maybe_temp,ReadBarrierOption read_barrier_option)6456 void InstructionCodeGeneratorARM64::GenerateReferenceLoadOneRegister(
6457     HInstruction* instruction,
6458     Location out,
6459     uint32_t offset,
6460     Location maybe_temp,
6461     ReadBarrierOption read_barrier_option) {
6462   DataType::Type type = DataType::Type::kReference;
6463   Register out_reg = RegisterFrom(out, type);
6464   if (read_barrier_option == kWithReadBarrier) {
6465     CHECK(kEmitCompilerReadBarrier);
6466     if (kUseBakerReadBarrier) {
6467       // Load with fast path based Baker's read barrier.
6468       // /* HeapReference<Object> */ out = *(out + offset)
6469       codegen_->GenerateFieldLoadWithBakerReadBarrier(instruction,
6470                                                       out,
6471                                                       out_reg,
6472                                                       offset,
6473                                                       maybe_temp,
6474                                                       /* needs_null_check= */ false,
6475                                                       /* use_load_acquire= */ false);
6476     } else {
6477       // Load with slow path based read barrier.
6478       // Save the value of `out` into `maybe_temp` before overwriting it
6479       // in the following move operation, as we will need it for the
6480       // read barrier below.
6481       Register temp_reg = RegisterFrom(maybe_temp, type);
6482       __ Mov(temp_reg, out_reg);
6483       // /* HeapReference<Object> */ out = *(out + offset)
6484       __ Ldr(out_reg, HeapOperand(out_reg, offset));
6485       codegen_->GenerateReadBarrierSlow(instruction, out, out, maybe_temp, offset);
6486     }
6487   } else {
6488     // Plain load with no read barrier.
6489     // /* HeapReference<Object> */ out = *(out + offset)
6490     __ Ldr(out_reg, HeapOperand(out_reg, offset));
6491     GetAssembler()->MaybeUnpoisonHeapReference(out_reg);
6492   }
6493 }
6494 
GenerateReferenceLoadTwoRegisters(HInstruction * instruction,Location out,Location obj,uint32_t offset,Location maybe_temp,ReadBarrierOption read_barrier_option)6495 void InstructionCodeGeneratorARM64::GenerateReferenceLoadTwoRegisters(
6496     HInstruction* instruction,
6497     Location out,
6498     Location obj,
6499     uint32_t offset,
6500     Location maybe_temp,
6501     ReadBarrierOption read_barrier_option) {
6502   DataType::Type type = DataType::Type::kReference;
6503   Register out_reg = RegisterFrom(out, type);
6504   Register obj_reg = RegisterFrom(obj, type);
6505   if (read_barrier_option == kWithReadBarrier) {
6506     CHECK(kEmitCompilerReadBarrier);
6507     if (kUseBakerReadBarrier) {
6508       // Load with fast path based Baker's read barrier.
6509       // /* HeapReference<Object> */ out = *(obj + offset)
6510       codegen_->GenerateFieldLoadWithBakerReadBarrier(instruction,
6511                                                       out,
6512                                                       obj_reg,
6513                                                       offset,
6514                                                       maybe_temp,
6515                                                       /* needs_null_check= */ false,
6516                                                       /* use_load_acquire= */ false);
6517     } else {
6518       // Load with slow path based read barrier.
6519       // /* HeapReference<Object> */ out = *(obj + offset)
6520       __ Ldr(out_reg, HeapOperand(obj_reg, offset));
6521       codegen_->GenerateReadBarrierSlow(instruction, out, out, obj, offset);
6522     }
6523   } else {
6524     // Plain load with no read barrier.
6525     // /* HeapReference<Object> */ out = *(obj + offset)
6526     __ Ldr(out_reg, HeapOperand(obj_reg, offset));
6527     GetAssembler()->MaybeUnpoisonHeapReference(out_reg);
6528   }
6529 }
6530 
GenerateGcRootFieldLoad(HInstruction * instruction,Location root,Register obj,uint32_t offset,vixl::aarch64::Label * fixup_label,ReadBarrierOption read_barrier_option)6531 void CodeGeneratorARM64::GenerateGcRootFieldLoad(
6532     HInstruction* instruction,
6533     Location root,
6534     Register obj,
6535     uint32_t offset,
6536     vixl::aarch64::Label* fixup_label,
6537     ReadBarrierOption read_barrier_option) {
6538   DCHECK(fixup_label == nullptr || offset == 0u);
6539   Register root_reg = RegisterFrom(root, DataType::Type::kReference);
6540   if (read_barrier_option == kWithReadBarrier) {
6541     DCHECK(kEmitCompilerReadBarrier);
6542     if (kUseBakerReadBarrier) {
6543       // Fast path implementation of art::ReadBarrier::BarrierForRoot when
6544       // Baker's read barrier are used.
6545 
6546       // Query `art::Thread::Current()->GetIsGcMarking()` (stored in
6547       // the Marking Register) to decide whether we need to enter
6548       // the slow path to mark the GC root.
6549       //
6550       // We use shared thunks for the slow path; shared within the method
6551       // for JIT, across methods for AOT. That thunk checks the reference
6552       // and jumps to the entrypoint if needed.
6553       //
6554       //     lr = &return_address;
6555       //     GcRoot<mirror::Object> root = *(obj+offset);  // Original reference load.
6556       //     if (mr) {  // Thread::Current()->GetIsGcMarking()
6557       //       goto gc_root_thunk<root_reg>(lr)
6558       //     }
6559       //   return_address:
6560 
6561       UseScratchRegisterScope temps(GetVIXLAssembler());
6562       DCHECK(temps.IsAvailable(ip0));
6563       DCHECK(temps.IsAvailable(ip1));
6564       temps.Exclude(ip0, ip1);
6565       uint32_t custom_data = EncodeBakerReadBarrierGcRootData(root_reg.GetCode());
6566 
6567       ExactAssemblyScope guard(GetVIXLAssembler(), 3 * vixl::aarch64::kInstructionSize);
6568       vixl::aarch64::Label return_address;
6569       __ adr(lr, &return_address);
6570       if (fixup_label != nullptr) {
6571         __ bind(fixup_label);
6572       }
6573       static_assert(BAKER_MARK_INTROSPECTION_GC_ROOT_LDR_OFFSET == -8,
6574                     "GC root LDR must be 2 instructions (8B) before the return address label.");
6575       __ ldr(root_reg, MemOperand(obj.X(), offset));
6576       EmitBakerReadBarrierCbnz(custom_data);
6577       __ bind(&return_address);
6578     } else {
6579       // GC root loaded through a slow path for read barriers other
6580       // than Baker's.
6581       // /* GcRoot<mirror::Object>* */ root = obj + offset
6582       if (fixup_label == nullptr) {
6583         __ Add(root_reg.X(), obj.X(), offset);
6584       } else {
6585         EmitAddPlaceholder(fixup_label, root_reg.X(), obj.X());
6586       }
6587       // /* mirror::Object* */ root = root->Read()
6588       GenerateReadBarrierForRootSlow(instruction, root, root);
6589     }
6590   } else {
6591     // Plain GC root load with no read barrier.
6592     // /* GcRoot<mirror::Object> */ root = *(obj + offset)
6593     if (fixup_label == nullptr) {
6594       __ Ldr(root_reg, MemOperand(obj, offset));
6595     } else {
6596       EmitLdrOffsetPlaceholder(fixup_label, root_reg, obj.X());
6597     }
6598     // Note that GC roots are not affected by heap poisoning, thus we
6599     // do not have to unpoison `root_reg` here.
6600   }
6601   MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__);
6602 }
6603 
GenerateIntrinsicCasMoveWithBakerReadBarrier(vixl::aarch64::Register marked_old_value,vixl::aarch64::Register old_value)6604 void CodeGeneratorARM64::GenerateIntrinsicCasMoveWithBakerReadBarrier(
6605     vixl::aarch64::Register marked_old_value,
6606     vixl::aarch64::Register old_value) {
6607   DCHECK(kEmitCompilerReadBarrier);
6608   DCHECK(kUseBakerReadBarrier);
6609 
6610   // Similar to the Baker RB path in GenerateGcRootFieldLoad(), with a MOV instead of LDR.
6611   uint32_t custom_data = EncodeBakerReadBarrierGcRootData(marked_old_value.GetCode());
6612 
6613   ExactAssemblyScope guard(GetVIXLAssembler(), 3 * vixl::aarch64::kInstructionSize);
6614   vixl::aarch64::Label return_address;
6615   __ adr(lr, &return_address);
6616   static_assert(BAKER_MARK_INTROSPECTION_GC_ROOT_LDR_OFFSET == -8,
6617                 "GC root LDR must be 2 instructions (8B) before the return address label.");
6618   __ mov(marked_old_value, old_value);
6619   EmitBakerReadBarrierCbnz(custom_data);
6620   __ bind(&return_address);
6621 }
6622 
GenerateFieldLoadWithBakerReadBarrier(HInstruction * instruction,Location ref,vixl::aarch64::Register obj,const vixl::aarch64::MemOperand & src,bool needs_null_check,bool use_load_acquire)6623 void CodeGeneratorARM64::GenerateFieldLoadWithBakerReadBarrier(HInstruction* instruction,
6624                                                                Location ref,
6625                                                                vixl::aarch64::Register obj,
6626                                                                const vixl::aarch64::MemOperand& src,
6627                                                                bool needs_null_check,
6628                                                                bool use_load_acquire) {
6629   DCHECK(kEmitCompilerReadBarrier);
6630   DCHECK(kUseBakerReadBarrier);
6631 
6632   // Query `art::Thread::Current()->GetIsGcMarking()` (stored in the
6633   // Marking Register) to decide whether we need to enter the slow
6634   // path to mark the reference. Then, in the slow path, check the
6635   // gray bit in the lock word of the reference's holder (`obj`) to
6636   // decide whether to mark `ref` or not.
6637   //
6638   // We use shared thunks for the slow path; shared within the method
6639   // for JIT, across methods for AOT. That thunk checks the holder
6640   // and jumps to the entrypoint if needed. If the holder is not gray,
6641   // it creates a fake dependency and returns to the LDR instruction.
6642   //
6643   //     lr = &gray_return_address;
6644   //     if (mr) {  // Thread::Current()->GetIsGcMarking()
6645   //       goto field_thunk<holder_reg, base_reg, use_load_acquire>(lr)
6646   //     }
6647   //   not_gray_return_address:
6648   //     // Original reference load. If the offset is too large to fit
6649   //     // into LDR, we use an adjusted base register here.
6650   //     HeapReference<mirror::Object> reference = *(obj+offset);
6651   //   gray_return_address:
6652 
6653   DCHECK(src.GetAddrMode() == vixl::aarch64::Offset);
6654   DCHECK_ALIGNED(src.GetOffset(), sizeof(mirror::HeapReference<mirror::Object>));
6655 
6656   UseScratchRegisterScope temps(GetVIXLAssembler());
6657   DCHECK(temps.IsAvailable(ip0));
6658   DCHECK(temps.IsAvailable(ip1));
6659   temps.Exclude(ip0, ip1);
6660   uint32_t custom_data = use_load_acquire
6661       ? EncodeBakerReadBarrierAcquireData(src.GetBaseRegister().GetCode(), obj.GetCode())
6662       : EncodeBakerReadBarrierFieldData(src.GetBaseRegister().GetCode(), obj.GetCode());
6663 
6664   {
6665     ExactAssemblyScope guard(GetVIXLAssembler(),
6666                              (kPoisonHeapReferences ? 4u : 3u) * vixl::aarch64::kInstructionSize);
6667     vixl::aarch64::Label return_address;
6668     __ adr(lr, &return_address);
6669     EmitBakerReadBarrierCbnz(custom_data);
6670     static_assert(BAKER_MARK_INTROSPECTION_FIELD_LDR_OFFSET == (kPoisonHeapReferences ? -8 : -4),
6671                   "Field LDR must be 1 instruction (4B) before the return address label; "
6672                   " 2 instructions (8B) for heap poisoning.");
6673     Register ref_reg = RegisterFrom(ref, DataType::Type::kReference);
6674     if (use_load_acquire) {
6675       DCHECK_EQ(src.GetOffset(), 0);
6676       __ ldar(ref_reg, src);
6677     } else {
6678       __ ldr(ref_reg, src);
6679     }
6680     if (needs_null_check) {
6681       MaybeRecordImplicitNullCheck(instruction);
6682     }
6683     // Unpoison the reference explicitly if needed. MaybeUnpoisonHeapReference() uses
6684     // macro instructions disallowed in ExactAssemblyScope.
6685     if (kPoisonHeapReferences) {
6686       __ neg(ref_reg, Operand(ref_reg));
6687     }
6688     __ bind(&return_address);
6689   }
6690   MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__, /* temp_loc= */ LocationFrom(ip1));
6691 }
6692 
GenerateFieldLoadWithBakerReadBarrier(HInstruction * instruction,Location ref,Register obj,uint32_t offset,Location maybe_temp,bool needs_null_check,bool use_load_acquire)6693 void CodeGeneratorARM64::GenerateFieldLoadWithBakerReadBarrier(HInstruction* instruction,
6694                                                                Location ref,
6695                                                                Register obj,
6696                                                                uint32_t offset,
6697                                                                Location maybe_temp,
6698                                                                bool needs_null_check,
6699                                                                bool use_load_acquire) {
6700   DCHECK_ALIGNED(offset, sizeof(mirror::HeapReference<mirror::Object>));
6701   Register base = obj;
6702   if (use_load_acquire) {
6703     DCHECK(maybe_temp.IsRegister());
6704     base = WRegisterFrom(maybe_temp);
6705     __ Add(base, obj, offset);
6706     offset = 0u;
6707   } else if (offset >= kReferenceLoadMinFarOffset) {
6708     DCHECK(maybe_temp.IsRegister());
6709     base = WRegisterFrom(maybe_temp);
6710     static_assert(IsPowerOfTwo(kReferenceLoadMinFarOffset), "Expecting a power of 2.");
6711     __ Add(base, obj, Operand(offset & ~(kReferenceLoadMinFarOffset - 1u)));
6712     offset &= (kReferenceLoadMinFarOffset - 1u);
6713   }
6714   MemOperand src(base.X(), offset);
6715   GenerateFieldLoadWithBakerReadBarrier(
6716       instruction, ref, obj, src, needs_null_check, use_load_acquire);
6717 }
6718 
GenerateArrayLoadWithBakerReadBarrier(HArrayGet * instruction,Location ref,Register obj,uint32_t data_offset,Location index,bool needs_null_check)6719 void CodeGeneratorARM64::GenerateArrayLoadWithBakerReadBarrier(HArrayGet* instruction,
6720                                                                Location ref,
6721                                                                Register obj,
6722                                                                uint32_t data_offset,
6723                                                                Location index,
6724                                                                bool needs_null_check) {
6725   DCHECK(kEmitCompilerReadBarrier);
6726   DCHECK(kUseBakerReadBarrier);
6727 
6728   static_assert(
6729       sizeof(mirror::HeapReference<mirror::Object>) == sizeof(int32_t),
6730       "art::mirror::HeapReference<art::mirror::Object> and int32_t have different sizes.");
6731   size_t scale_factor = DataType::SizeShift(DataType::Type::kReference);
6732 
6733   // Query `art::Thread::Current()->GetIsGcMarking()` (stored in the
6734   // Marking Register) to decide whether we need to enter the slow
6735   // path to mark the reference. Then, in the slow path, check the
6736   // gray bit in the lock word of the reference's holder (`obj`) to
6737   // decide whether to mark `ref` or not.
6738   //
6739   // We use shared thunks for the slow path; shared within the method
6740   // for JIT, across methods for AOT. That thunk checks the holder
6741   // and jumps to the entrypoint if needed. If the holder is not gray,
6742   // it creates a fake dependency and returns to the LDR instruction.
6743   //
6744   //     lr = &gray_return_address;
6745   //     if (mr) {  // Thread::Current()->GetIsGcMarking()
6746   //       goto array_thunk<base_reg>(lr)
6747   //     }
6748   //   not_gray_return_address:
6749   //     // Original reference load. If the offset is too large to fit
6750   //     // into LDR, we use an adjusted base register here.
6751   //     HeapReference<mirror::Object> reference = data[index];
6752   //   gray_return_address:
6753 
6754   DCHECK(index.IsValid());
6755   Register index_reg = RegisterFrom(index, DataType::Type::kInt32);
6756   Register ref_reg = RegisterFrom(ref, DataType::Type::kReference);
6757 
6758   UseScratchRegisterScope temps(GetVIXLAssembler());
6759   DCHECK(temps.IsAvailable(ip0));
6760   DCHECK(temps.IsAvailable(ip1));
6761   temps.Exclude(ip0, ip1);
6762 
6763   Register temp;
6764   if (instruction->GetArray()->IsIntermediateAddress()) {
6765     // We do not need to compute the intermediate address from the array: the
6766     // input instruction has done it already. See the comment in
6767     // `TryExtractArrayAccessAddress()`.
6768     if (kIsDebugBuild) {
6769       HIntermediateAddress* interm_addr = instruction->GetArray()->AsIntermediateAddress();
6770       DCHECK_EQ(interm_addr->GetOffset()->AsIntConstant()->GetValueAsUint64(), data_offset);
6771     }
6772     temp = obj;
6773   } else {
6774     temp = WRegisterFrom(instruction->GetLocations()->GetTemp(0));
6775     __ Add(temp.X(), obj.X(), Operand(data_offset));
6776   }
6777 
6778   uint32_t custom_data = EncodeBakerReadBarrierArrayData(temp.GetCode());
6779 
6780   {
6781     ExactAssemblyScope guard(GetVIXLAssembler(),
6782                              (kPoisonHeapReferences ? 4u : 3u) * vixl::aarch64::kInstructionSize);
6783     vixl::aarch64::Label return_address;
6784     __ adr(lr, &return_address);
6785     EmitBakerReadBarrierCbnz(custom_data);
6786     static_assert(BAKER_MARK_INTROSPECTION_ARRAY_LDR_OFFSET == (kPoisonHeapReferences ? -8 : -4),
6787                   "Array LDR must be 1 instruction (4B) before the return address label; "
6788                   " 2 instructions (8B) for heap poisoning.");
6789     __ ldr(ref_reg, MemOperand(temp.X(), index_reg.X(), LSL, scale_factor));
6790     DCHECK(!needs_null_check);  // The thunk cannot handle the null check.
6791     // Unpoison the reference explicitly if needed. MaybeUnpoisonHeapReference() uses
6792     // macro instructions disallowed in ExactAssemblyScope.
6793     if (kPoisonHeapReferences) {
6794       __ neg(ref_reg, Operand(ref_reg));
6795     }
6796     __ bind(&return_address);
6797   }
6798   MaybeGenerateMarkingRegisterCheck(/* code= */ __LINE__, /* temp_loc= */ LocationFrom(ip1));
6799 }
6800 
MaybeGenerateMarkingRegisterCheck(int code,Location temp_loc)6801 void CodeGeneratorARM64::MaybeGenerateMarkingRegisterCheck(int code, Location temp_loc) {
6802   // The following condition is a compile-time one, so it does not have a run-time cost.
6803   if (kEmitCompilerReadBarrier && kUseBakerReadBarrier && kIsDebugBuild) {
6804     // The following condition is a run-time one; it is executed after the
6805     // previous compile-time test, to avoid penalizing non-debug builds.
6806     if (GetCompilerOptions().EmitRunTimeChecksInDebugMode()) {
6807       UseScratchRegisterScope temps(GetVIXLAssembler());
6808       Register temp = temp_loc.IsValid() ? WRegisterFrom(temp_loc) : temps.AcquireW();
6809       GetAssembler()->GenerateMarkingRegisterCheck(temp, code);
6810     }
6811   }
6812 }
6813 
AddReadBarrierSlowPath(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)6814 SlowPathCodeARM64* CodeGeneratorARM64::AddReadBarrierSlowPath(HInstruction* instruction,
6815                                                               Location out,
6816                                                               Location ref,
6817                                                               Location obj,
6818                                                               uint32_t offset,
6819                                                               Location index) {
6820   SlowPathCodeARM64* slow_path = new (GetScopedAllocator())
6821       ReadBarrierForHeapReferenceSlowPathARM64(instruction, out, ref, obj, offset, index);
6822   AddSlowPath(slow_path);
6823   return slow_path;
6824 }
6825 
GenerateReadBarrierSlow(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)6826 void CodeGeneratorARM64::GenerateReadBarrierSlow(HInstruction* instruction,
6827                                                  Location out,
6828                                                  Location ref,
6829                                                  Location obj,
6830                                                  uint32_t offset,
6831                                                  Location index) {
6832   DCHECK(kEmitCompilerReadBarrier);
6833 
6834   // Insert a slow path based read barrier *after* the reference load.
6835   //
6836   // If heap poisoning is enabled, the unpoisoning of the loaded
6837   // reference will be carried out by the runtime within the slow
6838   // path.
6839   //
6840   // Note that `ref` currently does not get unpoisoned (when heap
6841   // poisoning is enabled), which is alright as the `ref` argument is
6842   // not used by the artReadBarrierSlow entry point.
6843   //
6844   // TODO: Unpoison `ref` when it is used by artReadBarrierSlow.
6845   SlowPathCodeARM64* slow_path = AddReadBarrierSlowPath(instruction, out, ref, obj, offset, index);
6846 
6847   __ B(slow_path->GetEntryLabel());
6848   __ Bind(slow_path->GetExitLabel());
6849 }
6850 
MaybeGenerateReadBarrierSlow(HInstruction * instruction,Location out,Location ref,Location obj,uint32_t offset,Location index)6851 void CodeGeneratorARM64::MaybeGenerateReadBarrierSlow(HInstruction* instruction,
6852                                                       Location out,
6853                                                       Location ref,
6854                                                       Location obj,
6855                                                       uint32_t offset,
6856                                                       Location index) {
6857   if (kEmitCompilerReadBarrier) {
6858     // Baker's read barriers shall be handled by the fast path
6859     // (CodeGeneratorARM64::GenerateReferenceLoadWithBakerReadBarrier).
6860     DCHECK(!kUseBakerReadBarrier);
6861     // If heap poisoning is enabled, unpoisoning will be taken care of
6862     // by the runtime within the slow path.
6863     GenerateReadBarrierSlow(instruction, out, ref, obj, offset, index);
6864   } else if (kPoisonHeapReferences) {
6865     GetAssembler()->UnpoisonHeapReference(WRegisterFrom(out));
6866   }
6867 }
6868 
GenerateReadBarrierForRootSlow(HInstruction * instruction,Location out,Location root)6869 void CodeGeneratorARM64::GenerateReadBarrierForRootSlow(HInstruction* instruction,
6870                                                         Location out,
6871                                                         Location root) {
6872   DCHECK(kEmitCompilerReadBarrier);
6873 
6874   // Insert a slow path based read barrier *after* the GC root load.
6875   //
6876   // Note that GC roots are not affected by heap poisoning, so we do
6877   // not need to do anything special for this here.
6878   SlowPathCodeARM64* slow_path =
6879       new (GetScopedAllocator()) ReadBarrierForRootSlowPathARM64(instruction, out, root);
6880   AddSlowPath(slow_path);
6881 
6882   __ B(slow_path->GetEntryLabel());
6883   __ Bind(slow_path->GetExitLabel());
6884 }
6885 
VisitClassTableGet(HClassTableGet * instruction)6886 void LocationsBuilderARM64::VisitClassTableGet(HClassTableGet* instruction) {
6887   LocationSummary* locations =
6888       new (GetGraph()->GetAllocator()) LocationSummary(instruction, LocationSummary::kNoCall);
6889   locations->SetInAt(0, Location::RequiresRegister());
6890   locations->SetOut(Location::RequiresRegister());
6891 }
6892 
VisitClassTableGet(HClassTableGet * instruction)6893 void InstructionCodeGeneratorARM64::VisitClassTableGet(HClassTableGet* instruction) {
6894   LocationSummary* locations = instruction->GetLocations();
6895   if (instruction->GetTableKind() == HClassTableGet::TableKind::kVTable) {
6896     uint32_t method_offset = mirror::Class::EmbeddedVTableEntryOffset(
6897         instruction->GetIndex(), kArm64PointerSize).SizeValue();
6898     __ Ldr(XRegisterFrom(locations->Out()),
6899            MemOperand(XRegisterFrom(locations->InAt(0)), method_offset));
6900   } else {
6901     uint32_t method_offset = static_cast<uint32_t>(ImTable::OffsetOfElement(
6902         instruction->GetIndex(), kArm64PointerSize));
6903     __ Ldr(XRegisterFrom(locations->Out()), MemOperand(XRegisterFrom(locations->InAt(0)),
6904         mirror::Class::ImtPtrOffset(kArm64PointerSize).Uint32Value()));
6905     __ Ldr(XRegisterFrom(locations->Out()),
6906            MemOperand(XRegisterFrom(locations->Out()), method_offset));
6907   }
6908 }
6909 
PatchJitRootUse(uint8_t * code,const uint8_t * roots_data,vixl::aarch64::Literal<uint32_t> * literal,uint64_t index_in_table)6910 static void PatchJitRootUse(uint8_t* code,
6911                             const uint8_t* roots_data,
6912                             vixl::aarch64::Literal<uint32_t>* literal,
6913                             uint64_t index_in_table) {
6914   uint32_t literal_offset = literal->GetOffset();
6915   uintptr_t address =
6916       reinterpret_cast<uintptr_t>(roots_data) + index_in_table * sizeof(GcRoot<mirror::Object>);
6917   uint8_t* data = code + literal_offset;
6918   reinterpret_cast<uint32_t*>(data)[0] = dchecked_integral_cast<uint32_t>(address);
6919 }
6920 
EmitJitRootPatches(uint8_t * code,const uint8_t * roots_data)6921 void CodeGeneratorARM64::EmitJitRootPatches(uint8_t* code, const uint8_t* roots_data) {
6922   for (const auto& entry : jit_string_patches_) {
6923     const StringReference& string_reference = entry.first;
6924     vixl::aarch64::Literal<uint32_t>* table_entry_literal = entry.second;
6925     uint64_t index_in_table = GetJitStringRootIndex(string_reference);
6926     PatchJitRootUse(code, roots_data, table_entry_literal, index_in_table);
6927   }
6928   for (const auto& entry : jit_class_patches_) {
6929     const TypeReference& type_reference = entry.first;
6930     vixl::aarch64::Literal<uint32_t>* table_entry_literal = entry.second;
6931     uint64_t index_in_table = GetJitClassRootIndex(type_reference);
6932     PatchJitRootUse(code, roots_data, table_entry_literal, index_in_table);
6933   }
6934 }
6935 
VecNEONAddress(HVecMemoryOperation * instruction,UseScratchRegisterScope * temps_scope,size_t size,bool is_string_char_at,Register * scratch)6936 MemOperand InstructionCodeGeneratorARM64::VecNEONAddress(
6937     HVecMemoryOperation* instruction,
6938     UseScratchRegisterScope* temps_scope,
6939     size_t size,
6940     bool is_string_char_at,
6941     /*out*/ Register* scratch) {
6942   LocationSummary* locations = instruction->GetLocations();
6943   Register base = InputRegisterAt(instruction, 0);
6944 
6945   if (instruction->InputAt(1)->IsIntermediateAddressIndex()) {
6946     DCHECK(!is_string_char_at);
6947     return MemOperand(base.X(), InputRegisterAt(instruction, 1).X());
6948   }
6949 
6950   Location index = locations->InAt(1);
6951   uint32_t offset = is_string_char_at
6952       ? mirror::String::ValueOffset().Uint32Value()
6953       : mirror::Array::DataOffset(size).Uint32Value();
6954   size_t shift = ComponentSizeShiftWidth(size);
6955 
6956   // HIntermediateAddress optimization is only applied for scalar ArrayGet and ArraySet.
6957   DCHECK(!instruction->InputAt(0)->IsIntermediateAddress());
6958 
6959   if (index.IsConstant()) {
6960     offset += Int64FromLocation(index) << shift;
6961     return HeapOperand(base, offset);
6962   } else {
6963     *scratch = temps_scope->AcquireSameSizeAs(base);
6964     __ Add(*scratch, base, Operand(WRegisterFrom(index), LSL, shift));
6965     return HeapOperand(*scratch, offset);
6966   }
6967 }
6968 
VecSVEAddress(HVecMemoryOperation * instruction,UseScratchRegisterScope * temps_scope,size_t size,bool is_string_char_at,Register * scratch)6969 SVEMemOperand InstructionCodeGeneratorARM64::VecSVEAddress(
6970     HVecMemoryOperation* instruction,
6971     UseScratchRegisterScope* temps_scope,
6972     size_t size,
6973     bool is_string_char_at,
6974     /*out*/ Register* scratch) {
6975   LocationSummary* locations = instruction->GetLocations();
6976   Register base = InputRegisterAt(instruction, 0);
6977   Location index = locations->InAt(1);
6978 
6979   DCHECK(!instruction->InputAt(1)->IsIntermediateAddressIndex());
6980   DCHECK(!index.IsConstant());
6981 
6982   uint32_t offset = is_string_char_at
6983       ? mirror::String::ValueOffset().Uint32Value()
6984       : mirror::Array::DataOffset(size).Uint32Value();
6985   size_t shift = ComponentSizeShiftWidth(size);
6986 
6987   if (instruction->InputAt(0)->IsIntermediateAddress()) {
6988     return SVEMemOperand(base.X(), XRegisterFrom(index), LSL, shift);
6989   }
6990 
6991   *scratch = temps_scope->AcquireSameSizeAs(base);
6992   __ Add(*scratch, base, offset);
6993   return SVEMemOperand(scratch->X(), XRegisterFrom(index), LSL, shift);
6994 }
6995 
6996 #undef __
6997 #undef QUICK_ENTRY_POINT
6998 
6999 #define __ assembler.GetVIXLAssembler()->
7000 
EmitGrayCheckAndFastPath(arm64::Arm64Assembler & assembler,vixl::aarch64::Register base_reg,vixl::aarch64::MemOperand & lock_word,vixl::aarch64::Label * slow_path,vixl::aarch64::Label * throw_npe=nullptr)7001 static void EmitGrayCheckAndFastPath(arm64::Arm64Assembler& assembler,
7002                                      vixl::aarch64::Register base_reg,
7003                                      vixl::aarch64::MemOperand& lock_word,
7004                                      vixl::aarch64::Label* slow_path,
7005                                      vixl::aarch64::Label* throw_npe = nullptr) {
7006   // Load the lock word containing the rb_state.
7007   __ Ldr(ip0.W(), lock_word);
7008   // Given the numeric representation, it's enough to check the low bit of the rb_state.
7009   static_assert(ReadBarrier::NonGrayState() == 0, "Expecting non-gray to have value 0");
7010   static_assert(ReadBarrier::GrayState() == 1, "Expecting gray to have value 1");
7011   __ Tbnz(ip0.W(), LockWord::kReadBarrierStateShift, slow_path);
7012   static_assert(
7013       BAKER_MARK_INTROSPECTION_ARRAY_LDR_OFFSET == BAKER_MARK_INTROSPECTION_FIELD_LDR_OFFSET,
7014       "Field and array LDR offsets must be the same to reuse the same code.");
7015   // To throw NPE, we return to the fast path; the artificial dependence below does not matter.
7016   if (throw_npe != nullptr) {
7017     __ Bind(throw_npe);
7018   }
7019   // Adjust the return address back to the LDR (1 instruction; 2 for heap poisoning).
7020   static_assert(BAKER_MARK_INTROSPECTION_FIELD_LDR_OFFSET == (kPoisonHeapReferences ? -8 : -4),
7021                 "Field LDR must be 1 instruction (4B) before the return address label; "
7022                 " 2 instructions (8B) for heap poisoning.");
7023   __ Add(lr, lr, BAKER_MARK_INTROSPECTION_FIELD_LDR_OFFSET);
7024   // Introduce a dependency on the lock_word including rb_state,
7025   // to prevent load-load reordering, and without using
7026   // a memory barrier (which would be more expensive).
7027   __ Add(base_reg, base_reg, Operand(ip0, LSR, 32));
7028   __ Br(lr);          // And return back to the function.
7029   // Note: The fake dependency is unnecessary for the slow path.
7030 }
7031 
7032 // Load the read barrier introspection entrypoint in register `entrypoint`.
LoadReadBarrierMarkIntrospectionEntrypoint(arm64::Arm64Assembler & assembler,vixl::aarch64::Register entrypoint)7033 static void LoadReadBarrierMarkIntrospectionEntrypoint(arm64::Arm64Assembler& assembler,
7034                                                        vixl::aarch64::Register entrypoint) {
7035   // entrypoint = Thread::Current()->pReadBarrierMarkReg16, i.e. pReadBarrierMarkIntrospection.
7036   DCHECK_EQ(ip0.GetCode(), 16u);
7037   const int32_t entry_point_offset =
7038       Thread::ReadBarrierMarkEntryPointsOffset<kArm64PointerSize>(ip0.GetCode());
7039   __ Ldr(entrypoint, MemOperand(tr, entry_point_offset));
7040 }
7041 
CompileBakerReadBarrierThunk(Arm64Assembler & assembler,uint32_t encoded_data,std::string * debug_name)7042 void CodeGeneratorARM64::CompileBakerReadBarrierThunk(Arm64Assembler& assembler,
7043                                                       uint32_t encoded_data,
7044                                                       /*out*/ std::string* debug_name) {
7045   BakerReadBarrierKind kind = BakerReadBarrierKindField::Decode(encoded_data);
7046   switch (kind) {
7047     case BakerReadBarrierKind::kField:
7048     case BakerReadBarrierKind::kAcquire: {
7049       Register base_reg =
7050           vixl::aarch64::XRegister(BakerReadBarrierFirstRegField::Decode(encoded_data));
7051       CheckValidReg(base_reg.GetCode());
7052       Register holder_reg =
7053           vixl::aarch64::XRegister(BakerReadBarrierSecondRegField::Decode(encoded_data));
7054       CheckValidReg(holder_reg.GetCode());
7055       UseScratchRegisterScope temps(assembler.GetVIXLAssembler());
7056       temps.Exclude(ip0, ip1);
7057       // In the case of a field load (with relaxed semantic), if `base_reg` differs from
7058       // `holder_reg`, the offset was too large and we must have emitted (during the construction
7059       // of the HIR graph, see `art::HInstructionBuilder::BuildInstanceFieldAccess`) and preserved
7060       // (see `art::PrepareForRegisterAllocation::VisitNullCheck`) an explicit null check before
7061       // the load. Otherwise, for implicit null checks, we need to null-check the holder as we do
7062       // not necessarily do that check before going to the thunk.
7063       //
7064       // In the case of a field load with load-acquire semantics (where `base_reg` always differs
7065       // from `holder_reg`), we also need an explicit null check when implicit null checks are
7066       // allowed, as we do not emit one before going to the thunk.
7067       vixl::aarch64::Label throw_npe_label;
7068       vixl::aarch64::Label* throw_npe = nullptr;
7069       if (GetCompilerOptions().GetImplicitNullChecks() &&
7070           (holder_reg.Is(base_reg) || (kind == BakerReadBarrierKind::kAcquire))) {
7071         throw_npe = &throw_npe_label;
7072         __ Cbz(holder_reg.W(), throw_npe);
7073       }
7074       // Check if the holder is gray and, if not, add fake dependency to the base register
7075       // and return to the LDR instruction to load the reference. Otherwise, use introspection
7076       // to load the reference and call the entrypoint that performs further checks on the
7077       // reference and marks it if needed.
7078       vixl::aarch64::Label slow_path;
7079       MemOperand lock_word(holder_reg, mirror::Object::MonitorOffset().Int32Value());
7080       EmitGrayCheckAndFastPath(assembler, base_reg, lock_word, &slow_path, throw_npe);
7081       __ Bind(&slow_path);
7082       if (kind == BakerReadBarrierKind::kField) {
7083         MemOperand ldr_address(lr, BAKER_MARK_INTROSPECTION_FIELD_LDR_OFFSET);
7084         __ Ldr(ip0.W(), ldr_address);         // Load the LDR (immediate) unsigned offset.
7085         LoadReadBarrierMarkIntrospectionEntrypoint(assembler, ip1);
7086         __ Ubfx(ip0.W(), ip0.W(), 10, 12);    // Extract the offset.
7087         __ Ldr(ip0.W(), MemOperand(base_reg, ip0, LSL, 2));   // Load the reference.
7088       } else {
7089         DCHECK(kind == BakerReadBarrierKind::kAcquire);
7090         DCHECK(!base_reg.Is(holder_reg));
7091         LoadReadBarrierMarkIntrospectionEntrypoint(assembler, ip1);
7092         __ Ldar(ip0.W(), MemOperand(base_reg));
7093       }
7094       // Do not unpoison. With heap poisoning enabled, the entrypoint expects a poisoned reference.
7095       __ Br(ip1);                           // Jump to the entrypoint.
7096       break;
7097     }
7098     case BakerReadBarrierKind::kArray: {
7099       Register base_reg =
7100           vixl::aarch64::XRegister(BakerReadBarrierFirstRegField::Decode(encoded_data));
7101       CheckValidReg(base_reg.GetCode());
7102       DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
7103                 BakerReadBarrierSecondRegField::Decode(encoded_data));
7104       UseScratchRegisterScope temps(assembler.GetVIXLAssembler());
7105       temps.Exclude(ip0, ip1);
7106       vixl::aarch64::Label slow_path;
7107       int32_t data_offset =
7108           mirror::Array::DataOffset(Primitive::ComponentSize(Primitive::kPrimNot)).Int32Value();
7109       MemOperand lock_word(base_reg, mirror::Object::MonitorOffset().Int32Value() - data_offset);
7110       DCHECK_LT(lock_word.GetOffset(), 0);
7111       EmitGrayCheckAndFastPath(assembler, base_reg, lock_word, &slow_path);
7112       __ Bind(&slow_path);
7113       MemOperand ldr_address(lr, BAKER_MARK_INTROSPECTION_ARRAY_LDR_OFFSET);
7114       __ Ldr(ip0.W(), ldr_address);         // Load the LDR (register) unsigned offset.
7115       LoadReadBarrierMarkIntrospectionEntrypoint(assembler, ip1);
7116       __ Ubfx(ip0, ip0, 16, 6);             // Extract the index register, plus 32 (bit 21 is set).
7117       __ Bfi(ip1, ip0, 3, 6);               // Insert ip0 to the entrypoint address to create
7118                                             // a switch case target based on the index register.
7119       __ Mov(ip0, base_reg);                // Move the base register to ip0.
7120       __ Br(ip1);                           // Jump to the entrypoint's array switch case.
7121       break;
7122     }
7123     case BakerReadBarrierKind::kGcRoot: {
7124       // Check if the reference needs to be marked and if so (i.e. not null, not marked yet
7125       // and it does not have a forwarding address), call the correct introspection entrypoint;
7126       // otherwise return the reference (or the extracted forwarding address).
7127       // There is no gray bit check for GC roots.
7128       Register root_reg =
7129           vixl::aarch64::WRegister(BakerReadBarrierFirstRegField::Decode(encoded_data));
7130       CheckValidReg(root_reg.GetCode());
7131       DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
7132                 BakerReadBarrierSecondRegField::Decode(encoded_data));
7133       UseScratchRegisterScope temps(assembler.GetVIXLAssembler());
7134       temps.Exclude(ip0, ip1);
7135       vixl::aarch64::Label return_label, not_marked, forwarding_address;
7136       __ Cbz(root_reg, &return_label);
7137       MemOperand lock_word(root_reg.X(), mirror::Object::MonitorOffset().Int32Value());
7138       __ Ldr(ip0.W(), lock_word);
7139       __ Tbz(ip0.W(), LockWord::kMarkBitStateShift, &not_marked);
7140       __ Bind(&return_label);
7141       __ Br(lr);
7142       __ Bind(&not_marked);
7143       __ Tst(ip0.W(), Operand(ip0.W(), LSL, 1));
7144       __ B(&forwarding_address, mi);
7145       LoadReadBarrierMarkIntrospectionEntrypoint(assembler, ip1);
7146       // Adjust the art_quick_read_barrier_mark_introspection address in IP1 to
7147       // art_quick_read_barrier_mark_introspection_gc_roots.
7148       __ Add(ip1, ip1, Operand(BAKER_MARK_INTROSPECTION_GC_ROOT_ENTRYPOINT_OFFSET));
7149       __ Mov(ip0.W(), root_reg);
7150       __ Br(ip1);
7151       __ Bind(&forwarding_address);
7152       __ Lsl(root_reg, ip0.W(), LockWord::kForwardingAddressShift);
7153       __ Br(lr);
7154       break;
7155     }
7156     default:
7157       LOG(FATAL) << "Unexpected kind: " << static_cast<uint32_t>(kind);
7158       UNREACHABLE();
7159   }
7160 
7161   // For JIT, the slow path is considered part of the compiled method,
7162   // so JIT should pass null as `debug_name`.
7163   DCHECK_IMPLIES(GetCompilerOptions().IsJitCompiler(), debug_name == nullptr);
7164   if (debug_name != nullptr && GetCompilerOptions().GenerateAnyDebugInfo()) {
7165     std::ostringstream oss;
7166     oss << "BakerReadBarrierThunk";
7167     switch (kind) {
7168       case BakerReadBarrierKind::kField:
7169         oss << "Field_r" << BakerReadBarrierFirstRegField::Decode(encoded_data)
7170             << "_r" << BakerReadBarrierSecondRegField::Decode(encoded_data);
7171         break;
7172       case BakerReadBarrierKind::kAcquire:
7173         oss << "Acquire_r" << BakerReadBarrierFirstRegField::Decode(encoded_data)
7174             << "_r" << BakerReadBarrierSecondRegField::Decode(encoded_data);
7175         break;
7176       case BakerReadBarrierKind::kArray:
7177         oss << "Array_r" << BakerReadBarrierFirstRegField::Decode(encoded_data);
7178         DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
7179                   BakerReadBarrierSecondRegField::Decode(encoded_data));
7180         break;
7181       case BakerReadBarrierKind::kGcRoot:
7182         oss << "GcRoot_r" << BakerReadBarrierFirstRegField::Decode(encoded_data);
7183         DCHECK_EQ(kBakerReadBarrierInvalidEncodedReg,
7184                   BakerReadBarrierSecondRegField::Decode(encoded_data));
7185         break;
7186     }
7187     *debug_name = oss.str();
7188   }
7189 }
7190 
7191 #undef __
7192 
7193 }  // namespace arm64
7194 }  // namespace art
7195