xref: /aosp_15_r20/art/compiler/optimizing/code_generator.h (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
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 #ifndef ART_COMPILER_OPTIMIZING_CODE_GENERATOR_H_
18 #define ART_COMPILER_OPTIMIZING_CODE_GENERATOR_H_
19 
20 #include "arch/instruction_set.h"
21 #include "arch/instruction_set_features.h"
22 #include "base/arena_containers.h"
23 #include "base/arena_object.h"
24 #include "base/array_ref.h"
25 #include "base/bit_field.h"
26 #include "base/bit_utils.h"
27 #include "base/globals.h"
28 #include "base/macros.h"
29 #include "base/memory_region.h"
30 #include "base/pointer_size.h"
31 #include "class_root.h"
32 #include "dex/proto_reference.h"
33 #include "dex/string_reference.h"
34 #include "dex/type_reference.h"
35 #include "graph_visualizer.h"
36 #include "locations.h"
37 #include "mirror/method_type.h"
38 #include "nodes.h"
39 #include "oat/oat_quick_method_header.h"
40 #include "optimizing_compiler_stats.h"
41 #include "read_barrier_option.h"
42 #include "stack.h"
43 #include "subtype_check.h"
44 #include "utils/assembler.h"
45 #include "utils/label.h"
46 
47 namespace art HIDDEN {
48 
49 // Binary encoding of 2^32 for type double.
50 static int64_t constexpr k2Pow32EncodingForDouble = INT64_C(0x41F0000000000000);
51 // Binary encoding of 2^31 for type double.
52 static int64_t constexpr k2Pow31EncodingForDouble = INT64_C(0x41E0000000000000);
53 
54 // Minimum value for a primitive integer.
55 static int32_t constexpr kPrimIntMin = 0x80000000;
56 // Minimum value for a primitive long.
57 static int64_t constexpr kPrimLongMin = INT64_C(0x8000000000000000);
58 
59 // Maximum value for a primitive integer.
60 static int32_t constexpr kPrimIntMax = 0x7fffffff;
61 // Maximum value for a primitive long.
62 static int64_t constexpr kPrimLongMax = INT64_C(0x7fffffffffffffff);
63 
64 constexpr size_t kClassStatusLsbPosition = SubtypeCheckBits::BitStructSizeOf();
65 constexpr size_t kClassStatusByteOffset =
66     mirror::Class::StatusOffset().SizeValue() + (kClassStatusLsbPosition / kBitsPerByte);
67 constexpr uint32_t kShiftedVisiblyInitializedValue = enum_cast<uint32_t>(
68     ClassStatus::kVisiblyInitialized) << (kClassStatusLsbPosition % kBitsPerByte);
69 constexpr uint32_t kShiftedInitializingValue =
70     enum_cast<uint32_t>(ClassStatus::kInitializing) << (kClassStatusLsbPosition % kBitsPerByte);
71 constexpr uint32_t kShiftedInitializedValue =
72     enum_cast<uint32_t>(ClassStatus::kInitialized) << (kClassStatusLsbPosition % kBitsPerByte);
73 
74 class Assembler;
75 class CodeGenerationData;
76 class CodeGenerator;
77 class CompilerOptions;
78 class StackMapStream;
79 class ParallelMoveResolver;
80 
81 namespace linker {
82 class LinkerPatch;
83 }  // namespace linker
84 
85 class SlowPathCode : public DeletableArenaObject<kArenaAllocSlowPaths> {
86  public:
SlowPathCode(HInstruction * instruction)87   explicit SlowPathCode(HInstruction* instruction) : instruction_(instruction) {
88     for (size_t i = 0; i < kMaximumNumberOfExpectedRegisters; ++i) {
89       saved_core_stack_offsets_[i] = kRegisterNotSaved;
90       saved_fpu_stack_offsets_[i] = kRegisterNotSaved;
91     }
92   }
93 
~SlowPathCode()94   virtual ~SlowPathCode() {}
95 
96   virtual void EmitNativeCode(CodeGenerator* codegen) = 0;
97 
98   // Save live core and floating-point caller-save registers and
99   // update the stack mask in `locations` for registers holding object
100   // references.
101   virtual void SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations);
102   // Restore live core and floating-point caller-save registers.
103   virtual void RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations);
104 
IsCoreRegisterSaved(int reg)105   bool IsCoreRegisterSaved(int reg) const {
106     return saved_core_stack_offsets_[reg] != kRegisterNotSaved;
107   }
108 
IsFpuRegisterSaved(int reg)109   bool IsFpuRegisterSaved(int reg) const {
110     return saved_fpu_stack_offsets_[reg] != kRegisterNotSaved;
111   }
112 
GetStackOffsetOfCoreRegister(int reg)113   uint32_t GetStackOffsetOfCoreRegister(int reg) const {
114     return saved_core_stack_offsets_[reg];
115   }
116 
GetStackOffsetOfFpuRegister(int reg)117   uint32_t GetStackOffsetOfFpuRegister(int reg) const {
118     return saved_fpu_stack_offsets_[reg];
119   }
120 
IsFatal()121   virtual bool IsFatal() const { return false; }
122 
123   virtual const char* GetDescription() const = 0;
124 
GetEntryLabel()125   Label* GetEntryLabel() { return &entry_label_; }
GetExitLabel()126   Label* GetExitLabel() { return &exit_label_; }
127 
GetInstruction()128   HInstruction* GetInstruction() const {
129     return instruction_;
130   }
131 
GetDexPc()132   uint32_t GetDexPc() const {
133     return instruction_ != nullptr ? instruction_->GetDexPc() : kNoDexPc;
134   }
135 
136  protected:
137   static constexpr size_t kMaximumNumberOfExpectedRegisters = 32;
138   static constexpr uint32_t kRegisterNotSaved = -1;
139   // The instruction where this slow path is happening.
140   HInstruction* instruction_;
141   uint32_t saved_core_stack_offsets_[kMaximumNumberOfExpectedRegisters];
142   uint32_t saved_fpu_stack_offsets_[kMaximumNumberOfExpectedRegisters];
143 
144  private:
145   Label entry_label_;
146   Label exit_label_;
147 
148   DISALLOW_COPY_AND_ASSIGN(SlowPathCode);
149 };
150 
151 class InvokeDexCallingConventionVisitor {
152  public:
153   virtual Location GetNextLocation(DataType::Type type) = 0;
154   virtual Location GetReturnLocation(DataType::Type type) const = 0;
155   virtual Location GetMethodLocation() const = 0;
156 
157  protected:
InvokeDexCallingConventionVisitor()158   InvokeDexCallingConventionVisitor() {}
~InvokeDexCallingConventionVisitor()159   virtual ~InvokeDexCallingConventionVisitor() {}
160 
161   // The current index for core registers.
162   uint32_t gp_index_ = 0u;
163   // The current index for floating-point registers.
164   uint32_t float_index_ = 0u;
165   // The current stack index.
166   uint32_t stack_index_ = 0u;
167 
168  private:
169   DISALLOW_COPY_AND_ASSIGN(InvokeDexCallingConventionVisitor);
170 };
171 
172 class FieldAccessCallingConvention {
173  public:
174   virtual Location GetObjectLocation() const = 0;
175   virtual Location GetFieldIndexLocation() const = 0;
176   virtual Location GetReturnLocation(DataType::Type type) const = 0;
177   virtual Location GetSetValueLocation(DataType::Type type, bool is_instance) const = 0;
178   virtual Location GetFpuLocation(DataType::Type type) const = 0;
~FieldAccessCallingConvention()179   virtual ~FieldAccessCallingConvention() {}
180 
181  protected:
FieldAccessCallingConvention()182   FieldAccessCallingConvention() {}
183 
184  private:
185   DISALLOW_COPY_AND_ASSIGN(FieldAccessCallingConvention);
186 };
187 
188 class CodeGenerator : public DeletableArenaObject<kArenaAllocCodeGenerator> {
189  public:
190   // Compiles the graph to executable instructions.
191   void Compile();
192   static std::unique_ptr<CodeGenerator> Create(HGraph* graph,
193                                                const CompilerOptions& compiler_options,
194                                                OptimizingCompilerStats* stats = nullptr);
195   virtual ~CodeGenerator();
196 
197   // Get the graph. This is the outermost graph, never the graph of a method being inlined.
GetGraph()198   HGraph* GetGraph() const { return graph_; }
199 
200   HBasicBlock* GetNextBlockToEmit() const;
201   HBasicBlock* FirstNonEmptyBlock(HBasicBlock* block) const;
202   bool GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const;
203 
GetStackSlotOfParameter(HParameterValue * parameter)204   size_t GetStackSlotOfParameter(HParameterValue* parameter) const {
205     // Note that this follows the current calling convention.
206     return GetFrameSize()
207         + static_cast<size_t>(InstructionSetPointerSize(GetInstructionSet()))  // Art method
208         + parameter->GetIndex() * kVRegSize;
209   }
210 
211   virtual void Initialize() = 0;
212   virtual void Finalize();
213   virtual void EmitLinkerPatches(ArenaVector<linker::LinkerPatch>* linker_patches);
214   virtual bool NeedsThunkCode(const linker::LinkerPatch& patch) const;
215   virtual void EmitThunkCode(const linker::LinkerPatch& patch,
216                              /*out*/ ArenaVector<uint8_t>* code,
217                              /*out*/ std::string* debug_name);
218   virtual void GenerateFrameEntry() = 0;
219   virtual void GenerateFrameExit() = 0;
220   virtual void Bind(HBasicBlock* block) = 0;
221   virtual void MoveConstant(Location destination, int32_t value) = 0;
222   virtual void MoveLocation(Location dst, Location src, DataType::Type dst_type) = 0;
223   virtual void AddLocationAsTemp(Location location, LocationSummary* locations) = 0;
224 
225   virtual Assembler* GetAssembler() = 0;
226   virtual const Assembler& GetAssembler() const = 0;
227   virtual size_t GetWordSize() const = 0;
228 
229   // Returns whether the target supports predicated SIMD instructions.
SupportsPredicatedSIMD()230   virtual bool SupportsPredicatedSIMD() const { return false; }
231 
232   // Get FP register width in bytes for spilling/restoring in the slow paths.
233   //
234   // Note: In SIMD graphs this should return SIMD register width as all FP and SIMD registers
235   // alias and live SIMD registers are forced to be spilled in full size in the slow paths.
GetSlowPathFPWidth()236   virtual size_t GetSlowPathFPWidth() const {
237     // Default implementation.
238     return GetCalleePreservedFPWidth();
239   }
240 
241   // Get FP register width required to be preserved by the target ABI.
242   virtual size_t GetCalleePreservedFPWidth() const  = 0;
243 
244   // Get the size of the target SIMD register in bytes.
245   virtual size_t GetSIMDRegisterWidth() const = 0;
246   virtual uintptr_t GetAddressOf(HBasicBlock* block) = 0;
247   void InitializeCodeGeneration(size_t number_of_spill_slots,
248                                 size_t maximum_safepoint_spill_size,
249                                 size_t number_of_out_slots,
250                                 const ArenaVector<HBasicBlock*>& block_order);
251   // Backends can override this as necessary. For most, no special alignment is required.
GetPreferredSlotsAlignment()252   virtual uint32_t GetPreferredSlotsAlignment() const { return 1; }
253 
GetFrameSize()254   uint32_t GetFrameSize() const { return frame_size_; }
SetFrameSize(uint32_t size)255   void SetFrameSize(uint32_t size) { frame_size_ = size; }
GetMaximumFrameSize()256   uint32_t GetMaximumFrameSize() const {
257     return GetStackOverflowReservedBytes(GetInstructionSet());
258   }
259 
GetCoreSpillMask()260   uint32_t GetCoreSpillMask() const { return core_spill_mask_; }
GetFpuSpillMask()261   uint32_t GetFpuSpillMask() const { return fpu_spill_mask_; }
262 
GetNumberOfCoreRegisters()263   size_t GetNumberOfCoreRegisters() const { return number_of_core_registers_; }
GetNumberOfFloatingPointRegisters()264   size_t GetNumberOfFloatingPointRegisters() const { return number_of_fpu_registers_; }
265   virtual void SetupBlockedRegisters() const = 0;
266 
ComputeSpillMask()267   virtual void ComputeSpillMask() {
268     core_spill_mask_ = allocated_registers_.GetCoreRegisters() & core_callee_save_mask_;
269     DCHECK_NE(core_spill_mask_, 0u) << "At least the return address register must be saved";
270     fpu_spill_mask_ = allocated_registers_.GetFloatingPointRegisters() & fpu_callee_save_mask_;
271   }
272 
273   virtual void DumpCoreRegister(std::ostream& stream, int reg) const = 0;
274   virtual void DumpFloatingPointRegister(std::ostream& stream, int reg) const = 0;
275   virtual InstructionSet GetInstructionSet() const = 0;
276 
277   // Saves the register in the stack. Returns the size taken on stack.
278   virtual size_t SaveCoreRegister(size_t stack_index, uint32_t reg_id) = 0;
279   // Restores the register from the stack. Returns the size taken on stack.
280   virtual size_t RestoreCoreRegister(size_t stack_index, uint32_t reg_id) = 0;
281 
282   virtual size_t SaveFloatingPointRegister(size_t stack_index, uint32_t reg_id) = 0;
283   virtual size_t RestoreFloatingPointRegister(size_t stack_index, uint32_t reg_id) = 0;
284 
285   virtual bool NeedsTwoRegisters(DataType::Type type) const = 0;
286   // Returns whether we should split long moves in parallel moves.
ShouldSplitLongMoves()287   virtual bool ShouldSplitLongMoves() const { return false; }
288 
289   // Returns true if `invoke` is an implemented intrinsic in this codegen's arch.
IsImplementedIntrinsic(HInvoke * invoke)290   bool IsImplementedIntrinsic(HInvoke* invoke) const {
291     return invoke->IsIntrinsic() &&
292            !unimplemented_intrinsics_[static_cast<size_t>(invoke->GetIntrinsic())];
293   }
294 
GetNumberOfCoreCalleeSaveRegisters()295   size_t GetNumberOfCoreCalleeSaveRegisters() const {
296     return POPCOUNT(core_callee_save_mask_);
297   }
298 
GetNumberOfCoreCallerSaveRegisters()299   size_t GetNumberOfCoreCallerSaveRegisters() const {
300     DCHECK_GE(GetNumberOfCoreRegisters(), GetNumberOfCoreCalleeSaveRegisters());
301     return GetNumberOfCoreRegisters() - GetNumberOfCoreCalleeSaveRegisters();
302   }
303 
IsCoreCalleeSaveRegister(int reg)304   bool IsCoreCalleeSaveRegister(int reg) const {
305     return (core_callee_save_mask_ & (1 << reg)) != 0;
306   }
307 
IsFloatingPointCalleeSaveRegister(int reg)308   bool IsFloatingPointCalleeSaveRegister(int reg) const {
309     return (fpu_callee_save_mask_ & (1 << reg)) != 0;
310   }
311 
GetSlowPathSpills(LocationSummary * locations,bool core_registers)312   uint32_t GetSlowPathSpills(LocationSummary* locations, bool core_registers) const {
313     DCHECK(locations->OnlyCallsOnSlowPath() ||
314            (locations->Intrinsified() && locations->CallsOnMainAndSlowPath() &&
315                !locations->HasCustomSlowPathCallingConvention()));
316     uint32_t live_registers = core_registers
317         ? locations->GetLiveRegisters()->GetCoreRegisters()
318         : locations->GetLiveRegisters()->GetFloatingPointRegisters();
319     if (locations->HasCustomSlowPathCallingConvention()) {
320       // Save only the live registers that the custom calling convention wants us to save.
321       uint32_t caller_saves = core_registers
322           ? locations->GetCustomSlowPathCallerSaves().GetCoreRegisters()
323           : locations->GetCustomSlowPathCallerSaves().GetFloatingPointRegisters();
324       return live_registers & caller_saves;
325     } else {
326       // Default ABI, we need to spill non-callee-save live registers.
327       uint32_t callee_saves = core_registers ? core_callee_save_mask_ : fpu_callee_save_mask_;
328       return live_registers & ~callee_saves;
329     }
330   }
331 
GetNumberOfSlowPathSpills(LocationSummary * locations,bool core_registers)332   size_t GetNumberOfSlowPathSpills(LocationSummary* locations, bool core_registers) const {
333     return POPCOUNT(GetSlowPathSpills(locations, core_registers));
334   }
335 
GetStackOffsetOfShouldDeoptimizeFlag()336   size_t GetStackOffsetOfShouldDeoptimizeFlag() const {
337     DCHECK(GetGraph()->HasShouldDeoptimizeFlag());
338     DCHECK_GE(GetFrameSize(), FrameEntrySpillSize() + kShouldDeoptimizeFlagSize);
339     return GetFrameSize() - FrameEntrySpillSize() - kShouldDeoptimizeFlagSize;
340   }
341 
342   // Record native to dex mapping for a suspend point. Required by runtime.
343   void RecordPcInfo(HInstruction* instruction,
344                     uint32_t dex_pc,
345                     uint32_t native_pc,
346                     SlowPathCode* slow_path = nullptr,
347                     bool native_debug_info = false);
348 
349   // Record native to dex mapping for a suspend point.
350   // The native_pc is used from Assembler::CodePosition.
351   //
352   // Note: As Assembler::CodePosition is target dependent, it does not guarantee the exact native_pc
353   // for the instruction. If the exact native_pc is required it must be provided explicitly.
354   void RecordPcInfo(HInstruction* instruction,
355                     uint32_t dex_pc,
356                     SlowPathCode* slow_path = nullptr,
357                     bool native_debug_info = false);
358 
359   // Check whether we have already recorded mapping at this PC.
360   bool HasStackMapAtCurrentPc();
361 
362   // Record extra stack maps if we support native debugging.
363   //
364   // ARM specific behaviour: The recorded native PC might be a branch over pools to instructions
365   // corresponding the dex PC.
366   void MaybeRecordNativeDebugInfo(HInstruction* instruction,
367                                   uint32_t dex_pc,
368                                   SlowPathCode* slow_path = nullptr);
369 
370   bool CanMoveNullCheckToUser(HNullCheck* null_check);
371   virtual void MaybeRecordImplicitNullCheck(HInstruction* instruction);
372   LocationSummary* CreateThrowingSlowPathLocations(
373       HInstruction* instruction, RegisterSet caller_saves = RegisterSet::Empty());
374   void GenerateNullCheck(HNullCheck* null_check);
375   virtual void GenerateImplicitNullCheck(HNullCheck* null_check) = 0;
376   virtual void GenerateExplicitNullCheck(HNullCheck* null_check) = 0;
377 
378   // Records a stack map which the runtime might use to set catch phi values
379   // during exception delivery.
380   // TODO: Replace with a catch-entering instruction that records the environment.
381   void RecordCatchBlockInfo();
382 
GetCompilerOptions()383   const CompilerOptions& GetCompilerOptions() const { return compiler_options_; }
384   bool EmitReadBarrier() const;
385   bool EmitBakerReadBarrier() const;
386   bool EmitNonBakerReadBarrier() const;
387   ReadBarrierOption GetCompilerReadBarrierOption() const;
388 
389   // Returns true if we should check the GC card for consistency purposes.
390   bool ShouldCheckGCCard(DataType::Type type,
391                          HInstruction* value,
392                          WriteBarrierKind write_barrier_kind) const;
393 
394   // Get the ScopedArenaAllocator used for codegen memory allocation.
395   ScopedArenaAllocator* GetScopedAllocator();
396 
397   void AddSlowPath(SlowPathCode* slow_path);
398 
399   ScopedArenaVector<uint8_t> BuildStackMaps(const dex::CodeItem* code_item_for_osr_check);
400   size_t GetNumberOfJitRoots() const;
401 
402   // Fills the `literals` array with literals collected during code generation.
403   // Also emits literal patches.
404   void EmitJitRoots(uint8_t* code,
405                     const uint8_t* roots_data,
406                     /*out*/std::vector<Handle<mirror::Object>>* roots)
407       REQUIRES_SHARED(Locks::mutator_lock_);
408 
IsLeafMethod()409   bool IsLeafMethod() const {
410     return is_leaf_;
411   }
412 
MarkNotLeaf()413   void MarkNotLeaf() {
414     is_leaf_ = false;
415     requires_current_method_ = true;
416   }
417 
NeedsSuspendCheckEntry()418   bool NeedsSuspendCheckEntry() const {
419     return needs_suspend_check_entry_;
420   }
421 
MarkNeedsSuspendCheckEntry()422   void MarkNeedsSuspendCheckEntry() {
423     needs_suspend_check_entry_ = true;
424   }
425 
SetRequiresCurrentMethod()426   void SetRequiresCurrentMethod() {
427     requires_current_method_ = true;
428   }
429 
RequiresCurrentMethod()430   bool RequiresCurrentMethod() const {
431     return requires_current_method_;
432   }
433 
434   // Clears the spill slots taken by loop phis in the `LocationSummary` of the
435   // suspend check. This is called when the code generator generates code
436   // for the suspend check at the back edge (instead of where the suspend check
437   // is, which is the loop entry). At this point, the spill slots for the phis
438   // have not been written to.
439   void ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck* suspend_check,
440                                              HParallelMove* spills) const;
441 
GetBlockedCoreRegisters()442   bool* GetBlockedCoreRegisters() const { return blocked_core_registers_; }
GetBlockedFloatingPointRegisters()443   bool* GetBlockedFloatingPointRegisters() const { return blocked_fpu_registers_; }
444 
IsBlockedCoreRegister(size_t i)445   bool IsBlockedCoreRegister(size_t i) { return blocked_core_registers_[i]; }
IsBlockedFloatingPointRegister(size_t i)446   bool IsBlockedFloatingPointRegister(size_t i) { return blocked_fpu_registers_[i]; }
447 
448   // Helper that returns the offset of the array's length field.
449   // Note: Besides the normal arrays, we also use the HArrayLength for
450   // accessing the String's `count` field in String intrinsics.
451   static uint32_t GetArrayLengthOffset(HArrayLength* array_length);
452 
453   // Helper that returns the offset of the array's data.
454   // Note: Besides the normal arrays, we also use the HArrayGet for
455   // accessing the String's `value` field in String intrinsics.
456   static uint32_t GetArrayDataOffset(HArrayGet* array_get);
457 
458   void EmitParallelMoves(Location from1,
459                          Location to1,
460                          DataType::Type type1,
461                          Location from2,
462                          Location to2,
463                          DataType::Type type2);
464 
InstanceOfNeedsReadBarrier(HInstanceOf * instance_of)465   bool InstanceOfNeedsReadBarrier(HInstanceOf* instance_of) {
466     // Used only for `kExactCheck`, `kAbstractClassCheck`, `kClassHierarchyCheck`,
467     // `kArrayObjectCheck` and `kInterfaceCheck`.
468     DCHECK(instance_of->GetTypeCheckKind() == TypeCheckKind::kExactCheck ||
469            instance_of->GetTypeCheckKind() == TypeCheckKind::kAbstractClassCheck ||
470            instance_of->GetTypeCheckKind() == TypeCheckKind::kClassHierarchyCheck ||
471            instance_of->GetTypeCheckKind() == TypeCheckKind::kArrayObjectCheck ||
472            instance_of->GetTypeCheckKind() == TypeCheckKind::kInterfaceCheck)
473         << instance_of->GetTypeCheckKind();
474     // If the target class is in the boot or app image, it's non-moveable and it doesn't matter
475     // if we compare it with a from-space or to-space reference, the result is the same.
476     // It's OK to traverse a class hierarchy jumping between from-space and to-space.
477     return EmitReadBarrier() && !instance_of->GetTargetClass()->IsInImage();
478   }
479 
ReadBarrierOptionForInstanceOf(HInstanceOf * instance_of)480   ReadBarrierOption ReadBarrierOptionForInstanceOf(HInstanceOf* instance_of) {
481     return InstanceOfNeedsReadBarrier(instance_of) ? kWithReadBarrier : kWithoutReadBarrier;
482   }
483 
IsTypeCheckSlowPathFatal(HCheckCast * check_cast)484   bool IsTypeCheckSlowPathFatal(HCheckCast* check_cast) {
485     switch (check_cast->GetTypeCheckKind()) {
486       case TypeCheckKind::kExactCheck:
487       case TypeCheckKind::kAbstractClassCheck:
488       case TypeCheckKind::kClassHierarchyCheck:
489       case TypeCheckKind::kArrayObjectCheck:
490       case TypeCheckKind::kInterfaceCheck: {
491         bool needs_read_barrier =
492             EmitReadBarrier() && !check_cast->GetTargetClass()->IsInImage();
493         // We do not emit read barriers for HCheckCast, so we can get false negatives
494         // and the slow path shall re-check and simply return if the cast is actually OK.
495         return !needs_read_barrier;
496       }
497       case TypeCheckKind::kArrayCheck:
498       case TypeCheckKind::kUnresolvedCheck:
499         return false;
500       case TypeCheckKind::kBitstringCheck:
501         return true;
502     }
503     LOG(FATAL) << "Unreachable";
504     UNREACHABLE();
505   }
506 
GetCheckCastCallKind(HCheckCast * check_cast)507   LocationSummary::CallKind GetCheckCastCallKind(HCheckCast* check_cast) {
508     return (IsTypeCheckSlowPathFatal(check_cast) && !check_cast->CanThrowIntoCatchBlock())
509         ? LocationSummary::kNoCall  // In fact, call on a fatal (non-returning) slow path.
510         : LocationSummary::kCallOnSlowPath;
511   }
512 
StoreNeedsWriteBarrier(DataType::Type type,HInstruction * value)513   static bool StoreNeedsWriteBarrier(DataType::Type type, HInstruction* value) {
514     // Check that null value is not represented as an integer constant.
515     DCHECK_IMPLIES(type == DataType::Type::kReference, !value->IsIntConstant());
516     return type == DataType::Type::kReference && !value->IsNullConstant();
517   }
518 
519   // If we are compiling a graph with the WBE pass enabled, we want to honor the WriteBarrierKind
520   // set during the WBE pass.
521   bool StoreNeedsWriteBarrier(DataType::Type type,
522                               HInstruction* value,
523                               WriteBarrierKind write_barrier_kind) const;
524 
525   // Performs checks pertaining to an InvokeRuntime call.
526   void ValidateInvokeRuntime(QuickEntrypointEnum entrypoint,
527                              HInstruction* instruction,
528                              SlowPathCode* slow_path);
529 
530   // Performs checks pertaining to an InvokeRuntimeWithoutRecordingPcInfo call.
531   static void ValidateInvokeRuntimeWithoutRecordingPcInfo(HInstruction* instruction,
532                                                           SlowPathCode* slow_path);
533 
AddAllocatedRegister(Location location)534   void AddAllocatedRegister(Location location) {
535     allocated_registers_.Add(location);
536   }
537 
HasAllocatedRegister(bool is_core,int reg)538   bool HasAllocatedRegister(bool is_core, int reg) const {
539     return is_core
540         ? allocated_registers_.ContainsCoreRegister(reg)
541         : allocated_registers_.ContainsFloatingPointRegister(reg);
542   }
543 
544   void AllocateLocations(HInstruction* instruction);
545 
546   // Tells whether the stack frame of the compiled method is
547   // considered "empty", that is either actually having a size of zero,
548   // or just containing the saved return address register.
HasEmptyFrame()549   bool HasEmptyFrame() const {
550     return GetFrameSize() == (CallPushesPC() ? GetWordSize() : 0);
551   }
552 
GetInt8ValueOf(HConstant * constant)553   static int8_t GetInt8ValueOf(HConstant* constant) {
554     DCHECK(constant->IsIntConstant());
555     return constant->AsIntConstant()->GetValue();
556   }
557 
GetInt16ValueOf(HConstant * constant)558   static int16_t GetInt16ValueOf(HConstant* constant) {
559     DCHECK(constant->IsIntConstant());
560     return constant->AsIntConstant()->GetValue();
561   }
562 
GetInt32ValueOf(HConstant * constant)563   static int32_t GetInt32ValueOf(HConstant* constant) {
564     if (constant->IsIntConstant()) {
565       return constant->AsIntConstant()->GetValue();
566     } else if (constant->IsNullConstant()) {
567       return 0;
568     } else {
569       DCHECK(constant->IsFloatConstant());
570       return bit_cast<int32_t, float>(constant->AsFloatConstant()->GetValue());
571     }
572   }
573 
GetInt64ValueOf(HConstant * constant)574   static int64_t GetInt64ValueOf(HConstant* constant) {
575     if (constant->IsIntConstant()) {
576       return constant->AsIntConstant()->GetValue();
577     } else if (constant->IsNullConstant()) {
578       return 0;
579     } else if (constant->IsFloatConstant()) {
580       return bit_cast<int32_t, float>(constant->AsFloatConstant()->GetValue());
581     } else if (constant->IsLongConstant()) {
582       return constant->AsLongConstant()->GetValue();
583     } else {
584       DCHECK(constant->IsDoubleConstant());
585       return bit_cast<int64_t, double>(constant->AsDoubleConstant()->GetValue());
586     }
587   }
588 
GetFirstRegisterSlotInSlowPath()589   size_t GetFirstRegisterSlotInSlowPath() const {
590     return first_register_slot_in_slow_path_;
591   }
592 
FrameEntrySpillSize()593   uint32_t FrameEntrySpillSize() const {
594     return GetFpuSpillSize() + GetCoreSpillSize();
595   }
596 
597   virtual ParallelMoveResolver* GetMoveResolver() = 0;
598 
599   static void CreateCommonInvokeLocationSummary(
600       HInvoke* invoke, InvokeDexCallingConventionVisitor* visitor);
601 
602   template <typename CriticalNativeCallingConventionVisitor,
603             size_t kNativeStackAlignment,
604             size_t GetCriticalNativeDirectCallFrameSize(std::string_view shorty)>
PrepareCriticalNativeCall(HInvokeStaticOrDirect * invoke)605   size_t PrepareCriticalNativeCall(HInvokeStaticOrDirect* invoke) {
606       DCHECK(!invoke->GetLocations()->Intrinsified());
607       CriticalNativeCallingConventionVisitor calling_convention_visitor(
608           /*for_register_allocation=*/ false);
609       HParallelMove parallel_move(GetGraph()->GetAllocator());
610       PrepareCriticalNativeArgumentMoves(invoke, &calling_convention_visitor, &parallel_move);
611       size_t out_frame_size =
612           RoundUp(calling_convention_visitor.GetStackOffset(), kNativeStackAlignment);
613       if (kIsDebugBuild) {
614         std::string_view shorty = GetCriticalNativeShorty(invoke);
615         CHECK_EQ(GetCriticalNativeDirectCallFrameSize(shorty), out_frame_size);
616       }
617       if (out_frame_size != 0u) {
618         FinishCriticalNativeFrameSetup(out_frame_size, &parallel_move);
619       }
620       return out_frame_size;
621   }
622 
623   void GenerateInvokeStaticOrDirectRuntimeCall(
624       HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path);
625 
626   void GenerateInvokeUnresolvedRuntimeCall(HInvokeUnresolved* invoke);
627 
628   void GenerateInvokePolymorphicCall(HInvokePolymorphic* invoke, SlowPathCode* slow_path = nullptr);
629 
630   void GenerateInvokeCustomCall(HInvokeCustom* invoke);
631 
632   void CreateStringBuilderAppendLocations(HStringBuilderAppend* instruction, Location out);
633 
634   void CreateUnresolvedFieldLocationSummary(
635       HInstruction* field_access,
636       DataType::Type field_type,
637       const FieldAccessCallingConvention& calling_convention);
638 
639   void GenerateUnresolvedFieldAccess(
640       HInstruction* field_access,
641       DataType::Type field_type,
642       uint32_t field_index,
643       uint32_t dex_pc,
644       const FieldAccessCallingConvention& calling_convention);
645 
646   static void CreateLoadClassRuntimeCallLocationSummary(HLoadClass* cls,
647                                                         Location runtime_type_index_location,
648                                                         Location runtime_return_location);
649   void GenerateLoadClassRuntimeCall(HLoadClass* cls);
650 
651   static void CreateLoadMethodHandleRuntimeCallLocationSummary(HLoadMethodHandle* method_handle,
652                                                              Location runtime_handle_index_location,
653                                                              Location runtime_return_location);
654   void GenerateLoadMethodHandleRuntimeCall(HLoadMethodHandle* method_handle);
655 
656   static void CreateLoadMethodTypeRuntimeCallLocationSummary(HLoadMethodType* method_type,
657                                                              Location runtime_type_index_location,
658                                                              Location runtime_return_location);
659   void GenerateLoadMethodTypeRuntimeCall(HLoadMethodType* method_type);
660 
661   static uint32_t GetBootImageOffset(ObjPtr<mirror::Object> object)
662       REQUIRES_SHARED(Locks::mutator_lock_);
663   static uint32_t GetBootImageOffset(HLoadClass* load_class);
664   static uint32_t GetBootImageOffset(HLoadString* load_string);
665   static uint32_t GetBootImageOffset(HInvoke* invoke);
666   static uint32_t GetBootImageOffset(ClassRoot class_root);
667   static uint32_t GetBootImageOffsetOfIntrinsicDeclaringClass(HInvoke* invoke);
668 
669   static LocationSummary* CreateSystemArrayCopyLocationSummary(
670       HInvoke* invoke, int32_t length_threshold = -1, size_t num_temps = 3);
671 
SetDisassemblyInformation(DisassemblyInformation * info)672   void SetDisassemblyInformation(DisassemblyInformation* info) { disasm_info_ = info; }
GetDisassemblyInformation()673   DisassemblyInformation* GetDisassemblyInformation() const { return disasm_info_; }
674 
675   virtual void InvokeRuntime(QuickEntrypointEnum entrypoint,
676                              HInstruction* instruction,
677                              uint32_t dex_pc,
678                              SlowPathCode* slow_path = nullptr) = 0;
679 
680   // Check if the desired_string_load_kind is supported. If it is, return it,
681   // otherwise return a fall-back kind that should be used instead.
682   virtual HLoadString::LoadKind GetSupportedLoadStringKind(
683       HLoadString::LoadKind desired_string_load_kind) = 0;
684 
685   // Check if the desired_class_load_kind is supported. If it is, return it,
686   // otherwise return a fall-back kind that should be used instead.
687   virtual HLoadClass::LoadKind GetSupportedLoadClassKind(
688       HLoadClass::LoadKind desired_class_load_kind) = 0;
689 
GetLoadStringCallKind(HLoadString * load)690   LocationSummary::CallKind GetLoadStringCallKind(HLoadString* load) {
691     switch (load->GetLoadKind()) {
692       case HLoadString::LoadKind::kBssEntry:
693         DCHECK(load->NeedsEnvironment());
694         return LocationSummary::kCallOnSlowPath;
695       case HLoadString::LoadKind::kRuntimeCall:
696         DCHECK(load->NeedsEnvironment());
697         return LocationSummary::kCallOnMainOnly;
698       case HLoadString::LoadKind::kJitTableAddress:
699         DCHECK(!load->NeedsEnvironment());
700         return EmitReadBarrier()
701             ? LocationSummary::kCallOnSlowPath
702             : LocationSummary::kNoCall;
703         break;
704       default:
705         DCHECK(!load->NeedsEnvironment());
706         return LocationSummary::kNoCall;
707     }
708   }
709 
710   // Check if the desired_dispatch_info is supported. If it is, return it,
711   // otherwise return a fall-back info that should be used instead.
712   virtual HInvokeStaticOrDirect::DispatchInfo GetSupportedInvokeStaticOrDirectDispatch(
713       const HInvokeStaticOrDirect::DispatchInfo& desired_dispatch_info,
714       ArtMethod* method) = 0;
715 
716   // Generate a call to a static or direct method.
717   virtual void GenerateStaticOrDirectCall(
718       HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path = nullptr) = 0;
719   // Generate a call to a virtual method.
720   virtual void GenerateVirtualCall(
721       HInvokeVirtual* invoke, Location temp, SlowPathCode* slow_path = nullptr) = 0;
722 
723   // Copy the result of a call into the given target.
724   virtual void MoveFromReturnRegister(Location trg, DataType::Type type) = 0;
725 
726   virtual void IncreaseFrame(size_t adjustment) = 0;
727   virtual void DecreaseFrame(size_t adjustment) = 0;
728 
729   virtual void GenerateNop() = 0;
730 
731   static QuickEntrypointEnum GetArrayAllocationEntrypoint(HNewArray* new_array);
732   static ScaleFactor ScaleFactorForType(DataType::Type type);
733 
GetCode()734   ArrayRef<const uint8_t> GetCode() const {
735     return ArrayRef<const uint8_t>(GetAssembler().CodeBufferBaseAddress(),
736                                    GetAssembler().CodeSize());
737   }
738 
739  protected:
740   // Patch info used for recording locations of required linker patches and their targets,
741   // i.e. target method, string, type or code identified by their dex file and index,
742   // or boot image .data.img.rel.ro entries identified by the boot image offset.
743   template <typename LabelType>
744   struct PatchInfo {
PatchInfoPatchInfo745     PatchInfo(const DexFile* dex_file, uint32_t off_or_idx)
746         : target_dex_file(dex_file), offset_or_index(off_or_idx), label() { }
747 
748     // Target dex file or null for boot image .data.img.rel.ro patches.
749     const DexFile* target_dex_file;
750     // Either the boot image offset (to write to .data.img.rel.ro) or string/type/method index.
751     uint32_t offset_or_index;
752     // Label for the instruction to patch.
753     LabelType label;
754   };
755 
756   CodeGenerator(HGraph* graph,
757                 size_t number_of_core_registers,
758                 size_t number_of_fpu_registers,
759                 size_t number_of_register_pairs,
760                 uint32_t core_callee_save_mask,
761                 uint32_t fpu_callee_save_mask,
762                 const CompilerOptions& compiler_options,
763                 OptimizingCompilerStats* stats,
764                 const art::ArrayRef<const bool>& unimplemented_intrinsics);
765 
766   virtual HGraphVisitor* GetLocationBuilder() = 0;
767   virtual HGraphVisitor* GetInstructionVisitor() = 0;
768 
769   template <typename RegType>
ComputeRegisterMask(const RegType * registers,size_t length)770   static uint32_t ComputeRegisterMask(const RegType* registers, size_t length) {
771     uint32_t mask = 0;
772     for (size_t i = 0, e = length; i < e; ++i) {
773       mask |= (1 << registers[i]);
774     }
775     return mask;
776   }
777 
778   // Returns the location of the first spilled entry for floating point registers,
779   // relative to the stack pointer.
GetFpuSpillStart()780   uint32_t GetFpuSpillStart() const {
781     return GetFrameSize() - FrameEntrySpillSize();
782   }
783 
GetFpuSpillSize()784   uint32_t GetFpuSpillSize() const {
785     return POPCOUNT(fpu_spill_mask_) * GetCalleePreservedFPWidth();
786   }
787 
GetCoreSpillSize()788   uint32_t GetCoreSpillSize() const {
789     return POPCOUNT(core_spill_mask_) * GetWordSize();
790   }
791 
HasAllocatedCalleeSaveRegisters()792   virtual bool HasAllocatedCalleeSaveRegisters() const {
793     // We check the core registers against 1 because it always comprises the return PC.
794     return (POPCOUNT(allocated_registers_.GetCoreRegisters() & core_callee_save_mask_) != 1)
795       || (POPCOUNT(allocated_registers_.GetFloatingPointRegisters() & fpu_callee_save_mask_) != 0);
796   }
797 
CallPushesPC()798   bool CallPushesPC() const {
799     InstructionSet instruction_set = GetInstructionSet();
800     return instruction_set == InstructionSet::kX86 || instruction_set == InstructionSet::kX86_64;
801   }
802 
803   // Arm64 has its own type for a label, so we need to templatize these methods
804   // to share the logic.
805 
806   template <typename LabelType>
CommonInitializeLabels()807   LabelType* CommonInitializeLabels() {
808     // We use raw array allocations instead of ArenaVector<> because Labels are
809     // non-constructible and non-movable and as such cannot be held in a vector.
810     size_t size = GetGraph()->GetBlocks().size();
811     LabelType* labels =
812         GetGraph()->GetAllocator()->AllocArray<LabelType>(size, kArenaAllocCodeGenerator);
813     for (size_t i = 0; i != size; ++i) {
814       new(labels + i) LabelType();
815     }
816     return labels;
817   }
818 
819   template <typename LabelType>
CommonGetLabelOf(LabelType * raw_pointer_to_labels_array,HBasicBlock * block)820   LabelType* CommonGetLabelOf(LabelType* raw_pointer_to_labels_array, HBasicBlock* block) const {
821     block = FirstNonEmptyBlock(block);
822     return raw_pointer_to_labels_array + block->GetBlockId();
823   }
824 
GetCurrentSlowPath()825   SlowPathCode* GetCurrentSlowPath() {
826     return current_slow_path_;
827   }
828 
829   StackMapStream* GetStackMapStream();
830 
GetCodeGenerationData()831   CodeGenerationData* GetCodeGenerationData() {
832     return code_generation_data_.get();
833   }
834 
835   void ReserveJitStringRoot(StringReference string_reference, Handle<mirror::String> string);
836   uint64_t GetJitStringRootIndex(StringReference string_reference);
837   void ReserveJitClassRoot(TypeReference type_reference, Handle<mirror::Class> klass);
838   uint64_t GetJitClassRootIndex(TypeReference type_reference);
839   void ReserveJitMethodTypeRoot(ProtoReference proto_reference,
840                                 Handle<mirror::MethodType> method_type);
841   uint64_t GetJitMethodTypeRootIndex(ProtoReference proto_reference);
842 
843   // Emit the patches assocatied with JIT roots. Only applies to JIT compiled code.
844   virtual void EmitJitRootPatches(uint8_t* code, const uint8_t* roots_data);
845 
846   // Frame size required for this method.
847   uint32_t frame_size_;
848   uint32_t core_spill_mask_;
849   uint32_t fpu_spill_mask_;
850   uint32_t first_register_slot_in_slow_path_;
851 
852   // Registers that were allocated during linear scan.
853   RegisterSet allocated_registers_;
854 
855   // Arrays used when doing register allocation to know which
856   // registers we can allocate. `SetupBlockedRegisters` updates the
857   // arrays.
858   bool* const blocked_core_registers_;
859   bool* const blocked_fpu_registers_;
860   size_t number_of_core_registers_;
861   size_t number_of_fpu_registers_;
862   size_t number_of_register_pairs_;
863   const uint32_t core_callee_save_mask_;
864   const uint32_t fpu_callee_save_mask_;
865 
866   // The order to use for code generation.
867   const ArenaVector<HBasicBlock*>* block_order_;
868 
869   DisassemblyInformation* disasm_info_;
870 
871  private:
872   void InitializeCodeGenerationData();
873   size_t GetStackOffsetOfSavedRegister(size_t index);
874   void GenerateSlowPaths();
875   void BlockIfInRegister(Location location, bool is_out = false) const;
876   void EmitEnvironment(HEnvironment* environment,
877                        SlowPathCode* slow_path,
878                        bool needs_vreg_info = true,
879                        bool is_for_catch_handler = false,
880                        bool innermost_environment = true);
881   void EmitVRegInfo(HEnvironment* environment, SlowPathCode* slow_path, bool is_for_catch_handler);
882   void EmitVRegInfoOnlyCatchPhis(HEnvironment* environment);
883 
884   static void PrepareCriticalNativeArgumentMoves(
885       HInvokeStaticOrDirect* invoke,
886       /*inout*/InvokeDexCallingConventionVisitor* visitor,
887       /*out*/HParallelMove* parallel_move);
888 
889   void FinishCriticalNativeFrameSetup(size_t out_frame_size, /*inout*/HParallelMove* parallel_move);
890 
891   static std::string_view GetCriticalNativeShorty(HInvokeStaticOrDirect* invoke);
892 
893   OptimizingCompilerStats* stats_;
894 
895   HGraph* const graph_;
896   const CompilerOptions& compiler_options_;
897 
898   // The current slow-path that we're generating code for.
899   SlowPathCode* current_slow_path_;
900 
901   // The current block index in `block_order_` of the block
902   // we are generating code for.
903   size_t current_block_index_;
904 
905   // Whether the method is a leaf method.
906   bool is_leaf_;
907 
908   // Whether the method has to emit a SuspendCheck at entry.
909   bool needs_suspend_check_entry_;
910 
911   // Whether an instruction in the graph accesses the current method.
912   // TODO: Rename: this actually indicates that some instruction in the method
913   // needs the environment including a valid stack frame.
914   bool requires_current_method_;
915 
916   // The CodeGenerationData contains a ScopedArenaAllocator intended for reusing the
917   // ArenaStack memory allocated in previous passes instead of adding to the memory
918   // held by the ArenaAllocator. This ScopedArenaAllocator is created in
919   // CodeGenerator::Compile() and remains alive until the CodeGenerator is destroyed.
920   std::unique_ptr<CodeGenerationData> code_generation_data_;
921 
922   // Which intrinsics we don't have handcrafted code for.
923   art::ArrayRef<const bool> unimplemented_intrinsics_;
924 
925   friend class OptimizingCFITest;
926   ART_FRIEND_TEST(CodegenTest, ARM64FrameSizeSIMD);
927   ART_FRIEND_TEST(CodegenTest, ARM64FrameSizeNoSIMD);
928 
929   DISALLOW_COPY_AND_ASSIGN(CodeGenerator);
930 };
931 
932 template <typename C, typename F>
933 class CallingConvention {
934  public:
CallingConvention(const C * registers,size_t number_of_registers,const F * fpu_registers,size_t number_of_fpu_registers,PointerSize pointer_size)935   CallingConvention(const C* registers,
936                     size_t number_of_registers,
937                     const F* fpu_registers,
938                     size_t number_of_fpu_registers,
939                     PointerSize pointer_size)
940       : registers_(registers),
941         number_of_registers_(number_of_registers),
942         fpu_registers_(fpu_registers),
943         number_of_fpu_registers_(number_of_fpu_registers),
944         pointer_size_(pointer_size) {}
945 
GetNumberOfRegisters()946   size_t GetNumberOfRegisters() const { return number_of_registers_; }
GetNumberOfFpuRegisters()947   size_t GetNumberOfFpuRegisters() const { return number_of_fpu_registers_; }
948 
GetRegisterAt(size_t index)949   C GetRegisterAt(size_t index) const {
950     DCHECK_LT(index, number_of_registers_);
951     return registers_[index];
952   }
953 
GetFpuRegisterAt(size_t index)954   F GetFpuRegisterAt(size_t index) const {
955     DCHECK_LT(index, number_of_fpu_registers_);
956     return fpu_registers_[index];
957   }
958 
GetStackOffsetOf(size_t index)959   size_t GetStackOffsetOf(size_t index) const {
960     // We still reserve the space for parameters passed by registers.
961     // Add space for the method pointer.
962     return static_cast<size_t>(pointer_size_) + index * kVRegSize;
963   }
964 
965  private:
966   const C* registers_;
967   const size_t number_of_registers_;
968   const F* fpu_registers_;
969   const size_t number_of_fpu_registers_;
970   const PointerSize pointer_size_;
971 
972   DISALLOW_COPY_AND_ASSIGN(CallingConvention);
973 };
974 
975 /**
976  * A templated class SlowPathGenerator with a templated method NewSlowPath()
977  * that can be used by any code generator to share equivalent slow-paths with
978  * the objective of reducing generated code size.
979  *
980  * InstructionType:  instruction that requires SlowPathCodeType
981  * SlowPathCodeType: subclass of SlowPathCode, with constructor SlowPathCodeType(InstructionType *)
982  */
983 template <typename InstructionType>
984 class SlowPathGenerator {
985   static_assert(std::is_base_of<HInstruction, InstructionType>::value,
986                 "InstructionType is not a subclass of art::HInstruction");
987 
988  public:
SlowPathGenerator(HGraph * graph,CodeGenerator * codegen)989   SlowPathGenerator(HGraph* graph, CodeGenerator* codegen)
990       : graph_(graph),
991         codegen_(codegen),
992         slow_path_map_(std::less<uint32_t>(),
993                        graph->GetAllocator()->Adapter(kArenaAllocSlowPaths)) {}
994 
995   // Creates and adds a new slow-path, if needed, or returns existing one otherwise.
996   // Templating the method (rather than the whole class) on the slow-path type enables
997   // keeping this code at a generic, non architecture-specific place.
998   //
999   // NOTE: This approach assumes each InstructionType only generates one SlowPathCodeType.
1000   //       To relax this requirement, we would need some RTTI on the stored slow-paths,
1001   //       or template the class as a whole on SlowPathType.
1002   template <typename SlowPathCodeType>
NewSlowPath(InstructionType * instruction)1003   SlowPathCodeType* NewSlowPath(InstructionType* instruction) {
1004     static_assert(std::is_base_of<SlowPathCode, SlowPathCodeType>::value,
1005                   "SlowPathCodeType is not a subclass of art::SlowPathCode");
1006     static_assert(std::is_constructible<SlowPathCodeType, InstructionType*>::value,
1007                   "SlowPathCodeType is not constructible from InstructionType*");
1008     // Iterate over potential candidates for sharing. Currently, only same-typed
1009     // slow-paths with exactly the same dex-pc are viable candidates.
1010     // TODO: pass dex-pc/slow-path-type to run-time to allow even more sharing?
1011     const uint32_t dex_pc = instruction->GetDexPc();
1012     auto iter = slow_path_map_.find(dex_pc);
1013     if (iter != slow_path_map_.end()) {
1014       const ArenaVector<std::pair<InstructionType*, SlowPathCode*>>& candidates = iter->second;
1015       for (const auto& it : candidates) {
1016         InstructionType* other_instruction = it.first;
1017         SlowPathCodeType* other_slow_path = down_cast<SlowPathCodeType*>(it.second);
1018         // Determine if the instructions allow for slow-path sharing.
1019         if (HaveSameLiveRegisters(instruction, other_instruction) &&
1020             HaveSameStackMap(instruction, other_instruction)) {
1021           // Can share: reuse existing one.
1022           return other_slow_path;
1023         }
1024       }
1025     } else {
1026       // First time this dex-pc is seen.
1027       iter = slow_path_map_.Put(dex_pc,
1028                                 {{}, {graph_->GetAllocator()->Adapter(kArenaAllocSlowPaths)}});
1029     }
1030     // Cannot share: create and add new slow-path for this particular dex-pc.
1031     SlowPathCodeType* slow_path =
1032         new (codegen_->GetScopedAllocator()) SlowPathCodeType(instruction);
1033     iter->second.emplace_back(std::make_pair(instruction, slow_path));
1034     codegen_->AddSlowPath(slow_path);
1035     return slow_path;
1036   }
1037 
1038  private:
1039   // Tests if both instructions have same set of live physical registers. This ensures
1040   // the slow-path has exactly the same preamble on saving these registers to stack.
HaveSameLiveRegisters(const InstructionType * i1,const InstructionType * i2)1041   bool HaveSameLiveRegisters(const InstructionType* i1, const InstructionType* i2) const {
1042     const uint32_t core_spill = ~codegen_->GetCoreSpillMask();
1043     const uint32_t fpu_spill = ~codegen_->GetFpuSpillMask();
1044     RegisterSet* live1 = i1->GetLocations()->GetLiveRegisters();
1045     RegisterSet* live2 = i2->GetLocations()->GetLiveRegisters();
1046     return (((live1->GetCoreRegisters() & core_spill) ==
1047              (live2->GetCoreRegisters() & core_spill)) &&
1048             ((live1->GetFloatingPointRegisters() & fpu_spill) ==
1049              (live2->GetFloatingPointRegisters() & fpu_spill)));
1050   }
1051 
1052   // Tests if both instructions have the same stack map. This ensures the interpreter
1053   // will find exactly the same dex-registers at the same entries.
HaveSameStackMap(const InstructionType * i1,const InstructionType * i2)1054   bool HaveSameStackMap(const InstructionType* i1, const InstructionType* i2) const {
1055     DCHECK(i1->HasEnvironment());
1056     DCHECK(i2->HasEnvironment());
1057     // We conservatively test if the two instructions find exactly the same instructions
1058     // and location in each dex-register. This guarantees they will have the same stack map.
1059     HEnvironment* e1 = i1->GetEnvironment();
1060     HEnvironment* e2 = i2->GetEnvironment();
1061     if (e1->GetParent() != e2->GetParent() || e1->Size() != e2->Size()) {
1062       return false;
1063     }
1064     for (size_t i = 0, sz = e1->Size(); i < sz; ++i) {
1065       if (e1->GetInstructionAt(i) != e2->GetInstructionAt(i) ||
1066           !e1->GetLocationAt(i).Equals(e2->GetLocationAt(i))) {
1067         return false;
1068       }
1069     }
1070     return true;
1071   }
1072 
1073   HGraph* const graph_;
1074   CodeGenerator* const codegen_;
1075 
1076   // Map from dex-pc to vector of already existing instruction/slow-path pairs.
1077   ArenaSafeMap<uint32_t, ArenaVector<std::pair<InstructionType*, SlowPathCode*>>> slow_path_map_;
1078 
1079   DISALLOW_COPY_AND_ASSIGN(SlowPathGenerator);
1080 };
1081 
1082 class InstructionCodeGenerator : public HGraphVisitor {
1083  public:
InstructionCodeGenerator(HGraph * graph,CodeGenerator * codegen)1084   InstructionCodeGenerator(HGraph* graph, CodeGenerator* codegen)
1085       : HGraphVisitor(graph),
1086         deopt_slow_paths_(graph, codegen) {}
1087 
1088  protected:
1089   // Add slow-path generator for each instruction/slow-path combination that desires sharing.
1090   // TODO: under current regime, only deopt sharing make sense; extend later.
1091   SlowPathGenerator<HDeoptimize> deopt_slow_paths_;
1092 };
1093 
1094 }  // namespace art
1095 
1096 #endif  // ART_COMPILER_OPTIMIZING_CODE_GENERATOR_H_
1097