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