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_NODES_H_
18 #define ART_COMPILER_OPTIMIZING_NODES_H_
19
20 #include <algorithm>
21 #include <array>
22 #include <type_traits>
23
24 #include "art_method.h"
25 #include "base/arena_allocator.h"
26 #include "base/arena_bit_vector.h"
27 #include "base/arena_containers.h"
28 #include "base/arena_object.h"
29 #include "base/array_ref.h"
30 #include "base/intrusive_forward_list.h"
31 #include "base/iteration_range.h"
32 #include "base/mutex.h"
33 #include "base/quasi_atomic.h"
34 #include "base/stl_util.h"
35 #include "base/transform_array_ref.h"
36 #include "block_namer.h"
37 #include "class_root.h"
38 #include "compilation_kind.h"
39 #include "data_type.h"
40 #include "deoptimization_kind.h"
41 #include "dex/dex_file.h"
42 #include "dex/dex_file_types.h"
43 #include "dex/invoke_type.h"
44 #include "dex/method_reference.h"
45 #include "entrypoints/quick/quick_entrypoints_enum.h"
46 #include "handle.h"
47 #include "handle_scope.h"
48 #include "intrinsics_enum.h"
49 #include "locations.h"
50 #include "mirror/class.h"
51 #include "mirror/method_type.h"
52 #include "offsets.h"
53
54 namespace art {
55
56 class ArenaStack;
57 class CodeGenerator;
58 class GraphChecker;
59 class HBasicBlock;
60 class HConstructorFence;
61 class HCurrentMethod;
62 class HDoubleConstant;
63 class HEnvironment;
64 class HFloatConstant;
65 class HGraphBuilder;
66 class HGraphVisitor;
67 class HInstruction;
68 class HIntConstant;
69 class HInvoke;
70 class HLongConstant;
71 class HNullConstant;
72 class HParameterValue;
73 class HPhi;
74 class HSuspendCheck;
75 class HTryBoundary;
76 class FieldInfo;
77 class LiveInterval;
78 class LocationSummary;
79 class ProfilingInfo;
80 class SlowPathCode;
81 class SsaBuilder;
82
83 namespace mirror {
84 class DexCache;
85 } // namespace mirror
86
87 static const int kDefaultNumberOfBlocks = 8;
88 static const int kDefaultNumberOfSuccessors = 2;
89 static const int kDefaultNumberOfPredecessors = 2;
90 static const int kDefaultNumberOfExceptionalPredecessors = 0;
91 static const int kDefaultNumberOfDominatedBlocks = 1;
92 static const int kDefaultNumberOfBackEdges = 1;
93
94 // The maximum (meaningful) distance (31) that can be used in an integer shift/rotate operation.
95 static constexpr int32_t kMaxIntShiftDistance = 0x1f;
96 // The maximum (meaningful) distance (63) that can be used in a long shift/rotate operation.
97 static constexpr int32_t kMaxLongShiftDistance = 0x3f;
98
99 static constexpr uint32_t kUnknownFieldIndex = static_cast<uint32_t>(-1);
100 static constexpr uint16_t kUnknownClassDefIndex = static_cast<uint16_t>(-1);
101
102 static constexpr InvokeType kInvalidInvokeType = static_cast<InvokeType>(-1);
103
104 static constexpr uint32_t kNoDexPc = -1;
105
IsSameDexFile(const DexFile & lhs,const DexFile & rhs)106 inline bool IsSameDexFile(const DexFile& lhs, const DexFile& rhs) {
107 // For the purposes of the compiler, the dex files must actually be the same object
108 // if we want to safely treat them as the same. This is especially important for JIT
109 // as custom class loaders can open the same underlying file (or memory) multiple
110 // times and provide different class resolution but no two class loaders should ever
111 // use the same DexFile object - doing so is an unsupported hack that can lead to
112 // all sorts of weird failures.
113 return &lhs == &rhs;
114 }
115
116 enum IfCondition {
117 // All types.
118 kCondEQ, // ==
119 kCondNE, // !=
120 // Signed integers and floating-point numbers.
121 kCondLT, // <
122 kCondLE, // <=
123 kCondGT, // >
124 kCondGE, // >=
125 // Unsigned integers.
126 kCondB, // <
127 kCondBE, // <=
128 kCondA, // >
129 kCondAE, // >=
130 // First and last aliases.
131 kCondFirst = kCondEQ,
132 kCondLast = kCondAE,
133 };
134
135 enum GraphAnalysisResult {
136 kAnalysisSkipped,
137 kAnalysisInvalidBytecode,
138 kAnalysisFailThrowCatchLoop,
139 kAnalysisFailAmbiguousArrayOp,
140 kAnalysisFailIrreducibleLoopAndStringInit,
141 kAnalysisFailPhiEquivalentInOsr,
142 kAnalysisSuccess,
143 };
144
145 template <typename T>
MakeUnsigned(T x)146 static inline typename std::make_unsigned<T>::type MakeUnsigned(T x) {
147 return static_cast<typename std::make_unsigned<T>::type>(x);
148 }
149
150 class HInstructionList : public ValueObject {
151 public:
HInstructionList()152 HInstructionList() : first_instruction_(nullptr), last_instruction_(nullptr) {}
153
154 void AddInstruction(HInstruction* instruction);
155 void RemoveInstruction(HInstruction* instruction);
156
157 // Insert `instruction` before/after an existing instruction `cursor`.
158 void InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor);
159 void InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor);
160
161 // Return true if this list contains `instruction`.
162 bool Contains(HInstruction* instruction) const;
163
164 // Return true if `instruction1` is found before `instruction2` in
165 // this instruction list and false otherwise. Abort if none
166 // of these instructions is found.
167 bool FoundBefore(const HInstruction* instruction1,
168 const HInstruction* instruction2) const;
169
IsEmpty()170 bool IsEmpty() const { return first_instruction_ == nullptr; }
Clear()171 void Clear() { first_instruction_ = last_instruction_ = nullptr; }
172
173 // Update the block of all instructions to be `block`.
174 void SetBlockOfInstructions(HBasicBlock* block) const;
175
176 void AddAfter(HInstruction* cursor, const HInstructionList& instruction_list);
177 void AddBefore(HInstruction* cursor, const HInstructionList& instruction_list);
178 void Add(const HInstructionList& instruction_list);
179
180 // Return the number of instructions in the list. This is an expensive operation.
181 size_t CountSize() const;
182
183 private:
184 HInstruction* first_instruction_;
185 HInstruction* last_instruction_;
186
187 friend class HBasicBlock;
188 friend class HGraph;
189 friend class HInstruction;
190 friend class HInstructionIterator;
191 friend class HInstructionIteratorHandleChanges;
192 friend class HBackwardInstructionIterator;
193
194 DISALLOW_COPY_AND_ASSIGN(HInstructionList);
195 };
196
197 class ReferenceTypeInfo : ValueObject {
198 public:
199 using TypeHandle = Handle<mirror::Class>;
200
201 static ReferenceTypeInfo Create(TypeHandle type_handle, bool is_exact);
202
Create(TypeHandle type_handle)203 static ReferenceTypeInfo Create(TypeHandle type_handle) REQUIRES_SHARED(Locks::mutator_lock_) {
204 return Create(type_handle, type_handle->CannotBeAssignedFromOtherTypes());
205 }
206
CreateUnchecked(TypeHandle type_handle,bool is_exact)207 static ReferenceTypeInfo CreateUnchecked(TypeHandle type_handle, bool is_exact) {
208 return ReferenceTypeInfo(type_handle, is_exact);
209 }
210
CreateInvalid()211 static ReferenceTypeInfo CreateInvalid() { return ReferenceTypeInfo(); }
212
IsValidHandle(TypeHandle handle)213 static bool IsValidHandle(TypeHandle handle) {
214 return handle.GetReference() != nullptr;
215 }
216
IsValid()217 bool IsValid() const {
218 return IsValidHandle(type_handle_);
219 }
220
IsExact()221 bool IsExact() const { return is_exact_; }
222
IsObjectClass()223 bool IsObjectClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
224 DCHECK(IsValid());
225 return GetTypeHandle()->IsObjectClass();
226 }
227
IsStringClass()228 bool IsStringClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
229 DCHECK(IsValid());
230 return GetTypeHandle()->IsStringClass();
231 }
232
IsObjectArray()233 bool IsObjectArray() const REQUIRES_SHARED(Locks::mutator_lock_) {
234 DCHECK(IsValid());
235 return IsArrayClass() && GetTypeHandle()->GetComponentType()->IsObjectClass();
236 }
237
IsInterface()238 bool IsInterface() const REQUIRES_SHARED(Locks::mutator_lock_) {
239 DCHECK(IsValid());
240 return GetTypeHandle()->IsInterface();
241 }
242
IsArrayClass()243 bool IsArrayClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
244 DCHECK(IsValid());
245 return GetTypeHandle()->IsArrayClass();
246 }
247
IsPrimitiveArrayClass()248 bool IsPrimitiveArrayClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
249 DCHECK(IsValid());
250 return GetTypeHandle()->IsPrimitiveArray();
251 }
252
IsNonPrimitiveArrayClass()253 bool IsNonPrimitiveArrayClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
254 DCHECK(IsValid());
255 return GetTypeHandle()->IsArrayClass() && !GetTypeHandle()->IsPrimitiveArray();
256 }
257
CanArrayHold(ReferenceTypeInfo rti)258 bool CanArrayHold(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
259 DCHECK(IsValid());
260 if (!IsExact()) return false;
261 if (!IsArrayClass()) return false;
262 return GetTypeHandle()->GetComponentType()->IsAssignableFrom(rti.GetTypeHandle().Get());
263 }
264
CanArrayHoldValuesOf(ReferenceTypeInfo rti)265 bool CanArrayHoldValuesOf(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
266 DCHECK(IsValid());
267 if (!IsExact()) return false;
268 if (!IsArrayClass()) return false;
269 if (!rti.IsArrayClass()) return false;
270 return GetTypeHandle()->GetComponentType()->IsAssignableFrom(
271 rti.GetTypeHandle()->GetComponentType());
272 }
273
GetTypeHandle()274 Handle<mirror::Class> GetTypeHandle() const { return type_handle_; }
275
IsSupertypeOf(ReferenceTypeInfo rti)276 bool IsSupertypeOf(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
277 DCHECK(IsValid());
278 DCHECK(rti.IsValid());
279 return GetTypeHandle()->IsAssignableFrom(rti.GetTypeHandle().Get());
280 }
281
282 // Returns true if the type information provide the same amount of details.
283 // Note that it does not mean that the instructions have the same actual type
284 // (because the type can be the result of a merge).
IsEqual(ReferenceTypeInfo rti)285 bool IsEqual(ReferenceTypeInfo rti) const REQUIRES_SHARED(Locks::mutator_lock_) {
286 if (!IsValid() && !rti.IsValid()) {
287 // Invalid types are equal.
288 return true;
289 }
290 if (!IsValid() || !rti.IsValid()) {
291 // One is valid, the other not.
292 return false;
293 }
294 return IsExact() == rti.IsExact()
295 && GetTypeHandle().Get() == rti.GetTypeHandle().Get();
296 }
297
298 private:
ReferenceTypeInfo()299 ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
ReferenceTypeInfo(TypeHandle type_handle,bool is_exact)300 ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
301 : type_handle_(type_handle), is_exact_(is_exact) { }
302
303 // The class of the object.
304 TypeHandle type_handle_;
305 // Whether or not the type is exact or a superclass of the actual type.
306 // Whether or not we have any information about this type.
307 bool is_exact_;
308 };
309
310 std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs);
311
312 class HandleCache {
313 public:
HandleCache(VariableSizedHandleScope * handles)314 explicit HandleCache(VariableSizedHandleScope* handles) : handles_(handles) { }
315
GetHandles()316 VariableSizedHandleScope* GetHandles() { return handles_; }
317
318 template <typename T>
NewHandle(T * object)319 MutableHandle<T> NewHandle(T* object) REQUIRES_SHARED(Locks::mutator_lock_) {
320 return handles_->NewHandle(object);
321 }
322
323 template <typename T>
NewHandle(ObjPtr<T> object)324 MutableHandle<T> NewHandle(ObjPtr<T> object) REQUIRES_SHARED(Locks::mutator_lock_) {
325 return handles_->NewHandle(object);
326 }
327
GetObjectClassHandle()328 ReferenceTypeInfo::TypeHandle GetObjectClassHandle() {
329 return GetRootHandle(ClassRoot::kJavaLangObject, &object_class_handle_);
330 }
331
GetClassClassHandle()332 ReferenceTypeInfo::TypeHandle GetClassClassHandle() {
333 return GetRootHandle(ClassRoot::kJavaLangClass, &class_class_handle_);
334 }
335
GetMethodHandleClassHandle()336 ReferenceTypeInfo::TypeHandle GetMethodHandleClassHandle() {
337 return GetRootHandle(ClassRoot::kJavaLangInvokeMethodHandleImpl, &method_handle_class_handle_);
338 }
339
GetMethodTypeClassHandle()340 ReferenceTypeInfo::TypeHandle GetMethodTypeClassHandle() {
341 return GetRootHandle(ClassRoot::kJavaLangInvokeMethodType, &method_type_class_handle_);
342 }
343
GetStringClassHandle()344 ReferenceTypeInfo::TypeHandle GetStringClassHandle() {
345 return GetRootHandle(ClassRoot::kJavaLangString, &string_class_handle_);
346 }
347
GetThrowableClassHandle()348 ReferenceTypeInfo::TypeHandle GetThrowableClassHandle() {
349 return GetRootHandle(ClassRoot::kJavaLangThrowable, &throwable_class_handle_);
350 }
351
352
353 private:
GetRootHandle(ClassRoot class_root,ReferenceTypeInfo::TypeHandle * cache)354 inline ReferenceTypeInfo::TypeHandle GetRootHandle(ClassRoot class_root,
355 ReferenceTypeInfo::TypeHandle* cache) {
356 if (UNLIKELY(!ReferenceTypeInfo::IsValidHandle(*cache))) {
357 *cache = CreateRootHandle(handles_, class_root);
358 }
359 return *cache;
360 }
361
362 static ReferenceTypeInfo::TypeHandle CreateRootHandle(VariableSizedHandleScope* handles,
363 ClassRoot class_root);
364
365 VariableSizedHandleScope* handles_;
366
367 ReferenceTypeInfo::TypeHandle object_class_handle_;
368 ReferenceTypeInfo::TypeHandle class_class_handle_;
369 ReferenceTypeInfo::TypeHandle method_handle_class_handle_;
370 ReferenceTypeInfo::TypeHandle method_type_class_handle_;
371 ReferenceTypeInfo::TypeHandle string_class_handle_;
372 ReferenceTypeInfo::TypeHandle throwable_class_handle_;
373 };
374
375 // Control-flow graph of a method. Contains a list of basic blocks.
376 class HGraph : public ArenaObject<kArenaAllocGraph> {
377 public:
378 HGraph(ArenaAllocator* allocator,
379 ArenaStack* arena_stack,
380 VariableSizedHandleScope* handles,
381 const DexFile& dex_file,
382 uint32_t method_idx,
383 InstructionSet instruction_set,
384 InvokeType invoke_type = kInvalidInvokeType,
385 bool dead_reference_safe = false,
386 bool debuggable = false,
387 CompilationKind compilation_kind = CompilationKind::kOptimized,
388 int start_instruction_id = 0)
allocator_(allocator)389 : allocator_(allocator),
390 arena_stack_(arena_stack),
391 handle_cache_(handles),
392 blocks_(allocator->Adapter(kArenaAllocBlockList)),
393 reverse_post_order_(allocator->Adapter(kArenaAllocReversePostOrder)),
394 linear_order_(allocator->Adapter(kArenaAllocLinearOrder)),
395 reachability_graph_(allocator, 0, 0, true, kArenaAllocReachabilityGraph),
396 entry_block_(nullptr),
397 exit_block_(nullptr),
398 maximum_number_of_out_vregs_(0),
399 number_of_vregs_(0),
400 number_of_in_vregs_(0),
401 temporaries_vreg_slots_(0),
402 has_bounds_checks_(false),
403 has_try_catch_(false),
404 has_monitor_operations_(false),
405 has_simd_(false),
406 has_loops_(false),
407 has_irreducible_loops_(false),
408 has_direct_critical_native_call_(false),
409 dead_reference_safe_(dead_reference_safe),
410 debuggable_(debuggable),
411 current_instruction_id_(start_instruction_id),
412 dex_file_(dex_file),
413 method_idx_(method_idx),
414 invoke_type_(invoke_type),
415 in_ssa_form_(false),
416 number_of_cha_guards_(0),
417 instruction_set_(instruction_set),
418 cached_null_constant_(nullptr),
419 cached_int_constants_(std::less<int32_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
420 cached_float_constants_(std::less<int32_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
421 cached_long_constants_(std::less<int64_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
422 cached_double_constants_(std::less<int64_t>(), allocator->Adapter(kArenaAllocConstantsMap)),
423 cached_current_method_(nullptr),
424 art_method_(nullptr),
425 compilation_kind_(compilation_kind),
426 cha_single_implementation_list_(allocator->Adapter(kArenaAllocCHA)) {
427 blocks_.reserve(kDefaultNumberOfBlocks);
428 }
429
430 std::ostream& Dump(std::ostream& os,
431 CodeGenerator* codegen,
432 std::optional<std::reference_wrapper<const BlockNamer>> namer = std::nullopt);
433
GetAllocator()434 ArenaAllocator* GetAllocator() const { return allocator_; }
GetArenaStack()435 ArenaStack* GetArenaStack() const { return arena_stack_; }
436
GetHandleCache()437 HandleCache* GetHandleCache() { return &handle_cache_; }
438
GetBlocks()439 const ArenaVector<HBasicBlock*>& GetBlocks() const { return blocks_; }
440
441 // An iterator to only blocks that are still actually in the graph (when
442 // blocks are removed they are replaced with 'nullptr' in GetBlocks to
443 // simplify block-id assignment and avoid memmoves in the block-list).
GetActiveBlocks()444 IterationRange<FilterNull<ArenaVector<HBasicBlock*>::const_iterator>> GetActiveBlocks() const {
445 return FilterOutNull(MakeIterationRange(GetBlocks()));
446 }
447
IsInSsaForm()448 bool IsInSsaForm() const { return in_ssa_form_; }
SetInSsaForm()449 void SetInSsaForm() { in_ssa_form_ = true; }
450
GetEntryBlock()451 HBasicBlock* GetEntryBlock() const { return entry_block_; }
GetExitBlock()452 HBasicBlock* GetExitBlock() const { return exit_block_; }
HasExitBlock()453 bool HasExitBlock() const { return exit_block_ != nullptr; }
454
SetEntryBlock(HBasicBlock * block)455 void SetEntryBlock(HBasicBlock* block) { entry_block_ = block; }
SetExitBlock(HBasicBlock * block)456 void SetExitBlock(HBasicBlock* block) { exit_block_ = block; }
457
458 void AddBlock(HBasicBlock* block);
459
460 void ComputeDominanceInformation();
461 void ClearDominanceInformation();
462 void ComputeReachabilityInformation();
463 void ClearReachabilityInformation();
464 void ClearLoopInformation();
465 void FindBackEdges(ArenaBitVector* visited);
466 GraphAnalysisResult BuildDominatorTree();
467 void SimplifyCFG();
468 void SimplifyCatchBlocks();
469
470 // Analyze all natural loops in this graph. Returns a code specifying that it
471 // was successful or the reason for failure. The method will fail if a loop
472 // is a throw-catch loop, i.e. the header is a catch block.
473 GraphAnalysisResult AnalyzeLoops() const;
474
475 // Iterate over blocks to compute try block membership. Needs reverse post
476 // order and loop information.
477 void ComputeTryBlockInformation();
478
479 // Inline this graph in `outer_graph`, replacing the given `invoke` instruction.
480 // Returns the instruction to replace the invoke expression or null if the
481 // invoke is for a void method. Note that the caller is responsible for replacing
482 // and removing the invoke instruction.
483 HInstruction* InlineInto(HGraph* outer_graph, HInvoke* invoke);
484
485 // Update the loop and try membership of `block`, which was spawned from `reference`.
486 // In case `reference` is a back edge, `replace_if_back_edge` notifies whether `block`
487 // should be the new back edge.
488 void UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
489 HBasicBlock* reference,
490 bool replace_if_back_edge);
491
492 // Need to add a couple of blocks to test if the loop body is entered and
493 // put deoptimization instructions, etc.
494 void TransformLoopHeaderForBCE(HBasicBlock* header);
495
496 // Adds a new loop directly after the loop with the given header and exit.
497 // Returns the new preheader.
498 HBasicBlock* TransformLoopForVectorization(HBasicBlock* header,
499 HBasicBlock* body,
500 HBasicBlock* exit);
501
502 // Removes `block` from the graph. Assumes `block` has been disconnected from
503 // other blocks and has no instructions or phis.
504 void DeleteDeadEmptyBlock(HBasicBlock* block);
505
506 // Splits the edge between `block` and `successor` while preserving the
507 // indices in the predecessor/successor lists. If there are multiple edges
508 // between the blocks, the lowest indices are used.
509 // Returns the new block which is empty and has the same dex pc as `successor`.
510 HBasicBlock* SplitEdge(HBasicBlock* block, HBasicBlock* successor);
511
512 void SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor);
513 void OrderLoopHeaderPredecessors(HBasicBlock* header);
514
515 // Transform a loop into a format with a single preheader.
516 //
517 // Each phi in the header should be split: original one in the header should only hold
518 // inputs reachable from the back edges and a single input from the preheader. The newly created
519 // phi in the preheader should collate the inputs from the original multiple incoming blocks.
520 //
521 // Loops in the graph typically have a single preheader, so this method is used to "repair" loops
522 // that no longer have this property.
523 void TransformLoopToSinglePreheaderFormat(HBasicBlock* header);
524
525 void SimplifyLoop(HBasicBlock* header);
526
GetNextInstructionId()527 int32_t GetNextInstructionId() {
528 CHECK_NE(current_instruction_id_, INT32_MAX);
529 return current_instruction_id_++;
530 }
531
GetCurrentInstructionId()532 int32_t GetCurrentInstructionId() const {
533 return current_instruction_id_;
534 }
535
SetCurrentInstructionId(int32_t id)536 void SetCurrentInstructionId(int32_t id) {
537 CHECK_GE(id, current_instruction_id_);
538 current_instruction_id_ = id;
539 }
540
GetMaximumNumberOfOutVRegs()541 uint16_t GetMaximumNumberOfOutVRegs() const {
542 return maximum_number_of_out_vregs_;
543 }
544
SetMaximumNumberOfOutVRegs(uint16_t new_value)545 void SetMaximumNumberOfOutVRegs(uint16_t new_value) {
546 maximum_number_of_out_vregs_ = new_value;
547 }
548
UpdateMaximumNumberOfOutVRegs(uint16_t other_value)549 void UpdateMaximumNumberOfOutVRegs(uint16_t other_value) {
550 maximum_number_of_out_vregs_ = std::max(maximum_number_of_out_vregs_, other_value);
551 }
552
UpdateTemporariesVRegSlots(size_t slots)553 void UpdateTemporariesVRegSlots(size_t slots) {
554 temporaries_vreg_slots_ = std::max(slots, temporaries_vreg_slots_);
555 }
556
GetTemporariesVRegSlots()557 size_t GetTemporariesVRegSlots() const {
558 DCHECK(!in_ssa_form_);
559 return temporaries_vreg_slots_;
560 }
561
SetNumberOfVRegs(uint16_t number_of_vregs)562 void SetNumberOfVRegs(uint16_t number_of_vregs) {
563 number_of_vregs_ = number_of_vregs;
564 }
565
GetNumberOfVRegs()566 uint16_t GetNumberOfVRegs() const {
567 return number_of_vregs_;
568 }
569
SetNumberOfInVRegs(uint16_t value)570 void SetNumberOfInVRegs(uint16_t value) {
571 number_of_in_vregs_ = value;
572 }
573
GetNumberOfInVRegs()574 uint16_t GetNumberOfInVRegs() const {
575 return number_of_in_vregs_;
576 }
577
GetNumberOfLocalVRegs()578 uint16_t GetNumberOfLocalVRegs() const {
579 DCHECK(!in_ssa_form_);
580 return number_of_vregs_ - number_of_in_vregs_;
581 }
582
GetReversePostOrder()583 const ArenaVector<HBasicBlock*>& GetReversePostOrder() const {
584 return reverse_post_order_;
585 }
586
GetReversePostOrderSkipEntryBlock()587 ArrayRef<HBasicBlock* const> GetReversePostOrderSkipEntryBlock() const {
588 DCHECK(GetReversePostOrder()[0] == entry_block_);
589 return ArrayRef<HBasicBlock* const>(GetReversePostOrder()).SubArray(1);
590 }
591
GetPostOrder()592 IterationRange<ArenaVector<HBasicBlock*>::const_reverse_iterator> GetPostOrder() const {
593 return ReverseRange(GetReversePostOrder());
594 }
595
GetLinearOrder()596 const ArenaVector<HBasicBlock*>& GetLinearOrder() const {
597 return linear_order_;
598 }
599
GetLinearPostOrder()600 IterationRange<ArenaVector<HBasicBlock*>::const_reverse_iterator> GetLinearPostOrder() const {
601 return ReverseRange(GetLinearOrder());
602 }
603
HasBoundsChecks()604 bool HasBoundsChecks() const {
605 return has_bounds_checks_;
606 }
607
SetHasBoundsChecks(bool value)608 void SetHasBoundsChecks(bool value) {
609 has_bounds_checks_ = value;
610 }
611
612 // Returns true if dest is reachable from source, using either blocks or block-ids.
613 bool PathBetween(const HBasicBlock* source, const HBasicBlock* dest) const;
614 bool PathBetween(uint32_t source_id, uint32_t dest_id) const;
615
616 // Is the code known to be robust against eliminating dead references
617 // and the effects of early finalization?
IsDeadReferenceSafe()618 bool IsDeadReferenceSafe() const { return dead_reference_safe_; }
619
MarkDeadReferenceUnsafe()620 void MarkDeadReferenceUnsafe() { dead_reference_safe_ = false; }
621
IsDebuggable()622 bool IsDebuggable() const { return debuggable_; }
623
624 // Returns a constant of the given type and value. If it does not exist
625 // already, it is created and inserted into the graph. This method is only for
626 // integral types.
627 HConstant* GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc = kNoDexPc);
628
629 // TODO: This is problematic for the consistency of reference type propagation
630 // because it can be created anytime after the pass and thus it will be left
631 // with an invalid type.
632 HNullConstant* GetNullConstant(uint32_t dex_pc = kNoDexPc);
633
634 HIntConstant* GetIntConstant(int32_t value, uint32_t dex_pc = kNoDexPc) {
635 return CreateConstant(value, &cached_int_constants_, dex_pc);
636 }
637 HLongConstant* GetLongConstant(int64_t value, uint32_t dex_pc = kNoDexPc) {
638 return CreateConstant(value, &cached_long_constants_, dex_pc);
639 }
640 HFloatConstant* GetFloatConstant(float value, uint32_t dex_pc = kNoDexPc) {
641 return CreateConstant(bit_cast<int32_t, float>(value), &cached_float_constants_, dex_pc);
642 }
643 HDoubleConstant* GetDoubleConstant(double value, uint32_t dex_pc = kNoDexPc) {
644 return CreateConstant(bit_cast<int64_t, double>(value), &cached_double_constants_, dex_pc);
645 }
646
647 HCurrentMethod* GetCurrentMethod();
648
GetDexFile()649 const DexFile& GetDexFile() const {
650 return dex_file_;
651 }
652
GetMethodIdx()653 uint32_t GetMethodIdx() const {
654 return method_idx_;
655 }
656
657 // Get the method name (without the signature), e.g. "<init>"
658 const char* GetMethodName() const;
659
660 // Get the pretty method name (class + name + optionally signature).
661 std::string PrettyMethod(bool with_signature = true) const;
662
GetInvokeType()663 InvokeType GetInvokeType() const {
664 return invoke_type_;
665 }
666
GetInstructionSet()667 InstructionSet GetInstructionSet() const {
668 return instruction_set_;
669 }
670
IsCompilingOsr()671 bool IsCompilingOsr() const { return compilation_kind_ == CompilationKind::kOsr; }
672
IsCompilingBaseline()673 bool IsCompilingBaseline() const { return compilation_kind_ == CompilationKind::kBaseline; }
674
GetCompilationKind()675 CompilationKind GetCompilationKind() const { return compilation_kind_; }
676
GetCHASingleImplementationList()677 ArenaSet<ArtMethod*>& GetCHASingleImplementationList() {
678 return cha_single_implementation_list_;
679 }
680
AddCHASingleImplementationDependency(ArtMethod * method)681 void AddCHASingleImplementationDependency(ArtMethod* method) {
682 cha_single_implementation_list_.insert(method);
683 }
684
HasShouldDeoptimizeFlag()685 bool HasShouldDeoptimizeFlag() const {
686 return number_of_cha_guards_ != 0 || debuggable_;
687 }
688
HasTryCatch()689 bool HasTryCatch() const { return has_try_catch_; }
SetHasTryCatch(bool value)690 void SetHasTryCatch(bool value) { has_try_catch_ = value; }
691
HasMonitorOperations()692 bool HasMonitorOperations() const { return has_monitor_operations_; }
SetHasMonitorOperations(bool value)693 void SetHasMonitorOperations(bool value) { has_monitor_operations_ = value; }
694
HasSIMD()695 bool HasSIMD() const { return has_simd_; }
SetHasSIMD(bool value)696 void SetHasSIMD(bool value) { has_simd_ = value; }
697
HasLoops()698 bool HasLoops() const { return has_loops_; }
SetHasLoops(bool value)699 void SetHasLoops(bool value) { has_loops_ = value; }
700
HasIrreducibleLoops()701 bool HasIrreducibleLoops() const { return has_irreducible_loops_; }
SetHasIrreducibleLoops(bool value)702 void SetHasIrreducibleLoops(bool value) { has_irreducible_loops_ = value; }
703
HasDirectCriticalNativeCall()704 bool HasDirectCriticalNativeCall() const { return has_direct_critical_native_call_; }
SetHasDirectCriticalNativeCall(bool value)705 void SetHasDirectCriticalNativeCall(bool value) { has_direct_critical_native_call_ = value; }
706
GetArtMethod()707 ArtMethod* GetArtMethod() const { return art_method_; }
SetArtMethod(ArtMethod * method)708 void SetArtMethod(ArtMethod* method) { art_method_ = method; }
709
SetProfilingInfo(ProfilingInfo * info)710 void SetProfilingInfo(ProfilingInfo* info) { profiling_info_ = info; }
GetProfilingInfo()711 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
712
713 // Returns an instruction with the opposite Boolean value from 'cond'.
714 // The instruction has been inserted into the graph, either as a constant, or
715 // before cursor.
716 HInstruction* InsertOppositeCondition(HInstruction* cond, HInstruction* cursor);
717
GetInexactObjectRti()718 ReferenceTypeInfo GetInexactObjectRti() {
719 return ReferenceTypeInfo::Create(handle_cache_.GetObjectClassHandle(), /* is_exact= */ false);
720 }
721
GetNumberOfCHAGuards()722 uint32_t GetNumberOfCHAGuards() { return number_of_cha_guards_; }
SetNumberOfCHAGuards(uint32_t num)723 void SetNumberOfCHAGuards(uint32_t num) { number_of_cha_guards_ = num; }
IncrementNumberOfCHAGuards()724 void IncrementNumberOfCHAGuards() { number_of_cha_guards_++; }
725
726 private:
727 void RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const;
728 void RemoveDeadBlocks(const ArenaBitVector& visited);
729
730 template <class InstructionType, typename ValueType>
731 InstructionType* CreateConstant(ValueType value,
732 ArenaSafeMap<ValueType, InstructionType*>* cache,
733 uint32_t dex_pc = kNoDexPc) {
734 // Try to find an existing constant of the given value.
735 InstructionType* constant = nullptr;
736 auto cached_constant = cache->find(value);
737 if (cached_constant != cache->end()) {
738 constant = cached_constant->second;
739 }
740
741 // If not found or previously deleted, create and cache a new instruction.
742 // Don't bother reviving a previously deleted instruction, for simplicity.
743 if (constant == nullptr || constant->GetBlock() == nullptr) {
744 constant = new (allocator_) InstructionType(value, dex_pc);
745 cache->Overwrite(value, constant);
746 InsertConstant(constant);
747 }
748 return constant;
749 }
750
751 void InsertConstant(HConstant* instruction);
752
753 // Cache a float constant into the graph. This method should only be
754 // called by the SsaBuilder when creating "equivalent" instructions.
755 void CacheFloatConstant(HFloatConstant* constant);
756
757 // See CacheFloatConstant comment.
758 void CacheDoubleConstant(HDoubleConstant* constant);
759
760 ArenaAllocator* const allocator_;
761 ArenaStack* const arena_stack_;
762
763 HandleCache handle_cache_;
764
765 // List of blocks in insertion order.
766 ArenaVector<HBasicBlock*> blocks_;
767
768 // List of blocks to perform a reverse post order tree traversal.
769 ArenaVector<HBasicBlock*> reverse_post_order_;
770
771 // List of blocks to perform a linear order tree traversal. Unlike the reverse
772 // post order, this order is not incrementally kept up-to-date.
773 ArenaVector<HBasicBlock*> linear_order_;
774
775 // Reachability graph for checking connectedness between nodes. Acts as a partitioned vector where
776 // each RoundUp(blocks_.size(), BitVector::kWordBits) is the reachability of each node.
777 ArenaBitVectorArray reachability_graph_;
778
779 HBasicBlock* entry_block_;
780 HBasicBlock* exit_block_;
781
782 // The maximum number of virtual registers arguments passed to a HInvoke in this graph.
783 uint16_t maximum_number_of_out_vregs_;
784
785 // The number of virtual registers in this method. Contains the parameters.
786 uint16_t number_of_vregs_;
787
788 // The number of virtual registers used by parameters of this method.
789 uint16_t number_of_in_vregs_;
790
791 // Number of vreg size slots that the temporaries use (used in baseline compiler).
792 size_t temporaries_vreg_slots_;
793
794 // Flag whether there are bounds checks in the graph. We can skip
795 // BCE if it's false. It's only best effort to keep it up to date in
796 // the presence of code elimination so there might be false positives.
797 bool has_bounds_checks_;
798
799 // Flag whether there are try/catch blocks in the graph. We will skip
800 // try/catch-related passes if it's false. It's only best effort to keep
801 // it up to date in the presence of code elimination so there might be
802 // false positives.
803 bool has_try_catch_;
804
805 // Flag whether there are any HMonitorOperation in the graph. If yes this will mandate
806 // DexRegisterMap to be present to allow deadlock analysis for non-debuggable code.
807 bool has_monitor_operations_;
808
809 // Flag whether SIMD instructions appear in the graph. If true, the
810 // code generators may have to be more careful spilling the wider
811 // contents of SIMD registers.
812 bool has_simd_;
813
814 // Flag whether there are any loops in the graph. We can skip loop
815 // optimization if it's false. It's only best effort to keep it up
816 // to date in the presence of code elimination so there might be false
817 // positives.
818 bool has_loops_;
819
820 // Flag whether there are any irreducible loops in the graph. It's only
821 // best effort to keep it up to date in the presence of code elimination
822 // so there might be false positives.
823 bool has_irreducible_loops_;
824
825 // Flag whether there are any direct calls to native code registered
826 // for @CriticalNative methods.
827 bool has_direct_critical_native_call_;
828
829 // Is the code known to be robust against eliminating dead references
830 // and the effects of early finalization? If false, dead reference variables
831 // are kept if they might be visible to the garbage collector.
832 // Currently this means that the class was declared to be dead-reference-safe,
833 // the method accesses no reachability-sensitive fields or data, and the same
834 // is true for any methods that were inlined into the current one.
835 bool dead_reference_safe_;
836
837 // Indicates whether the graph should be compiled in a way that
838 // ensures full debuggability. If false, we can apply more
839 // aggressive optimizations that may limit the level of debugging.
840 const bool debuggable_;
841
842 // The current id to assign to a newly added instruction. See HInstruction.id_.
843 int32_t current_instruction_id_;
844
845 // The dex file from which the method is from.
846 const DexFile& dex_file_;
847
848 // The method index in the dex file.
849 const uint32_t method_idx_;
850
851 // If inlined, this encodes how the callee is being invoked.
852 const InvokeType invoke_type_;
853
854 // Whether the graph has been transformed to SSA form. Only used
855 // in debug mode to ensure we are not using properties only valid
856 // for non-SSA form (like the number of temporaries).
857 bool in_ssa_form_;
858
859 // Number of CHA guards in the graph. Used to short-circuit the
860 // CHA guard optimization pass when there is no CHA guard left.
861 uint32_t number_of_cha_guards_;
862
863 const InstructionSet instruction_set_;
864
865 // Cached constants.
866 HNullConstant* cached_null_constant_;
867 ArenaSafeMap<int32_t, HIntConstant*> cached_int_constants_;
868 ArenaSafeMap<int32_t, HFloatConstant*> cached_float_constants_;
869 ArenaSafeMap<int64_t, HLongConstant*> cached_long_constants_;
870 ArenaSafeMap<int64_t, HDoubleConstant*> cached_double_constants_;
871
872 HCurrentMethod* cached_current_method_;
873
874 // The ArtMethod this graph is for. Note that for AOT, it may be null,
875 // for example for methods whose declaring class could not be resolved
876 // (such as when the superclass could not be found).
877 ArtMethod* art_method_;
878
879 // The `ProfilingInfo` associated with the method being compiled.
880 ProfilingInfo* profiling_info_;
881
882 // How we are compiling the graph: either optimized, osr, or baseline.
883 // For osr, we will make all loops seen as irreducible and emit special
884 // stack maps to mark compiled code entries which the interpreter can
885 // directly jump to.
886 const CompilationKind compilation_kind_;
887
888 // List of methods that are assumed to have single implementation.
889 ArenaSet<ArtMethod*> cha_single_implementation_list_;
890
891 friend class SsaBuilder; // For caching constants.
892 friend class SsaLivenessAnalysis; // For the linear order.
893 friend class HInliner; // For the reverse post order.
894 ART_FRIEND_TEST(GraphTest, IfSuccessorSimpleJoinBlock1);
895 DISALLOW_COPY_AND_ASSIGN(HGraph);
896 };
897
898 class HLoopInformation : public ArenaObject<kArenaAllocLoopInfo> {
899 public:
HLoopInformation(HBasicBlock * header,HGraph * graph)900 HLoopInformation(HBasicBlock* header, HGraph* graph)
901 : header_(header),
902 suspend_check_(nullptr),
903 irreducible_(false),
904 contains_irreducible_loop_(false),
905 back_edges_(graph->GetAllocator()->Adapter(kArenaAllocLoopInfoBackEdges)),
906 // Make bit vector growable, as the number of blocks may change.
907 blocks_(graph->GetAllocator(),
908 graph->GetBlocks().size(),
909 true,
910 kArenaAllocLoopInfoBackEdges) {
911 back_edges_.reserve(kDefaultNumberOfBackEdges);
912 }
913
IsIrreducible()914 bool IsIrreducible() const { return irreducible_; }
ContainsIrreducibleLoop()915 bool ContainsIrreducibleLoop() const { return contains_irreducible_loop_; }
916
917 void Dump(std::ostream& os);
918
GetHeader()919 HBasicBlock* GetHeader() const {
920 return header_;
921 }
922
SetHeader(HBasicBlock * block)923 void SetHeader(HBasicBlock* block) {
924 header_ = block;
925 }
926
GetSuspendCheck()927 HSuspendCheck* GetSuspendCheck() const { return suspend_check_; }
SetSuspendCheck(HSuspendCheck * check)928 void SetSuspendCheck(HSuspendCheck* check) { suspend_check_ = check; }
HasSuspendCheck()929 bool HasSuspendCheck() const { return suspend_check_ != nullptr; }
930
AddBackEdge(HBasicBlock * back_edge)931 void AddBackEdge(HBasicBlock* back_edge) {
932 back_edges_.push_back(back_edge);
933 }
934
RemoveBackEdge(HBasicBlock * back_edge)935 void RemoveBackEdge(HBasicBlock* back_edge) {
936 RemoveElement(back_edges_, back_edge);
937 }
938
IsBackEdge(const HBasicBlock & block)939 bool IsBackEdge(const HBasicBlock& block) const {
940 return ContainsElement(back_edges_, &block);
941 }
942
NumberOfBackEdges()943 size_t NumberOfBackEdges() const {
944 return back_edges_.size();
945 }
946
947 HBasicBlock* GetPreHeader() const;
948
GetBackEdges()949 const ArenaVector<HBasicBlock*>& GetBackEdges() const {
950 return back_edges_;
951 }
952
953 // Returns the lifetime position of the back edge that has the
954 // greatest lifetime position.
955 size_t GetLifetimeEnd() const;
956
ReplaceBackEdge(HBasicBlock * existing,HBasicBlock * new_back_edge)957 void ReplaceBackEdge(HBasicBlock* existing, HBasicBlock* new_back_edge) {
958 ReplaceElement(back_edges_, existing, new_back_edge);
959 }
960
961 // Finds blocks that are part of this loop.
962 void Populate();
963
964 // Updates blocks population of the loop and all of its outer' ones recursively after the
965 // population of the inner loop is updated.
966 void PopulateInnerLoopUpwards(HLoopInformation* inner_loop);
967
968 // Returns whether this loop information contains `block`.
969 // Note that this loop information *must* be populated before entering this function.
970 bool Contains(const HBasicBlock& block) const;
971
972 // Returns whether this loop information is an inner loop of `other`.
973 // Note that `other` *must* be populated before entering this function.
974 bool IsIn(const HLoopInformation& other) const;
975
976 // Returns true if instruction is not defined within this loop.
977 bool IsDefinedOutOfTheLoop(HInstruction* instruction) const;
978
GetBlocks()979 const ArenaBitVector& GetBlocks() const { return blocks_; }
980
981 void Add(HBasicBlock* block);
982 void Remove(HBasicBlock* block);
983
ClearAllBlocks()984 void ClearAllBlocks() {
985 blocks_.ClearAllBits();
986 }
987
988 bool HasBackEdgeNotDominatedByHeader() const;
989
IsPopulated()990 bool IsPopulated() const {
991 return blocks_.GetHighestBitSet() != -1;
992 }
993
994 bool DominatesAllBackEdges(HBasicBlock* block);
995
996 bool HasExitEdge() const;
997
998 // Resets back edge and blocks-in-loop data.
ResetBasicBlockData()999 void ResetBasicBlockData() {
1000 back_edges_.clear();
1001 ClearAllBlocks();
1002 }
1003
1004 private:
1005 // Internal recursive implementation of `Populate`.
1006 void PopulateRecursive(HBasicBlock* block);
1007 void PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized);
1008
1009 HBasicBlock* header_;
1010 HSuspendCheck* suspend_check_;
1011 bool irreducible_;
1012 bool contains_irreducible_loop_;
1013 ArenaVector<HBasicBlock*> back_edges_;
1014 ArenaBitVector blocks_;
1015
1016 DISALLOW_COPY_AND_ASSIGN(HLoopInformation);
1017 };
1018
1019 // Stores try/catch information for basic blocks.
1020 // Note that HGraph is constructed so that catch blocks cannot simultaneously
1021 // be try blocks.
1022 class TryCatchInformation : public ArenaObject<kArenaAllocTryCatchInfo> {
1023 public:
1024 // Try block information constructor.
TryCatchInformation(const HTryBoundary & try_entry)1025 explicit TryCatchInformation(const HTryBoundary& try_entry)
1026 : try_entry_(&try_entry),
1027 catch_dex_file_(nullptr),
1028 catch_type_index_(dex::TypeIndex::Invalid()) {
1029 DCHECK(try_entry_ != nullptr);
1030 }
1031
1032 // Catch block information constructor.
TryCatchInformation(dex::TypeIndex catch_type_index,const DexFile & dex_file)1033 TryCatchInformation(dex::TypeIndex catch_type_index, const DexFile& dex_file)
1034 : try_entry_(nullptr),
1035 catch_dex_file_(&dex_file),
1036 catch_type_index_(catch_type_index) {}
1037
IsTryBlock()1038 bool IsTryBlock() const { return try_entry_ != nullptr; }
1039
GetTryEntry()1040 const HTryBoundary& GetTryEntry() const {
1041 DCHECK(IsTryBlock());
1042 return *try_entry_;
1043 }
1044
IsCatchBlock()1045 bool IsCatchBlock() const { return catch_dex_file_ != nullptr; }
1046
IsValidTypeIndex()1047 bool IsValidTypeIndex() const {
1048 DCHECK(IsCatchBlock());
1049 return catch_type_index_.IsValid();
1050 }
1051
GetCatchTypeIndex()1052 dex::TypeIndex GetCatchTypeIndex() const {
1053 DCHECK(IsCatchBlock());
1054 return catch_type_index_;
1055 }
1056
GetCatchDexFile()1057 const DexFile& GetCatchDexFile() const {
1058 DCHECK(IsCatchBlock());
1059 return *catch_dex_file_;
1060 }
1061
SetInvalidTypeIndex()1062 void SetInvalidTypeIndex() {
1063 catch_type_index_ = dex::TypeIndex::Invalid();
1064 }
1065
1066 private:
1067 // One of possibly several TryBoundary instructions entering the block's try.
1068 // Only set for try blocks.
1069 const HTryBoundary* try_entry_;
1070
1071 // Exception type information. Only set for catch blocks.
1072 const DexFile* catch_dex_file_;
1073 dex::TypeIndex catch_type_index_;
1074 };
1075
1076 static constexpr size_t kNoLifetime = -1;
1077 static constexpr uint32_t kInvalidBlockId = static_cast<uint32_t>(-1);
1078
1079 // A block in a method. Contains the list of instructions represented
1080 // as a double linked list. Each block knows its predecessors and
1081 // successors.
1082
1083 class HBasicBlock : public ArenaObject<kArenaAllocBasicBlock> {
1084 public:
1085 explicit HBasicBlock(HGraph* graph, uint32_t dex_pc = kNoDexPc)
graph_(graph)1086 : graph_(graph),
1087 predecessors_(graph->GetAllocator()->Adapter(kArenaAllocPredecessors)),
1088 successors_(graph->GetAllocator()->Adapter(kArenaAllocSuccessors)),
1089 loop_information_(nullptr),
1090 dominator_(nullptr),
1091 dominated_blocks_(graph->GetAllocator()->Adapter(kArenaAllocDominated)),
1092 block_id_(kInvalidBlockId),
1093 dex_pc_(dex_pc),
1094 lifetime_start_(kNoLifetime),
1095 lifetime_end_(kNoLifetime),
1096 try_catch_information_(nullptr) {
1097 predecessors_.reserve(kDefaultNumberOfPredecessors);
1098 successors_.reserve(kDefaultNumberOfSuccessors);
1099 dominated_blocks_.reserve(kDefaultNumberOfDominatedBlocks);
1100 }
1101
GetPredecessors()1102 const ArenaVector<HBasicBlock*>& GetPredecessors() const {
1103 return predecessors_;
1104 }
1105
GetNumberOfPredecessors()1106 size_t GetNumberOfPredecessors() const {
1107 return GetPredecessors().size();
1108 }
1109
GetSuccessors()1110 const ArenaVector<HBasicBlock*>& GetSuccessors() const {
1111 return successors_;
1112 }
1113
1114 ArrayRef<HBasicBlock* const> GetNormalSuccessors() const;
1115 ArrayRef<HBasicBlock* const> GetExceptionalSuccessors() const;
1116
1117 bool HasSuccessor(const HBasicBlock* block, size_t start_from = 0u) {
1118 return ContainsElement(successors_, block, start_from);
1119 }
1120
GetDominatedBlocks()1121 const ArenaVector<HBasicBlock*>& GetDominatedBlocks() const {
1122 return dominated_blocks_;
1123 }
1124
IsEntryBlock()1125 bool IsEntryBlock() const {
1126 return graph_->GetEntryBlock() == this;
1127 }
1128
IsExitBlock()1129 bool IsExitBlock() const {
1130 return graph_->GetExitBlock() == this;
1131 }
1132
1133 bool IsSingleGoto() const;
1134 bool IsSingleReturn() const;
1135 bool IsSingleReturnOrReturnVoidAllowingPhis() const;
1136 bool IsSingleTryBoundary() const;
1137
1138 // Returns true if this block emits nothing but a jump.
IsSingleJump()1139 bool IsSingleJump() const {
1140 HLoopInformation* loop_info = GetLoopInformation();
1141 return (IsSingleGoto() || IsSingleTryBoundary())
1142 // Back edges generate a suspend check.
1143 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
1144 }
1145
AddBackEdge(HBasicBlock * back_edge)1146 void AddBackEdge(HBasicBlock* back_edge) {
1147 if (loop_information_ == nullptr) {
1148 loop_information_ = new (graph_->GetAllocator()) HLoopInformation(this, graph_);
1149 }
1150 DCHECK_EQ(loop_information_->GetHeader(), this);
1151 loop_information_->AddBackEdge(back_edge);
1152 }
1153
1154 // Registers a back edge; if the block was not a loop header before the call associates a newly
1155 // created loop info with it.
1156 //
1157 // Used in SuperblockCloner to preserve LoopInformation object instead of reseting loop
1158 // info for all blocks during back edges recalculation.
AddBackEdgeWhileUpdating(HBasicBlock * back_edge)1159 void AddBackEdgeWhileUpdating(HBasicBlock* back_edge) {
1160 if (loop_information_ == nullptr || loop_information_->GetHeader() != this) {
1161 loop_information_ = new (graph_->GetAllocator()) HLoopInformation(this, graph_);
1162 }
1163 loop_information_->AddBackEdge(back_edge);
1164 }
1165
GetGraph()1166 HGraph* GetGraph() const { return graph_; }
SetGraph(HGraph * graph)1167 void SetGraph(HGraph* graph) { graph_ = graph; }
1168
GetBlockId()1169 uint32_t GetBlockId() const { return block_id_; }
SetBlockId(int id)1170 void SetBlockId(int id) { block_id_ = id; }
GetDexPc()1171 uint32_t GetDexPc() const { return dex_pc_; }
1172
GetDominator()1173 HBasicBlock* GetDominator() const { return dominator_; }
SetDominator(HBasicBlock * dominator)1174 void SetDominator(HBasicBlock* dominator) { dominator_ = dominator; }
AddDominatedBlock(HBasicBlock * block)1175 void AddDominatedBlock(HBasicBlock* block) { dominated_blocks_.push_back(block); }
1176
RemoveDominatedBlock(HBasicBlock * block)1177 void RemoveDominatedBlock(HBasicBlock* block) {
1178 RemoveElement(dominated_blocks_, block);
1179 }
1180
ReplaceDominatedBlock(HBasicBlock * existing,HBasicBlock * new_block)1181 void ReplaceDominatedBlock(HBasicBlock* existing, HBasicBlock* new_block) {
1182 ReplaceElement(dominated_blocks_, existing, new_block);
1183 }
1184
1185 void ClearDominanceInformation();
1186
NumberOfBackEdges()1187 int NumberOfBackEdges() const {
1188 return IsLoopHeader() ? loop_information_->NumberOfBackEdges() : 0;
1189 }
1190
GetFirstInstruction()1191 HInstruction* GetFirstInstruction() const { return instructions_.first_instruction_; }
GetLastInstruction()1192 HInstruction* GetLastInstruction() const { return instructions_.last_instruction_; }
GetInstructions()1193 const HInstructionList& GetInstructions() const { return instructions_; }
GetFirstPhi()1194 HInstruction* GetFirstPhi() const { return phis_.first_instruction_; }
GetLastPhi()1195 HInstruction* GetLastPhi() const { return phis_.last_instruction_; }
GetPhis()1196 const HInstructionList& GetPhis() const { return phis_; }
1197
1198 HInstruction* GetFirstInstructionDisregardMoves() const;
1199
AddSuccessor(HBasicBlock * block)1200 void AddSuccessor(HBasicBlock* block) {
1201 successors_.push_back(block);
1202 block->predecessors_.push_back(this);
1203 }
1204
ReplaceSuccessor(HBasicBlock * existing,HBasicBlock * new_block)1205 void ReplaceSuccessor(HBasicBlock* existing, HBasicBlock* new_block) {
1206 size_t successor_index = GetSuccessorIndexOf(existing);
1207 existing->RemovePredecessor(this);
1208 new_block->predecessors_.push_back(this);
1209 successors_[successor_index] = new_block;
1210 }
1211
ReplacePredecessor(HBasicBlock * existing,HBasicBlock * new_block)1212 void ReplacePredecessor(HBasicBlock* existing, HBasicBlock* new_block) {
1213 size_t predecessor_index = GetPredecessorIndexOf(existing);
1214 existing->RemoveSuccessor(this);
1215 new_block->successors_.push_back(this);
1216 predecessors_[predecessor_index] = new_block;
1217 }
1218
1219 // Insert `this` between `predecessor` and `successor. This method
1220 // preserves the indices, and will update the first edge found between
1221 // `predecessor` and `successor`.
InsertBetween(HBasicBlock * predecessor,HBasicBlock * successor)1222 void InsertBetween(HBasicBlock* predecessor, HBasicBlock* successor) {
1223 size_t predecessor_index = successor->GetPredecessorIndexOf(predecessor);
1224 size_t successor_index = predecessor->GetSuccessorIndexOf(successor);
1225 successor->predecessors_[predecessor_index] = this;
1226 predecessor->successors_[successor_index] = this;
1227 successors_.push_back(successor);
1228 predecessors_.push_back(predecessor);
1229 }
1230
RemovePredecessor(HBasicBlock * block)1231 void RemovePredecessor(HBasicBlock* block) {
1232 predecessors_.erase(predecessors_.begin() + GetPredecessorIndexOf(block));
1233 }
1234
RemoveSuccessor(HBasicBlock * block)1235 void RemoveSuccessor(HBasicBlock* block) {
1236 successors_.erase(successors_.begin() + GetSuccessorIndexOf(block));
1237 }
1238
ClearAllPredecessors()1239 void ClearAllPredecessors() {
1240 predecessors_.clear();
1241 }
1242
AddPredecessor(HBasicBlock * block)1243 void AddPredecessor(HBasicBlock* block) {
1244 predecessors_.push_back(block);
1245 block->successors_.push_back(this);
1246 }
1247
SwapPredecessors()1248 void SwapPredecessors() {
1249 DCHECK_EQ(predecessors_.size(), 2u);
1250 std::swap(predecessors_[0], predecessors_[1]);
1251 }
1252
SwapSuccessors()1253 void SwapSuccessors() {
1254 DCHECK_EQ(successors_.size(), 2u);
1255 std::swap(successors_[0], successors_[1]);
1256 }
1257
GetPredecessorIndexOf(HBasicBlock * predecessor)1258 size_t GetPredecessorIndexOf(HBasicBlock* predecessor) const {
1259 return IndexOfElement(predecessors_, predecessor);
1260 }
1261
GetSuccessorIndexOf(HBasicBlock * successor)1262 size_t GetSuccessorIndexOf(HBasicBlock* successor) const {
1263 return IndexOfElement(successors_, successor);
1264 }
1265
GetSinglePredecessor()1266 HBasicBlock* GetSinglePredecessor() const {
1267 DCHECK_EQ(GetPredecessors().size(), 1u);
1268 return GetPredecessors()[0];
1269 }
1270
GetSingleSuccessor()1271 HBasicBlock* GetSingleSuccessor() const {
1272 DCHECK_EQ(GetSuccessors().size(), 1u);
1273 return GetSuccessors()[0];
1274 }
1275
1276 // Returns whether the first occurrence of `predecessor` in the list of
1277 // predecessors is at index `idx`.
IsFirstIndexOfPredecessor(HBasicBlock * predecessor,size_t idx)1278 bool IsFirstIndexOfPredecessor(HBasicBlock* predecessor, size_t idx) const {
1279 DCHECK_EQ(GetPredecessors()[idx], predecessor);
1280 return GetPredecessorIndexOf(predecessor) == idx;
1281 }
1282
1283 // Create a new block between this block and its predecessors. The new block
1284 // is added to the graph, all predecessor edges are relinked to it and an edge
1285 // is created to `this`. Returns the new empty block. Reverse post order or
1286 // loop and try/catch information are not updated.
1287 HBasicBlock* CreateImmediateDominator();
1288
1289 // Split the block into two blocks just before `cursor`. Returns the newly
1290 // created, latter block. Note that this method will add the block to the
1291 // graph, create a Goto at the end of the former block and will create an edge
1292 // between the blocks. It will not, however, update the reverse post order or
1293 // loop and try/catch information.
1294 HBasicBlock* SplitBefore(HInstruction* cursor);
1295
1296 // Split the block into two blocks just before `cursor`. Returns the newly
1297 // created block. Note that this method just updates raw block information,
1298 // like predecessors, successors, dominators, and instruction list. It does not
1299 // update the graph, reverse post order, loop information, nor make sure the
1300 // blocks are consistent (for example ending with a control flow instruction).
1301 HBasicBlock* SplitBeforeForInlining(HInstruction* cursor);
1302
1303 // Similar to `SplitBeforeForInlining` but does it after `cursor`.
1304 HBasicBlock* SplitAfterForInlining(HInstruction* cursor);
1305
1306 // Merge `other` at the end of `this`. Successors and dominated blocks of
1307 // `other` are changed to be successors and dominated blocks of `this`. Note
1308 // that this method does not update the graph, reverse post order, loop
1309 // information, nor make sure the blocks are consistent (for example ending
1310 // with a control flow instruction).
1311 void MergeWithInlined(HBasicBlock* other);
1312
1313 // Replace `this` with `other`. Predecessors, successors, and dominated blocks
1314 // of `this` are moved to `other`.
1315 // Note that this method does not update the graph, reverse post order, loop
1316 // information, nor make sure the blocks are consistent (for example ending
1317 // with a control flow instruction).
1318 void ReplaceWith(HBasicBlock* other);
1319
1320 // Merges the instructions of `other` at the end of `this`.
1321 void MergeInstructionsWith(HBasicBlock* other);
1322
1323 // Merge `other` at the end of `this`. This method updates loops, reverse post
1324 // order, links to predecessors, successors, dominators and deletes the block
1325 // from the graph. The two blocks must be successive, i.e. `this` the only
1326 // predecessor of `other` and vice versa.
1327 void MergeWith(HBasicBlock* other);
1328
1329 // Disconnects `this` from all its predecessors, successors and dominator,
1330 // removes it from all loops it is included in and eventually from the graph.
1331 // The block must not dominate any other block. Predecessors and successors
1332 // are safely updated.
1333 void DisconnectAndDelete();
1334
1335 void AddInstruction(HInstruction* instruction);
1336 // Insert `instruction` before/after an existing instruction `cursor`.
1337 void InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor);
1338 void InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor);
1339 // Replace phi `initial` with `replacement` within this block.
1340 void ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement);
1341 // Replace instruction `initial` with `replacement` within this block.
1342 void ReplaceAndRemoveInstructionWith(HInstruction* initial,
1343 HInstruction* replacement);
1344 void AddPhi(HPhi* phi);
1345 void InsertPhiAfter(HPhi* instruction, HPhi* cursor);
1346 // RemoveInstruction and RemovePhi delete a given instruction from the respective
1347 // instruction list. With 'ensure_safety' set to true, it verifies that the
1348 // instruction is not in use and removes it from the use lists of its inputs.
1349 void RemoveInstruction(HInstruction* instruction, bool ensure_safety = true);
1350 void RemovePhi(HPhi* phi, bool ensure_safety = true);
1351 void RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety = true);
1352
IsLoopHeader()1353 bool IsLoopHeader() const {
1354 return IsInLoop() && (loop_information_->GetHeader() == this);
1355 }
1356
IsLoopPreHeaderFirstPredecessor()1357 bool IsLoopPreHeaderFirstPredecessor() const {
1358 DCHECK(IsLoopHeader());
1359 return GetPredecessors()[0] == GetLoopInformation()->GetPreHeader();
1360 }
1361
IsFirstPredecessorBackEdge()1362 bool IsFirstPredecessorBackEdge() const {
1363 DCHECK(IsLoopHeader());
1364 return GetLoopInformation()->IsBackEdge(*GetPredecessors()[0]);
1365 }
1366
GetLoopInformation()1367 HLoopInformation* GetLoopInformation() const {
1368 return loop_information_;
1369 }
1370
1371 // Set the loop_information_ on this block. Overrides the current
1372 // loop_information if it is an outer loop of the passed loop information.
1373 // Note that this method is called while creating the loop information.
SetInLoop(HLoopInformation * info)1374 void SetInLoop(HLoopInformation* info) {
1375 if (IsLoopHeader()) {
1376 // Nothing to do. This just means `info` is an outer loop.
1377 } else if (!IsInLoop()) {
1378 loop_information_ = info;
1379 } else if (loop_information_->Contains(*info->GetHeader())) {
1380 // Block is currently part of an outer loop. Make it part of this inner loop.
1381 // Note that a non loop header having a loop information means this loop information
1382 // has already been populated
1383 loop_information_ = info;
1384 } else {
1385 // Block is part of an inner loop. Do not update the loop information.
1386 // Note that we cannot do the check `info->Contains(loop_information_)->GetHeader()`
1387 // at this point, because this method is being called while populating `info`.
1388 }
1389 }
1390
1391 // Raw update of the loop information.
SetLoopInformation(HLoopInformation * info)1392 void SetLoopInformation(HLoopInformation* info) {
1393 loop_information_ = info;
1394 }
1395
IsInLoop()1396 bool IsInLoop() const { return loop_information_ != nullptr; }
1397
GetTryCatchInformation()1398 TryCatchInformation* GetTryCatchInformation() const { return try_catch_information_; }
1399
SetTryCatchInformation(TryCatchInformation * try_catch_information)1400 void SetTryCatchInformation(TryCatchInformation* try_catch_information) {
1401 try_catch_information_ = try_catch_information;
1402 }
1403
IsTryBlock()1404 bool IsTryBlock() const {
1405 return try_catch_information_ != nullptr && try_catch_information_->IsTryBlock();
1406 }
1407
IsCatchBlock()1408 bool IsCatchBlock() const {
1409 return try_catch_information_ != nullptr && try_catch_information_->IsCatchBlock();
1410 }
1411
1412 // Returns the try entry that this block's successors should have. They will
1413 // be in the same try, unless the block ends in a try boundary. In that case,
1414 // the appropriate try entry will be returned.
1415 const HTryBoundary* ComputeTryEntryOfSuccessors() const;
1416
1417 bool HasThrowingInstructions() const;
1418
1419 // Returns whether this block dominates the blocked passed as parameter.
1420 bool Dominates(const HBasicBlock* block) const;
1421
GetLifetimeStart()1422 size_t GetLifetimeStart() const { return lifetime_start_; }
GetLifetimeEnd()1423 size_t GetLifetimeEnd() const { return lifetime_end_; }
1424
SetLifetimeStart(size_t start)1425 void SetLifetimeStart(size_t start) { lifetime_start_ = start; }
SetLifetimeEnd(size_t end)1426 void SetLifetimeEnd(size_t end) { lifetime_end_ = end; }
1427
1428 bool EndsWithControlFlowInstruction() const;
1429 bool EndsWithReturn() const;
1430 bool EndsWithIf() const;
1431 bool EndsWithTryBoundary() const;
1432 bool HasSinglePhi() const;
1433
1434 private:
1435 HGraph* graph_;
1436 ArenaVector<HBasicBlock*> predecessors_;
1437 ArenaVector<HBasicBlock*> successors_;
1438 HInstructionList instructions_;
1439 HInstructionList phis_;
1440 HLoopInformation* loop_information_;
1441 HBasicBlock* dominator_;
1442 ArenaVector<HBasicBlock*> dominated_blocks_;
1443 uint32_t block_id_;
1444 // The dex program counter of the first instruction of this block.
1445 const uint32_t dex_pc_;
1446 size_t lifetime_start_;
1447 size_t lifetime_end_;
1448 TryCatchInformation* try_catch_information_;
1449
1450 friend class HGraph;
1451 friend class HInstruction;
1452 // Allow manual control of the ordering of predecessors/successors
1453 friend class OptimizingUnitTestHelper;
1454
1455 DISALLOW_COPY_AND_ASSIGN(HBasicBlock);
1456 };
1457
1458 // Iterates over the LoopInformation of all loops which contain 'block'
1459 // from the innermost to the outermost.
1460 class HLoopInformationOutwardIterator : public ValueObject {
1461 public:
HLoopInformationOutwardIterator(const HBasicBlock & block)1462 explicit HLoopInformationOutwardIterator(const HBasicBlock& block)
1463 : current_(block.GetLoopInformation()) {}
1464
Done()1465 bool Done() const { return current_ == nullptr; }
1466
Advance()1467 void Advance() {
1468 DCHECK(!Done());
1469 current_ = current_->GetPreHeader()->GetLoopInformation();
1470 }
1471
Current()1472 HLoopInformation* Current() const {
1473 DCHECK(!Done());
1474 return current_;
1475 }
1476
1477 private:
1478 HLoopInformation* current_;
1479
1480 DISALLOW_COPY_AND_ASSIGN(HLoopInformationOutwardIterator);
1481 };
1482
1483 #define FOR_EACH_CONCRETE_INSTRUCTION_SCALAR_COMMON(M) \
1484 M(Above, Condition) \
1485 M(AboveOrEqual, Condition) \
1486 M(Abs, UnaryOperation) \
1487 M(Add, BinaryOperation) \
1488 M(And, BinaryOperation) \
1489 M(ArrayGet, Instruction) \
1490 M(ArrayLength, Instruction) \
1491 M(ArraySet, Instruction) \
1492 M(Below, Condition) \
1493 M(BelowOrEqual, Condition) \
1494 M(BooleanNot, UnaryOperation) \
1495 M(BoundsCheck, Instruction) \
1496 M(BoundType, Instruction) \
1497 M(CheckCast, Instruction) \
1498 M(ClassTableGet, Instruction) \
1499 M(ClearException, Instruction) \
1500 M(ClinitCheck, Instruction) \
1501 M(Compare, BinaryOperation) \
1502 M(ConstructorFence, Instruction) \
1503 M(CurrentMethod, Instruction) \
1504 M(ShouldDeoptimizeFlag, Instruction) \
1505 M(Deoptimize, Instruction) \
1506 M(Div, BinaryOperation) \
1507 M(DivZeroCheck, Instruction) \
1508 M(DoubleConstant, Constant) \
1509 M(Equal, Condition) \
1510 M(Exit, Instruction) \
1511 M(FloatConstant, Constant) \
1512 M(Goto, Instruction) \
1513 M(GreaterThan, Condition) \
1514 M(GreaterThanOrEqual, Condition) \
1515 M(If, Instruction) \
1516 M(InstanceFieldGet, Instruction) \
1517 M(InstanceFieldSet, Instruction) \
1518 M(PredicatedInstanceFieldGet, Instruction) \
1519 M(InstanceOf, Instruction) \
1520 M(IntConstant, Constant) \
1521 M(IntermediateAddress, Instruction) \
1522 M(InvokeUnresolved, Invoke) \
1523 M(InvokeInterface, Invoke) \
1524 M(InvokeStaticOrDirect, Invoke) \
1525 M(InvokeVirtual, Invoke) \
1526 M(InvokePolymorphic, Invoke) \
1527 M(InvokeCustom, Invoke) \
1528 M(LessThan, Condition) \
1529 M(LessThanOrEqual, Condition) \
1530 M(LoadClass, Instruction) \
1531 M(LoadException, Instruction) \
1532 M(LoadMethodHandle, Instruction) \
1533 M(LoadMethodType, Instruction) \
1534 M(LoadString, Instruction) \
1535 M(LongConstant, Constant) \
1536 M(Max, Instruction) \
1537 M(MemoryBarrier, Instruction) \
1538 M(MethodEntryHook, Instruction) \
1539 M(MethodExitHook, Instruction) \
1540 M(Min, BinaryOperation) \
1541 M(MonitorOperation, Instruction) \
1542 M(Mul, BinaryOperation) \
1543 M(NativeDebugInfo, Instruction) \
1544 M(Neg, UnaryOperation) \
1545 M(NewArray, Instruction) \
1546 M(NewInstance, Instruction) \
1547 M(Not, UnaryOperation) \
1548 M(NotEqual, Condition) \
1549 M(NullConstant, Instruction) \
1550 M(NullCheck, Instruction) \
1551 M(Or, BinaryOperation) \
1552 M(PackedSwitch, Instruction) \
1553 M(ParallelMove, Instruction) \
1554 M(ParameterValue, Instruction) \
1555 M(Phi, Instruction) \
1556 M(Rem, BinaryOperation) \
1557 M(Return, Instruction) \
1558 M(ReturnVoid, Instruction) \
1559 M(Ror, BinaryOperation) \
1560 M(Shl, BinaryOperation) \
1561 M(Shr, BinaryOperation) \
1562 M(StaticFieldGet, Instruction) \
1563 M(StaticFieldSet, Instruction) \
1564 M(StringBuilderAppend, Instruction) \
1565 M(UnresolvedInstanceFieldGet, Instruction) \
1566 M(UnresolvedInstanceFieldSet, Instruction) \
1567 M(UnresolvedStaticFieldGet, Instruction) \
1568 M(UnresolvedStaticFieldSet, Instruction) \
1569 M(Select, Instruction) \
1570 M(Sub, BinaryOperation) \
1571 M(SuspendCheck, Instruction) \
1572 M(Throw, Instruction) \
1573 M(TryBoundary, Instruction) \
1574 M(TypeConversion, Instruction) \
1575 M(UShr, BinaryOperation) \
1576 M(Xor, BinaryOperation)
1577
1578 #define FOR_EACH_CONCRETE_INSTRUCTION_VECTOR_COMMON(M) \
1579 M(VecReplicateScalar, VecUnaryOperation) \
1580 M(VecExtractScalar, VecUnaryOperation) \
1581 M(VecReduce, VecUnaryOperation) \
1582 M(VecCnv, VecUnaryOperation) \
1583 M(VecNeg, VecUnaryOperation) \
1584 M(VecAbs, VecUnaryOperation) \
1585 M(VecNot, VecUnaryOperation) \
1586 M(VecAdd, VecBinaryOperation) \
1587 M(VecHalvingAdd, VecBinaryOperation) \
1588 M(VecSub, VecBinaryOperation) \
1589 M(VecMul, VecBinaryOperation) \
1590 M(VecDiv, VecBinaryOperation) \
1591 M(VecMin, VecBinaryOperation) \
1592 M(VecMax, VecBinaryOperation) \
1593 M(VecAnd, VecBinaryOperation) \
1594 M(VecAndNot, VecBinaryOperation) \
1595 M(VecOr, VecBinaryOperation) \
1596 M(VecXor, VecBinaryOperation) \
1597 M(VecSaturationAdd, VecBinaryOperation) \
1598 M(VecSaturationSub, VecBinaryOperation) \
1599 M(VecShl, VecBinaryOperation) \
1600 M(VecShr, VecBinaryOperation) \
1601 M(VecUShr, VecBinaryOperation) \
1602 M(VecSetScalars, VecOperation) \
1603 M(VecMultiplyAccumulate, VecOperation) \
1604 M(VecSADAccumulate, VecOperation) \
1605 M(VecDotProd, VecOperation) \
1606 M(VecLoad, VecMemoryOperation) \
1607 M(VecStore, VecMemoryOperation) \
1608 M(VecPredSetAll, VecPredSetOperation) \
1609 M(VecPredWhile, VecPredSetOperation) \
1610 M(VecPredCondition, VecOperation) \
1611
1612 #define FOR_EACH_CONCRETE_INSTRUCTION_COMMON(M) \
1613 FOR_EACH_CONCRETE_INSTRUCTION_SCALAR_COMMON(M) \
1614 FOR_EACH_CONCRETE_INSTRUCTION_VECTOR_COMMON(M)
1615
1616 /*
1617 * Instructions, shared across several (not all) architectures.
1618 */
1619 #if !defined(ART_ENABLE_CODEGEN_arm) && !defined(ART_ENABLE_CODEGEN_arm64)
1620 #define FOR_EACH_CONCRETE_INSTRUCTION_SHARED(M)
1621 #else
1622 #define FOR_EACH_CONCRETE_INSTRUCTION_SHARED(M) \
1623 M(BitwiseNegatedRight, Instruction) \
1624 M(DataProcWithShifterOp, Instruction) \
1625 M(MultiplyAccumulate, Instruction) \
1626 M(IntermediateAddressIndex, Instruction)
1627 #endif
1628
1629 #define FOR_EACH_CONCRETE_INSTRUCTION_ARM(M)
1630
1631 #define FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M)
1632
1633 #ifndef ART_ENABLE_CODEGEN_x86
1634 #define FOR_EACH_CONCRETE_INSTRUCTION_X86(M)
1635 #else
1636 #define FOR_EACH_CONCRETE_INSTRUCTION_X86(M) \
1637 M(X86ComputeBaseMethodAddress, Instruction) \
1638 M(X86LoadFromConstantTable, Instruction) \
1639 M(X86FPNeg, Instruction) \
1640 M(X86PackedSwitch, Instruction)
1641 #endif
1642
1643 #if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
1644 #define FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(M) \
1645 M(X86AndNot, Instruction) \
1646 M(X86MaskOrResetLeastSetBit, Instruction)
1647 #else
1648 #define FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(M)
1649 #endif
1650
1651 #define FOR_EACH_CONCRETE_INSTRUCTION_X86_64(M)
1652
1653 #define FOR_EACH_CONCRETE_INSTRUCTION(M) \
1654 FOR_EACH_CONCRETE_INSTRUCTION_COMMON(M) \
1655 FOR_EACH_CONCRETE_INSTRUCTION_SHARED(M) \
1656 FOR_EACH_CONCRETE_INSTRUCTION_ARM(M) \
1657 FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M) \
1658 FOR_EACH_CONCRETE_INSTRUCTION_X86(M) \
1659 FOR_EACH_CONCRETE_INSTRUCTION_X86_64(M) \
1660 FOR_EACH_CONCRETE_INSTRUCTION_X86_COMMON(M)
1661
1662 #define FOR_EACH_ABSTRACT_INSTRUCTION(M) \
1663 M(Condition, BinaryOperation) \
1664 M(Constant, Instruction) \
1665 M(UnaryOperation, Instruction) \
1666 M(BinaryOperation, Instruction) \
1667 M(Invoke, Instruction) \
1668 M(VecOperation, Instruction) \
1669 M(VecUnaryOperation, VecOperation) \
1670 M(VecBinaryOperation, VecOperation) \
1671 M(VecMemoryOperation, VecOperation) \
1672 M(VecPredSetOperation, VecOperation)
1673
1674 #define FOR_EACH_INSTRUCTION(M) \
1675 FOR_EACH_CONCRETE_INSTRUCTION(M) \
1676 FOR_EACH_ABSTRACT_INSTRUCTION(M)
1677
1678 #define FORWARD_DECLARATION(type, super) class H##type;
FOR_EACH_INSTRUCTION(FORWARD_DECLARATION)1679 FOR_EACH_INSTRUCTION(FORWARD_DECLARATION)
1680 #undef FORWARD_DECLARATION
1681
1682 #define DECLARE_INSTRUCTION(type) \
1683 private: \
1684 H##type& operator=(const H##type&) = delete; \
1685 public: \
1686 const char* DebugName() const override { return #type; } \
1687 HInstruction* Clone(ArenaAllocator* arena) const override { \
1688 DCHECK(IsClonable()); \
1689 return new (arena) H##type(*this->As##type()); \
1690 } \
1691 void Accept(HGraphVisitor* visitor) override
1692
1693 #define DECLARE_ABSTRACT_INSTRUCTION(type) \
1694 private: \
1695 H##type& operator=(const H##type&) = delete; \
1696 public:
1697
1698 #define DEFAULT_COPY_CONSTRUCTOR(type) H##type(const H##type& other) = default;
1699
1700 template <typename T>
1701 class HUseListNode : public ArenaObject<kArenaAllocUseListNode>,
1702 public IntrusiveForwardListNode<HUseListNode<T>> {
1703 public:
1704 // Get the instruction which has this use as one of the inputs.
1705 T GetUser() const { return user_; }
1706 // Get the position of the input record that this use corresponds to.
1707 size_t GetIndex() const { return index_; }
1708 // Set the position of the input record that this use corresponds to.
1709 void SetIndex(size_t index) { index_ = index; }
1710
1711 private:
1712 HUseListNode(T user, size_t index)
1713 : user_(user), index_(index) {}
1714
1715 T const user_;
1716 size_t index_;
1717
1718 friend class HInstruction;
1719
1720 DISALLOW_COPY_AND_ASSIGN(HUseListNode);
1721 };
1722
1723 template <typename T>
1724 using HUseList = IntrusiveForwardList<HUseListNode<T>>;
1725
1726 // This class is used by HEnvironment and HInstruction classes to record the
1727 // instructions they use and pointers to the corresponding HUseListNodes kept
1728 // by the used instructions.
1729 template <typename T>
1730 class HUserRecord : public ValueObject {
1731 public:
HUserRecord()1732 HUserRecord() : instruction_(nullptr), before_use_node_() {}
HUserRecord(HInstruction * instruction)1733 explicit HUserRecord(HInstruction* instruction) : instruction_(instruction), before_use_node_() {}
1734
HUserRecord(const HUserRecord<T> & old_record,typename HUseList<T>::iterator before_use_node)1735 HUserRecord(const HUserRecord<T>& old_record, typename HUseList<T>::iterator before_use_node)
1736 : HUserRecord(old_record.instruction_, before_use_node) {}
HUserRecord(HInstruction * instruction,typename HUseList<T>::iterator before_use_node)1737 HUserRecord(HInstruction* instruction, typename HUseList<T>::iterator before_use_node)
1738 : instruction_(instruction), before_use_node_(before_use_node) {
1739 DCHECK(instruction_ != nullptr);
1740 }
1741
GetInstruction()1742 HInstruction* GetInstruction() const { return instruction_; }
GetBeforeUseNode()1743 typename HUseList<T>::iterator GetBeforeUseNode() const { return before_use_node_; }
GetUseNode()1744 typename HUseList<T>::iterator GetUseNode() const { return ++GetBeforeUseNode(); }
1745
1746 private:
1747 // Instruction used by the user.
1748 HInstruction* instruction_;
1749
1750 // Iterator before the corresponding entry in the use list kept by 'instruction_'.
1751 typename HUseList<T>::iterator before_use_node_;
1752 };
1753
1754 // Helper class that extracts the input instruction from HUserRecord<HInstruction*>.
1755 // This is used for HInstruction::GetInputs() to return a container wrapper providing
1756 // HInstruction* values even though the underlying container has HUserRecord<>s.
1757 struct HInputExtractor {
operatorHInputExtractor1758 HInstruction* operator()(HUserRecord<HInstruction*>& record) const {
1759 return record.GetInstruction();
1760 }
operatorHInputExtractor1761 const HInstruction* operator()(const HUserRecord<HInstruction*>& record) const {
1762 return record.GetInstruction();
1763 }
1764 };
1765
1766 using HInputsRef = TransformArrayRef<HUserRecord<HInstruction*>, HInputExtractor>;
1767 using HConstInputsRef = TransformArrayRef<const HUserRecord<HInstruction*>, HInputExtractor>;
1768
1769 /**
1770 * Side-effects representation.
1771 *
1772 * For write/read dependences on fields/arrays, the dependence analysis uses
1773 * type disambiguation (e.g. a float field write cannot modify the value of an
1774 * integer field read) and the access type (e.g. a reference array write cannot
1775 * modify the value of a reference field read [although it may modify the
1776 * reference fetch prior to reading the field, which is represented by its own
1777 * write/read dependence]). The analysis makes conservative points-to
1778 * assumptions on reference types (e.g. two same typed arrays are assumed to be
1779 * the same, and any reference read depends on any reference read without
1780 * further regard of its type).
1781 *
1782 * kDependsOnGCBit is defined in the following way: instructions with kDependsOnGCBit must not be
1783 * alive across the point where garbage collection might happen.
1784 *
1785 * Note: Instructions with kCanTriggerGCBit do not depend on each other.
1786 *
1787 * kCanTriggerGCBit must be used for instructions for which GC might happen on the path across
1788 * those instructions from the compiler perspective (between this instruction and the next one
1789 * in the IR).
1790 *
1791 * Note: Instructions which can cause GC only on a fatal slow path do not need
1792 * kCanTriggerGCBit as the execution never returns to the instruction next to the exceptional
1793 * one. However the execution may return to compiled code if there is a catch block in the
1794 * current method; for this purpose the TryBoundary exit instruction has kCanTriggerGCBit
1795 * set.
1796 *
1797 * The internal representation uses 38-bit and is described in the table below.
1798 * The first line indicates the side effect, and for field/array accesses the
1799 * second line indicates the type of the access (in the order of the
1800 * DataType::Type enum).
1801 * The two numbered lines below indicate the bit position in the bitfield (read
1802 * vertically).
1803 *
1804 * |Depends on GC|ARRAY-R |FIELD-R |Can trigger GC|ARRAY-W |FIELD-W |
1805 * +-------------+---------+---------+--------------+---------+---------+
1806 * | |DFJISCBZL|DFJISCBZL| |DFJISCBZL|DFJISCBZL|
1807 * | 3 |333333322|222222221| 1 |111111110|000000000|
1808 * | 7 |654321098|765432109| 8 |765432109|876543210|
1809 *
1810 * Note that, to ease the implementation, 'changes' bits are least significant
1811 * bits, while 'dependency' bits are most significant bits.
1812 */
1813 class SideEffects : public ValueObject {
1814 public:
SideEffects()1815 SideEffects() : flags_(0) {}
1816
None()1817 static SideEffects None() {
1818 return SideEffects(0);
1819 }
1820
All()1821 static SideEffects All() {
1822 return SideEffects(kAllChangeBits | kAllDependOnBits);
1823 }
1824
AllChanges()1825 static SideEffects AllChanges() {
1826 return SideEffects(kAllChangeBits);
1827 }
1828
AllDependencies()1829 static SideEffects AllDependencies() {
1830 return SideEffects(kAllDependOnBits);
1831 }
1832
AllExceptGCDependency()1833 static SideEffects AllExceptGCDependency() {
1834 return AllWritesAndReads().Union(SideEffects::CanTriggerGC());
1835 }
1836
AllWritesAndReads()1837 static SideEffects AllWritesAndReads() {
1838 return SideEffects(kAllWrites | kAllReads);
1839 }
1840
AllWrites()1841 static SideEffects AllWrites() {
1842 return SideEffects(kAllWrites);
1843 }
1844
AllReads()1845 static SideEffects AllReads() {
1846 return SideEffects(kAllReads);
1847 }
1848
FieldWriteOfType(DataType::Type type,bool is_volatile)1849 static SideEffects FieldWriteOfType(DataType::Type type, bool is_volatile) {
1850 return is_volatile
1851 ? AllWritesAndReads()
1852 : SideEffects(TypeFlag(type, kFieldWriteOffset));
1853 }
1854
ArrayWriteOfType(DataType::Type type)1855 static SideEffects ArrayWriteOfType(DataType::Type type) {
1856 return SideEffects(TypeFlag(type, kArrayWriteOffset));
1857 }
1858
FieldReadOfType(DataType::Type type,bool is_volatile)1859 static SideEffects FieldReadOfType(DataType::Type type, bool is_volatile) {
1860 return is_volatile
1861 ? AllWritesAndReads()
1862 : SideEffects(TypeFlag(type, kFieldReadOffset));
1863 }
1864
ArrayReadOfType(DataType::Type type)1865 static SideEffects ArrayReadOfType(DataType::Type type) {
1866 return SideEffects(TypeFlag(type, kArrayReadOffset));
1867 }
1868
1869 // Returns whether GC might happen across this instruction from the compiler perspective so
1870 // the next instruction in the IR would see that.
1871 //
1872 // See the SideEffect class comments.
CanTriggerGC()1873 static SideEffects CanTriggerGC() {
1874 return SideEffects(1ULL << kCanTriggerGCBit);
1875 }
1876
1877 // Returns whether the instruction must not be alive across a GC point.
1878 //
1879 // See the SideEffect class comments.
DependsOnGC()1880 static SideEffects DependsOnGC() {
1881 return SideEffects(1ULL << kDependsOnGCBit);
1882 }
1883
1884 // Combines the side-effects of this and the other.
Union(SideEffects other)1885 SideEffects Union(SideEffects other) const {
1886 return SideEffects(flags_ | other.flags_);
1887 }
1888
Exclusion(SideEffects other)1889 SideEffects Exclusion(SideEffects other) const {
1890 return SideEffects(flags_ & ~other.flags_);
1891 }
1892
Add(SideEffects other)1893 void Add(SideEffects other) {
1894 flags_ |= other.flags_;
1895 }
1896
Includes(SideEffects other)1897 bool Includes(SideEffects other) const {
1898 return (other.flags_ & flags_) == other.flags_;
1899 }
1900
HasSideEffects()1901 bool HasSideEffects() const {
1902 return (flags_ & kAllChangeBits);
1903 }
1904
HasDependencies()1905 bool HasDependencies() const {
1906 return (flags_ & kAllDependOnBits);
1907 }
1908
1909 // Returns true if there are no side effects or dependencies.
DoesNothing()1910 bool DoesNothing() const {
1911 return flags_ == 0;
1912 }
1913
1914 // Returns true if something is written.
DoesAnyWrite()1915 bool DoesAnyWrite() const {
1916 return (flags_ & kAllWrites);
1917 }
1918
1919 // Returns true if something is read.
DoesAnyRead()1920 bool DoesAnyRead() const {
1921 return (flags_ & kAllReads);
1922 }
1923
1924 // Returns true if potentially everything is written and read
1925 // (every type and every kind of access).
DoesAllReadWrite()1926 bool DoesAllReadWrite() const {
1927 return (flags_ & (kAllWrites | kAllReads)) == (kAllWrites | kAllReads);
1928 }
1929
DoesAll()1930 bool DoesAll() const {
1931 return flags_ == (kAllChangeBits | kAllDependOnBits);
1932 }
1933
1934 // Returns true if `this` may read something written by `other`.
MayDependOn(SideEffects other)1935 bool MayDependOn(SideEffects other) const {
1936 const uint64_t depends_on_flags = (flags_ & kAllDependOnBits) >> kChangeBits;
1937 return (other.flags_ & depends_on_flags);
1938 }
1939
1940 // Returns string representation of flags (for debugging only).
1941 // Format: |x|DFJISCBZL|DFJISCBZL|y|DFJISCBZL|DFJISCBZL|
ToString()1942 std::string ToString() const {
1943 std::string flags = "|";
1944 for (int s = kLastBit; s >= 0; s--) {
1945 bool current_bit_is_set = ((flags_ >> s) & 1) != 0;
1946 if ((s == kDependsOnGCBit) || (s == kCanTriggerGCBit)) {
1947 // This is a bit for the GC side effect.
1948 if (current_bit_is_set) {
1949 flags += "GC";
1950 }
1951 flags += "|";
1952 } else {
1953 // This is a bit for the array/field analysis.
1954 // The underscore character stands for the 'can trigger GC' bit.
1955 static const char *kDebug = "LZBCSIJFDLZBCSIJFD_LZBCSIJFDLZBCSIJFD";
1956 if (current_bit_is_set) {
1957 flags += kDebug[s];
1958 }
1959 if ((s == kFieldWriteOffset) || (s == kArrayWriteOffset) ||
1960 (s == kFieldReadOffset) || (s == kArrayReadOffset)) {
1961 flags += "|";
1962 }
1963 }
1964 }
1965 return flags;
1966 }
1967
Equals(const SideEffects & other)1968 bool Equals(const SideEffects& other) const { return flags_ == other.flags_; }
1969
1970 private:
1971 static constexpr int kFieldArrayAnalysisBits = 9;
1972
1973 static constexpr int kFieldWriteOffset = 0;
1974 static constexpr int kArrayWriteOffset = kFieldWriteOffset + kFieldArrayAnalysisBits;
1975 static constexpr int kLastBitForWrites = kArrayWriteOffset + kFieldArrayAnalysisBits - 1;
1976 static constexpr int kCanTriggerGCBit = kLastBitForWrites + 1;
1977
1978 static constexpr int kChangeBits = kCanTriggerGCBit + 1;
1979
1980 static constexpr int kFieldReadOffset = kCanTriggerGCBit + 1;
1981 static constexpr int kArrayReadOffset = kFieldReadOffset + kFieldArrayAnalysisBits;
1982 static constexpr int kLastBitForReads = kArrayReadOffset + kFieldArrayAnalysisBits - 1;
1983 static constexpr int kDependsOnGCBit = kLastBitForReads + 1;
1984
1985 static constexpr int kLastBit = kDependsOnGCBit;
1986 static constexpr int kDependOnBits = kLastBit + 1 - kChangeBits;
1987
1988 // Aliases.
1989
1990 static_assert(kChangeBits == kDependOnBits,
1991 "the 'change' bits should match the 'depend on' bits.");
1992
1993 static constexpr uint64_t kAllChangeBits = ((1ULL << kChangeBits) - 1);
1994 static constexpr uint64_t kAllDependOnBits = ((1ULL << kDependOnBits) - 1) << kChangeBits;
1995 static constexpr uint64_t kAllWrites =
1996 ((1ULL << (kLastBitForWrites + 1 - kFieldWriteOffset)) - 1) << kFieldWriteOffset;
1997 static constexpr uint64_t kAllReads =
1998 ((1ULL << (kLastBitForReads + 1 - kFieldReadOffset)) - 1) << kFieldReadOffset;
1999
2000 // Translates type to bit flag. The type must correspond to a Java type.
TypeFlag(DataType::Type type,int offset)2001 static uint64_t TypeFlag(DataType::Type type, int offset) {
2002 int shift;
2003 switch (type) {
2004 case DataType::Type::kReference: shift = 0; break;
2005 case DataType::Type::kBool: shift = 1; break;
2006 case DataType::Type::kInt8: shift = 2; break;
2007 case DataType::Type::kUint16: shift = 3; break;
2008 case DataType::Type::kInt16: shift = 4; break;
2009 case DataType::Type::kInt32: shift = 5; break;
2010 case DataType::Type::kInt64: shift = 6; break;
2011 case DataType::Type::kFloat32: shift = 7; break;
2012 case DataType::Type::kFloat64: shift = 8; break;
2013 default:
2014 LOG(FATAL) << "Unexpected data type " << type;
2015 UNREACHABLE();
2016 }
2017 DCHECK_LE(kFieldWriteOffset, shift);
2018 DCHECK_LT(shift, kArrayWriteOffset);
2019 return UINT64_C(1) << (shift + offset);
2020 }
2021
2022 // Private constructor on direct flags value.
SideEffects(uint64_t flags)2023 explicit SideEffects(uint64_t flags) : flags_(flags) {}
2024
2025 uint64_t flags_;
2026 };
2027
2028 // A HEnvironment object contains the values of virtual registers at a given location.
2029 class HEnvironment : public ArenaObject<kArenaAllocEnvironment> {
2030 public:
HEnvironment(ArenaAllocator * allocator,size_t number_of_vregs,ArtMethod * method,uint32_t dex_pc,HInstruction * holder)2031 ALWAYS_INLINE HEnvironment(ArenaAllocator* allocator,
2032 size_t number_of_vregs,
2033 ArtMethod* method,
2034 uint32_t dex_pc,
2035 HInstruction* holder)
2036 : vregs_(number_of_vregs, allocator->Adapter(kArenaAllocEnvironmentVRegs)),
2037 locations_(allocator->Adapter(kArenaAllocEnvironmentLocations)),
2038 parent_(nullptr),
2039 method_(method),
2040 dex_pc_(dex_pc),
2041 holder_(holder) {
2042 }
2043
HEnvironment(ArenaAllocator * allocator,const HEnvironment & to_copy,HInstruction * holder)2044 ALWAYS_INLINE HEnvironment(ArenaAllocator* allocator,
2045 const HEnvironment& to_copy,
2046 HInstruction* holder)
2047 : HEnvironment(allocator,
2048 to_copy.Size(),
2049 to_copy.GetMethod(),
2050 to_copy.GetDexPc(),
2051 holder) {}
2052
AllocateLocations()2053 void AllocateLocations() {
2054 DCHECK(locations_.empty());
2055 locations_.resize(vregs_.size());
2056 }
2057
SetAndCopyParentChain(ArenaAllocator * allocator,HEnvironment * parent)2058 void SetAndCopyParentChain(ArenaAllocator* allocator, HEnvironment* parent) {
2059 if (parent_ != nullptr) {
2060 parent_->SetAndCopyParentChain(allocator, parent);
2061 } else {
2062 parent_ = new (allocator) HEnvironment(allocator, *parent, holder_);
2063 parent_->CopyFrom(parent);
2064 if (parent->GetParent() != nullptr) {
2065 parent_->SetAndCopyParentChain(allocator, parent->GetParent());
2066 }
2067 }
2068 }
2069
2070 void CopyFrom(ArrayRef<HInstruction* const> locals);
2071 void CopyFrom(HEnvironment* environment);
2072
2073 // Copy from `env`. If it's a loop phi for `loop_header`, copy the first
2074 // input to the loop phi instead. This is for inserting instructions that
2075 // require an environment (like HDeoptimization) in the loop pre-header.
2076 void CopyFromWithLoopPhiAdjustment(HEnvironment* env, HBasicBlock* loop_header);
2077
SetRawEnvAt(size_t index,HInstruction * instruction)2078 void SetRawEnvAt(size_t index, HInstruction* instruction) {
2079 vregs_[index] = HUserRecord<HEnvironment*>(instruction);
2080 }
2081
GetInstructionAt(size_t index)2082 HInstruction* GetInstructionAt(size_t index) const {
2083 return vregs_[index].GetInstruction();
2084 }
2085
2086 void RemoveAsUserOfInput(size_t index) const;
2087
2088 // Replaces the input at the position 'index' with the replacement; the replacement and old
2089 // input instructions' env_uses_ lists are adjusted. The function works similar to
2090 // HInstruction::ReplaceInput.
2091 void ReplaceInput(HInstruction* replacement, size_t index);
2092
Size()2093 size_t Size() const { return vregs_.size(); }
2094
GetParent()2095 HEnvironment* GetParent() const { return parent_; }
2096
SetLocationAt(size_t index,Location location)2097 void SetLocationAt(size_t index, Location location) {
2098 locations_[index] = location;
2099 }
2100
GetLocationAt(size_t index)2101 Location GetLocationAt(size_t index) const {
2102 return locations_[index];
2103 }
2104
GetDexPc()2105 uint32_t GetDexPc() const {
2106 return dex_pc_;
2107 }
2108
GetMethod()2109 ArtMethod* GetMethod() const {
2110 return method_;
2111 }
2112
GetHolder()2113 HInstruction* GetHolder() const {
2114 return holder_;
2115 }
2116
2117
IsFromInlinedInvoke()2118 bool IsFromInlinedInvoke() const {
2119 return GetParent() != nullptr;
2120 }
2121
2122 class EnvInputSelector {
2123 public:
EnvInputSelector(const HEnvironment * e)2124 explicit EnvInputSelector(const HEnvironment* e) : env_(e) {}
operator()2125 HInstruction* operator()(size_t s) const {
2126 return env_->GetInstructionAt(s);
2127 }
2128 private:
2129 const HEnvironment* env_;
2130 };
2131
2132 using HConstEnvInputRef = TransformIterator<CountIter, EnvInputSelector>;
GetEnvInputs()2133 IterationRange<HConstEnvInputRef> GetEnvInputs() const {
2134 IterationRange<CountIter> range(Range(Size()));
2135 return MakeIterationRange(MakeTransformIterator(range.begin(), EnvInputSelector(this)),
2136 MakeTransformIterator(range.end(), EnvInputSelector(this)));
2137 }
2138
2139 private:
2140 ArenaVector<HUserRecord<HEnvironment*>> vregs_;
2141 ArenaVector<Location> locations_;
2142 HEnvironment* parent_;
2143 ArtMethod* method_;
2144 const uint32_t dex_pc_;
2145
2146 // The instruction that holds this environment.
2147 HInstruction* const holder_;
2148
2149 friend class HInstruction;
2150
2151 DISALLOW_COPY_AND_ASSIGN(HEnvironment);
2152 };
2153
2154 std::ostream& operator<<(std::ostream& os, const HInstruction& rhs);
2155
2156 // Iterates over the Environments
2157 class HEnvironmentIterator : public ValueObject,
2158 public std::iterator<std::forward_iterator_tag, HEnvironment*> {
2159 public:
HEnvironmentIterator(HEnvironment * cur)2160 explicit HEnvironmentIterator(HEnvironment* cur) : cur_(cur) {}
2161
2162 HEnvironment* operator*() const {
2163 return cur_;
2164 }
2165
2166 HEnvironmentIterator& operator++() {
2167 DCHECK(cur_ != nullptr);
2168 cur_ = cur_->GetParent();
2169 return *this;
2170 }
2171
2172 HEnvironmentIterator operator++(int) {
2173 HEnvironmentIterator prev(*this);
2174 ++(*this);
2175 return prev;
2176 }
2177
2178 bool operator==(const HEnvironmentIterator& other) const {
2179 return other.cur_ == cur_;
2180 }
2181
2182 bool operator!=(const HEnvironmentIterator& other) const {
2183 return !(*this == other);
2184 }
2185
2186 private:
2187 HEnvironment* cur_;
2188 };
2189
2190 class HInstruction : public ArenaObject<kArenaAllocInstruction> {
2191 public:
2192 #define DECLARE_KIND(type, super) k##type,
2193 enum InstructionKind { // private marker to avoid generate-operator-out.py from processing.
2194 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_KIND)
2195 kLastInstructionKind
2196 };
2197 #undef DECLARE_KIND
2198
HInstruction(InstructionKind kind,SideEffects side_effects,uint32_t dex_pc)2199 HInstruction(InstructionKind kind, SideEffects side_effects, uint32_t dex_pc)
2200 : HInstruction(kind, DataType::Type::kVoid, side_effects, dex_pc) {}
2201
HInstruction(InstructionKind kind,DataType::Type type,SideEffects side_effects,uint32_t dex_pc)2202 HInstruction(InstructionKind kind, DataType::Type type, SideEffects side_effects, uint32_t dex_pc)
2203 : previous_(nullptr),
2204 next_(nullptr),
2205 block_(nullptr),
2206 dex_pc_(dex_pc),
2207 id_(-1),
2208 ssa_index_(-1),
2209 packed_fields_(0u),
2210 environment_(nullptr),
2211 locations_(nullptr),
2212 live_interval_(nullptr),
2213 lifetime_position_(kNoLifetime),
2214 side_effects_(side_effects),
2215 reference_type_handle_(ReferenceTypeInfo::CreateInvalid().GetTypeHandle()) {
2216 SetPackedField<InstructionKindField>(kind);
2217 SetPackedField<TypeField>(type);
2218 SetPackedFlag<kFlagReferenceTypeIsExact>(ReferenceTypeInfo::CreateInvalid().IsExact());
2219 }
2220
~HInstruction()2221 virtual ~HInstruction() {}
2222
2223 std::ostream& Dump(std::ostream& os, bool dump_args = false);
2224
2225 // Helper for dumping without argument information using operator<<
2226 struct NoArgsDump {
2227 const HInstruction* ins;
2228 };
DumpWithoutArgs()2229 NoArgsDump DumpWithoutArgs() const {
2230 return NoArgsDump{this};
2231 }
2232 // Helper for dumping with argument information using operator<<
2233 struct ArgsDump {
2234 const HInstruction* ins;
2235 };
DumpWithArgs()2236 ArgsDump DumpWithArgs() const {
2237 return ArgsDump{this};
2238 }
2239
GetNext()2240 HInstruction* GetNext() const { return next_; }
GetPrevious()2241 HInstruction* GetPrevious() const { return previous_; }
2242
2243 HInstruction* GetNextDisregardingMoves() const;
2244 HInstruction* GetPreviousDisregardingMoves() const;
2245
GetBlock()2246 HBasicBlock* GetBlock() const { return block_; }
GetAllocator()2247 ArenaAllocator* GetAllocator() const { return block_->GetGraph()->GetAllocator(); }
SetBlock(HBasicBlock * block)2248 void SetBlock(HBasicBlock* block) { block_ = block; }
IsInBlock()2249 bool IsInBlock() const { return block_ != nullptr; }
IsInLoop()2250 bool IsInLoop() const { return block_->IsInLoop(); }
IsLoopHeaderPhi()2251 bool IsLoopHeaderPhi() const { return IsPhi() && block_->IsLoopHeader(); }
IsIrreducibleLoopHeaderPhi()2252 bool IsIrreducibleLoopHeaderPhi() const {
2253 return IsLoopHeaderPhi() && GetBlock()->GetLoopInformation()->IsIrreducible();
2254 }
2255
2256 virtual ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() = 0;
2257
GetInputRecords()2258 ArrayRef<const HUserRecord<HInstruction*>> GetInputRecords() const {
2259 // One virtual method is enough, just const_cast<> and then re-add the const.
2260 return ArrayRef<const HUserRecord<HInstruction*>>(
2261 const_cast<HInstruction*>(this)->GetInputRecords());
2262 }
2263
GetInputs()2264 HInputsRef GetInputs() {
2265 return MakeTransformArrayRef(GetInputRecords(), HInputExtractor());
2266 }
2267
GetInputs()2268 HConstInputsRef GetInputs() const {
2269 return MakeTransformArrayRef(GetInputRecords(), HInputExtractor());
2270 }
2271
InputCount()2272 size_t InputCount() const { return GetInputRecords().size(); }
InputAt(size_t i)2273 HInstruction* InputAt(size_t i) const { return InputRecordAt(i).GetInstruction(); }
2274
HasInput(HInstruction * input)2275 bool HasInput(HInstruction* input) const {
2276 for (const HInstruction* i : GetInputs()) {
2277 if (i == input) {
2278 return true;
2279 }
2280 }
2281 return false;
2282 }
2283
SetRawInputAt(size_t index,HInstruction * input)2284 void SetRawInputAt(size_t index, HInstruction* input) {
2285 SetRawInputRecordAt(index, HUserRecord<HInstruction*>(input));
2286 }
2287
2288 virtual void Accept(HGraphVisitor* visitor) = 0;
2289 virtual const char* DebugName() const = 0;
2290
GetType()2291 DataType::Type GetType() const {
2292 return TypeField::Decode(GetPackedFields());
2293 }
2294
NeedsEnvironment()2295 virtual bool NeedsEnvironment() const { return false; }
NeedsBss()2296 virtual bool NeedsBss() const {
2297 return false;
2298 }
2299
GetDexPc()2300 uint32_t GetDexPc() const { return dex_pc_; }
2301
IsControlFlow()2302 virtual bool IsControlFlow() const { return false; }
2303
2304 // Can the instruction throw?
2305 // TODO: We should rename to CanVisiblyThrow, as some instructions (like HNewInstance),
2306 // could throw OOME, but it is still OK to remove them if they are unused.
CanThrow()2307 virtual bool CanThrow() const { return false; }
2308
2309 // Does the instruction always throw an exception unconditionally?
AlwaysThrows()2310 virtual bool AlwaysThrows() const { return false; }
2311 // Will this instruction only cause async exceptions if it causes any at all?
OnlyThrowsAsyncExceptions()2312 virtual bool OnlyThrowsAsyncExceptions() const {
2313 return false;
2314 }
2315
CanThrowIntoCatchBlock()2316 bool CanThrowIntoCatchBlock() const { return CanThrow() && block_->IsTryBlock(); }
2317
HasSideEffects()2318 bool HasSideEffects() const { return side_effects_.HasSideEffects(); }
DoesAnyWrite()2319 bool DoesAnyWrite() const { return side_effects_.DoesAnyWrite(); }
2320
2321 // Does not apply for all instructions, but having this at top level greatly
2322 // simplifies the null check elimination.
2323 // TODO: Consider merging can_be_null into ReferenceTypeInfo.
CanBeNull()2324 virtual bool CanBeNull() const {
2325 DCHECK_EQ(GetType(), DataType::Type::kReference) << "CanBeNull only applies to reference types";
2326 return true;
2327 }
2328
CanDoImplicitNullCheckOn(HInstruction * obj ATTRIBUTE_UNUSED)2329 virtual bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const {
2330 return false;
2331 }
2332
2333 // If this instruction will do an implicit null check, return the `HNullCheck` associated
2334 // with it. Otherwise return null.
GetImplicitNullCheck()2335 HNullCheck* GetImplicitNullCheck() const {
2336 // Go over previous non-move instructions that are emitted at use site.
2337 HInstruction* prev_not_move = GetPreviousDisregardingMoves();
2338 while (prev_not_move != nullptr && prev_not_move->IsEmittedAtUseSite()) {
2339 if (prev_not_move->IsNullCheck()) {
2340 return prev_not_move->AsNullCheck();
2341 }
2342 prev_not_move = prev_not_move->GetPreviousDisregardingMoves();
2343 }
2344 return nullptr;
2345 }
2346
IsActualObject()2347 virtual bool IsActualObject() const {
2348 return GetType() == DataType::Type::kReference;
2349 }
2350
2351 void SetReferenceTypeInfo(ReferenceTypeInfo rti);
2352
GetReferenceTypeInfo()2353 ReferenceTypeInfo GetReferenceTypeInfo() const {
2354 DCHECK_EQ(GetType(), DataType::Type::kReference);
2355 return ReferenceTypeInfo::CreateUnchecked(reference_type_handle_,
2356 GetPackedFlag<kFlagReferenceTypeIsExact>());
2357 }
2358
AddUseAt(HInstruction * user,size_t index)2359 void AddUseAt(HInstruction* user, size_t index) {
2360 DCHECK(user != nullptr);
2361 // Note: fixup_end remains valid across push_front().
2362 auto fixup_end = uses_.empty() ? uses_.begin() : ++uses_.begin();
2363 ArenaAllocator* allocator = user->GetBlock()->GetGraph()->GetAllocator();
2364 HUseListNode<HInstruction*>* new_node =
2365 new (allocator) HUseListNode<HInstruction*>(user, index);
2366 uses_.push_front(*new_node);
2367 FixUpUserRecordsAfterUseInsertion(fixup_end);
2368 }
2369
AddEnvUseAt(HEnvironment * user,size_t index)2370 void AddEnvUseAt(HEnvironment* user, size_t index) {
2371 DCHECK(user != nullptr);
2372 // Note: env_fixup_end remains valid across push_front().
2373 auto env_fixup_end = env_uses_.empty() ? env_uses_.begin() : ++env_uses_.begin();
2374 HUseListNode<HEnvironment*>* new_node =
2375 new (GetBlock()->GetGraph()->GetAllocator()) HUseListNode<HEnvironment*>(user, index);
2376 env_uses_.push_front(*new_node);
2377 FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
2378 }
2379
RemoveAsUserOfInput(size_t input)2380 void RemoveAsUserOfInput(size_t input) {
2381 HUserRecord<HInstruction*> input_use = InputRecordAt(input);
2382 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
2383 input_use.GetInstruction()->uses_.erase_after(before_use_node);
2384 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
2385 }
2386
RemoveAsUserOfAllInputs()2387 void RemoveAsUserOfAllInputs() {
2388 for (const HUserRecord<HInstruction*>& input_use : GetInputRecords()) {
2389 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
2390 input_use.GetInstruction()->uses_.erase_after(before_use_node);
2391 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
2392 }
2393 }
2394
GetUses()2395 const HUseList<HInstruction*>& GetUses() const { return uses_; }
GetEnvUses()2396 const HUseList<HEnvironment*>& GetEnvUses() const { return env_uses_; }
2397
HasUses()2398 bool HasUses() const { return !uses_.empty() || !env_uses_.empty(); }
HasEnvironmentUses()2399 bool HasEnvironmentUses() const { return !env_uses_.empty(); }
HasNonEnvironmentUses()2400 bool HasNonEnvironmentUses() const { return !uses_.empty(); }
HasOnlyOneNonEnvironmentUse()2401 bool HasOnlyOneNonEnvironmentUse() const {
2402 return !HasEnvironmentUses() && GetUses().HasExactlyOneElement();
2403 }
2404
IsRemovable()2405 bool IsRemovable() const {
2406 return
2407 !DoesAnyWrite() &&
2408 !CanThrow() &&
2409 !IsSuspendCheck() &&
2410 !IsControlFlow() &&
2411 !IsNativeDebugInfo() &&
2412 !IsParameterValue() &&
2413 // If we added an explicit barrier then we should keep it.
2414 !IsMemoryBarrier() &&
2415 !IsConstructorFence();
2416 }
2417
IsDeadAndRemovable()2418 bool IsDeadAndRemovable() const {
2419 return IsRemovable() && !HasUses();
2420 }
2421
2422 // Does this instruction strictly dominate `other_instruction`?
2423 // Returns false if this instruction and `other_instruction` are the same.
2424 // Aborts if this instruction and `other_instruction` are both phis.
2425 bool StrictlyDominates(HInstruction* other_instruction) const;
2426
GetId()2427 int GetId() const { return id_; }
SetId(int id)2428 void SetId(int id) { id_ = id; }
2429
GetSsaIndex()2430 int GetSsaIndex() const { return ssa_index_; }
SetSsaIndex(int ssa_index)2431 void SetSsaIndex(int ssa_index) { ssa_index_ = ssa_index; }
HasSsaIndex()2432 bool HasSsaIndex() const { return ssa_index_ != -1; }
2433
HasEnvironment()2434 bool HasEnvironment() const { return environment_ != nullptr; }
GetEnvironment()2435 HEnvironment* GetEnvironment() const { return environment_; }
GetAllEnvironments()2436 IterationRange<HEnvironmentIterator> GetAllEnvironments() const {
2437 return MakeIterationRange(HEnvironmentIterator(GetEnvironment()),
2438 HEnvironmentIterator(nullptr));
2439 }
2440 // Set the `environment_` field. Raw because this method does not
2441 // update the uses lists.
SetRawEnvironment(HEnvironment * environment)2442 void SetRawEnvironment(HEnvironment* environment) {
2443 DCHECK(environment_ == nullptr);
2444 DCHECK_EQ(environment->GetHolder(), this);
2445 environment_ = environment;
2446 }
2447
InsertRawEnvironment(HEnvironment * environment)2448 void InsertRawEnvironment(HEnvironment* environment) {
2449 DCHECK(environment_ != nullptr);
2450 DCHECK_EQ(environment->GetHolder(), this);
2451 DCHECK(environment->GetParent() == nullptr);
2452 environment->parent_ = environment_;
2453 environment_ = environment;
2454 }
2455
2456 void RemoveEnvironment();
2457
2458 // Set the environment of this instruction, copying it from `environment`. While
2459 // copying, the uses lists are being updated.
CopyEnvironmentFrom(HEnvironment * environment)2460 void CopyEnvironmentFrom(HEnvironment* environment) {
2461 DCHECK(environment_ == nullptr);
2462 ArenaAllocator* allocator = GetBlock()->GetGraph()->GetAllocator();
2463 environment_ = new (allocator) HEnvironment(allocator, *environment, this);
2464 environment_->CopyFrom(environment);
2465 if (environment->GetParent() != nullptr) {
2466 environment_->SetAndCopyParentChain(allocator, environment->GetParent());
2467 }
2468 }
2469
CopyEnvironmentFromWithLoopPhiAdjustment(HEnvironment * environment,HBasicBlock * block)2470 void CopyEnvironmentFromWithLoopPhiAdjustment(HEnvironment* environment,
2471 HBasicBlock* block) {
2472 DCHECK(environment_ == nullptr);
2473 ArenaAllocator* allocator = GetBlock()->GetGraph()->GetAllocator();
2474 environment_ = new (allocator) HEnvironment(allocator, *environment, this);
2475 environment_->CopyFromWithLoopPhiAdjustment(environment, block);
2476 if (environment->GetParent() != nullptr) {
2477 environment_->SetAndCopyParentChain(allocator, environment->GetParent());
2478 }
2479 }
2480
2481 // Returns the number of entries in the environment. Typically, that is the
2482 // number of dex registers in a method. It could be more in case of inlining.
2483 size_t EnvironmentSize() const;
2484
GetLocations()2485 LocationSummary* GetLocations() const { return locations_; }
SetLocations(LocationSummary * locations)2486 void SetLocations(LocationSummary* locations) { locations_ = locations; }
2487
2488 void ReplaceWith(HInstruction* instruction);
2489 void ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement);
2490 void ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement);
2491 void ReplaceInput(HInstruction* replacement, size_t index);
2492
2493 // This is almost the same as doing `ReplaceWith()`. But in this helper, the
2494 // uses of this instruction by `other` are *not* updated.
ReplaceWithExceptInReplacementAtIndex(HInstruction * other,size_t use_index)2495 void ReplaceWithExceptInReplacementAtIndex(HInstruction* other, size_t use_index) {
2496 ReplaceWith(other);
2497 other->ReplaceInput(this, use_index);
2498 }
2499
2500 // Move `this` instruction before `cursor`
2501 void MoveBefore(HInstruction* cursor, bool do_checks = true);
2502
2503 // Move `this` before its first user and out of any loops. If there is no
2504 // out-of-loop user that dominates all other users, move the instruction
2505 // to the end of the out-of-loop common dominator of the user's blocks.
2506 //
2507 // This can be used only on non-throwing instructions with no side effects that
2508 // have at least one use but no environment uses.
2509 void MoveBeforeFirstUserAndOutOfLoops();
2510
2511 #define INSTRUCTION_TYPE_CHECK(type, super) \
2512 bool Is##type() const;
2513
2514 FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
2515 #undef INSTRUCTION_TYPE_CHECK
2516
2517 #define INSTRUCTION_TYPE_CAST(type, super) \
2518 const H##type* As##type() const; \
2519 H##type* As##type();
2520
FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CAST)2521 FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CAST)
2522 #undef INSTRUCTION_TYPE_CAST
2523
2524 // Return a clone of the instruction if it is clonable (shallow copy by default, custom copy
2525 // if a custom copy-constructor is provided for a particular type). If IsClonable() is false for
2526 // the instruction then the behaviour of this function is undefined.
2527 //
2528 // Note: It is semantically valid to create a clone of the instruction only until
2529 // prepare_for_register_allocator phase as lifetime, intervals and codegen info are not
2530 // copied.
2531 //
2532 // Note: HEnvironment and some other fields are not copied and are set to default values, see
2533 // 'explicit HInstruction(const HInstruction& other)' for details.
2534 virtual HInstruction* Clone(ArenaAllocator* arena ATTRIBUTE_UNUSED) const {
2535 LOG(FATAL) << "Cloning is not implemented for the instruction " <<
2536 DebugName() << " " << GetId();
2537 UNREACHABLE();
2538 }
2539
IsFieldAccess()2540 virtual bool IsFieldAccess() const {
2541 return false;
2542 }
2543
GetFieldInfo()2544 virtual const FieldInfo& GetFieldInfo() const {
2545 CHECK(IsFieldAccess()) << "Only callable on field accessors not " << DebugName() << " "
2546 << *this;
2547 LOG(FATAL) << "Must be overridden by field accessors. Not implemented by " << *this;
2548 UNREACHABLE();
2549 }
2550
2551 // Return whether instruction can be cloned (copied).
IsClonable()2552 virtual bool IsClonable() const { return false; }
2553
2554 // Returns whether the instruction can be moved within the graph.
2555 // TODO: this method is used by LICM and GVN with possibly different
2556 // meanings? split and rename?
CanBeMoved()2557 virtual bool CanBeMoved() const { return false; }
2558
2559 // Returns whether any data encoded in the two instructions is equal.
2560 // This method does not look at the inputs. Both instructions must be
2561 // of the same type, otherwise the method has undefined behavior.
InstructionDataEquals(const HInstruction * other ATTRIBUTE_UNUSED)2562 virtual bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const {
2563 return false;
2564 }
2565
2566 // Returns whether two instructions are equal, that is:
2567 // 1) They have the same type and contain the same data (InstructionDataEquals).
2568 // 2) Their inputs are identical.
2569 bool Equals(const HInstruction* other) const;
2570
GetKind()2571 InstructionKind GetKind() const { return GetPackedField<InstructionKindField>(); }
2572
ComputeHashCode()2573 virtual size_t ComputeHashCode() const {
2574 size_t result = GetKind();
2575 for (const HInstruction* input : GetInputs()) {
2576 result = (result * 31) + input->GetId();
2577 }
2578 return result;
2579 }
2580
GetSideEffects()2581 SideEffects GetSideEffects() const { return side_effects_; }
SetSideEffects(SideEffects other)2582 void SetSideEffects(SideEffects other) { side_effects_ = other; }
AddSideEffects(SideEffects other)2583 void AddSideEffects(SideEffects other) { side_effects_.Add(other); }
2584
GetLifetimePosition()2585 size_t GetLifetimePosition() const { return lifetime_position_; }
SetLifetimePosition(size_t position)2586 void SetLifetimePosition(size_t position) { lifetime_position_ = position; }
GetLiveInterval()2587 LiveInterval* GetLiveInterval() const { return live_interval_; }
SetLiveInterval(LiveInterval * interval)2588 void SetLiveInterval(LiveInterval* interval) { live_interval_ = interval; }
HasLiveInterval()2589 bool HasLiveInterval() const { return live_interval_ != nullptr; }
2590
IsSuspendCheckEntry()2591 bool IsSuspendCheckEntry() const { return IsSuspendCheck() && GetBlock()->IsEntryBlock(); }
2592
2593 // Returns whether the code generation of the instruction will require to have access
2594 // to the current method. Such instructions are:
2595 // (1): Instructions that require an environment, as calling the runtime requires
2596 // to walk the stack and have the current method stored at a specific stack address.
2597 // (2): HCurrentMethod, potentially used by HInvokeStaticOrDirect, HLoadString, or HLoadClass
2598 // to access the dex cache.
NeedsCurrentMethod()2599 bool NeedsCurrentMethod() const {
2600 return NeedsEnvironment() || IsCurrentMethod();
2601 }
2602
2603 // Does this instruction have any use in an environment before
2604 // control flow hits 'other'?
2605 bool HasAnyEnvironmentUseBefore(HInstruction* other);
2606
2607 // Remove all references to environment uses of this instruction.
2608 // The caller must ensure that this is safe to do.
2609 void RemoveEnvironmentUsers();
2610
IsEmittedAtUseSite()2611 bool IsEmittedAtUseSite() const { return GetPackedFlag<kFlagEmittedAtUseSite>(); }
MarkEmittedAtUseSite()2612 void MarkEmittedAtUseSite() { SetPackedFlag<kFlagEmittedAtUseSite>(true); }
2613
2614 protected:
2615 // If set, the machine code for this instruction is assumed to be generated by
2616 // its users. Used by liveness analysis to compute use positions accordingly.
2617 static constexpr size_t kFlagEmittedAtUseSite = 0u;
2618 static constexpr size_t kFlagReferenceTypeIsExact = kFlagEmittedAtUseSite + 1;
2619 static constexpr size_t kFieldInstructionKind = kFlagReferenceTypeIsExact + 1;
2620 static constexpr size_t kFieldInstructionKindSize =
2621 MinimumBitsToStore(static_cast<size_t>(InstructionKind::kLastInstructionKind - 1));
2622 static constexpr size_t kFieldType =
2623 kFieldInstructionKind + kFieldInstructionKindSize;
2624 static constexpr size_t kFieldTypeSize =
2625 MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
2626 static constexpr size_t kNumberOfGenericPackedBits = kFieldType + kFieldTypeSize;
2627 static constexpr size_t kMaxNumberOfPackedBits = sizeof(uint32_t) * kBitsPerByte;
2628
2629 static_assert(kNumberOfGenericPackedBits <= kMaxNumberOfPackedBits,
2630 "Too many generic packed fields");
2631
2632 using TypeField = BitField<DataType::Type, kFieldType, kFieldTypeSize>;
2633
InputRecordAt(size_t i)2634 const HUserRecord<HInstruction*> InputRecordAt(size_t i) const {
2635 return GetInputRecords()[i];
2636 }
2637
SetRawInputRecordAt(size_t index,const HUserRecord<HInstruction * > & input)2638 void SetRawInputRecordAt(size_t index, const HUserRecord<HInstruction*>& input) {
2639 ArrayRef<HUserRecord<HInstruction*>> input_records = GetInputRecords();
2640 input_records[index] = input;
2641 }
2642
GetPackedFields()2643 uint32_t GetPackedFields() const {
2644 return packed_fields_;
2645 }
2646
2647 template <size_t flag>
GetPackedFlag()2648 bool GetPackedFlag() const {
2649 return (packed_fields_ & (1u << flag)) != 0u;
2650 }
2651
2652 template <size_t flag>
2653 void SetPackedFlag(bool value = true) {
2654 packed_fields_ = (packed_fields_ & ~(1u << flag)) | ((value ? 1u : 0u) << flag);
2655 }
2656
2657 template <typename BitFieldType>
GetPackedField()2658 typename BitFieldType::value_type GetPackedField() const {
2659 return BitFieldType::Decode(packed_fields_);
2660 }
2661
2662 template <typename BitFieldType>
SetPackedField(typename BitFieldType::value_type value)2663 void SetPackedField(typename BitFieldType::value_type value) {
2664 DCHECK(IsUint<BitFieldType::size>(static_cast<uintptr_t>(value)));
2665 packed_fields_ = BitFieldType::Update(value, packed_fields_);
2666 }
2667
2668 // Copy construction for the instruction (used for Clone function).
2669 //
2670 // Fields (e.g. lifetime, intervals and codegen info) associated with phases starting from
2671 // prepare_for_register_allocator are not copied (set to default values).
2672 //
2673 // Copy constructors must be provided for every HInstruction type; default copy constructor is
2674 // fine for most of them. However for some of the instructions a custom copy constructor must be
2675 // specified (when instruction has non-trivially copyable fields and must have a special behaviour
2676 // for copying them).
HInstruction(const HInstruction & other)2677 explicit HInstruction(const HInstruction& other)
2678 : previous_(nullptr),
2679 next_(nullptr),
2680 block_(nullptr),
2681 dex_pc_(other.dex_pc_),
2682 id_(-1),
2683 ssa_index_(-1),
2684 packed_fields_(other.packed_fields_),
2685 environment_(nullptr),
2686 locations_(nullptr),
2687 live_interval_(nullptr),
2688 lifetime_position_(kNoLifetime),
2689 side_effects_(other.side_effects_),
2690 reference_type_handle_(other.reference_type_handle_) {
2691 }
2692
2693 private:
2694 using InstructionKindField =
2695 BitField<InstructionKind, kFieldInstructionKind, kFieldInstructionKindSize>;
2696
FixUpUserRecordsAfterUseInsertion(HUseList<HInstruction * >::iterator fixup_end)2697 void FixUpUserRecordsAfterUseInsertion(HUseList<HInstruction*>::iterator fixup_end) {
2698 auto before_use_node = uses_.before_begin();
2699 for (auto use_node = uses_.begin(); use_node != fixup_end; ++use_node) {
2700 HInstruction* user = use_node->GetUser();
2701 size_t input_index = use_node->GetIndex();
2702 user->SetRawInputRecordAt(input_index, HUserRecord<HInstruction*>(this, before_use_node));
2703 before_use_node = use_node;
2704 }
2705 }
2706
FixUpUserRecordsAfterUseRemoval(HUseList<HInstruction * >::iterator before_use_node)2707 void FixUpUserRecordsAfterUseRemoval(HUseList<HInstruction*>::iterator before_use_node) {
2708 auto next = ++HUseList<HInstruction*>::iterator(before_use_node);
2709 if (next != uses_.end()) {
2710 HInstruction* next_user = next->GetUser();
2711 size_t next_index = next->GetIndex();
2712 DCHECK(next_user->InputRecordAt(next_index).GetInstruction() == this);
2713 next_user->SetRawInputRecordAt(next_index, HUserRecord<HInstruction*>(this, before_use_node));
2714 }
2715 }
2716
FixUpUserRecordsAfterEnvUseInsertion(HUseList<HEnvironment * >::iterator env_fixup_end)2717 void FixUpUserRecordsAfterEnvUseInsertion(HUseList<HEnvironment*>::iterator env_fixup_end) {
2718 auto before_env_use_node = env_uses_.before_begin();
2719 for (auto env_use_node = env_uses_.begin(); env_use_node != env_fixup_end; ++env_use_node) {
2720 HEnvironment* user = env_use_node->GetUser();
2721 size_t input_index = env_use_node->GetIndex();
2722 user->vregs_[input_index] = HUserRecord<HEnvironment*>(this, before_env_use_node);
2723 before_env_use_node = env_use_node;
2724 }
2725 }
2726
FixUpUserRecordsAfterEnvUseRemoval(HUseList<HEnvironment * >::iterator before_env_use_node)2727 void FixUpUserRecordsAfterEnvUseRemoval(HUseList<HEnvironment*>::iterator before_env_use_node) {
2728 auto next = ++HUseList<HEnvironment*>::iterator(before_env_use_node);
2729 if (next != env_uses_.end()) {
2730 HEnvironment* next_user = next->GetUser();
2731 size_t next_index = next->GetIndex();
2732 DCHECK(next_user->vregs_[next_index].GetInstruction() == this);
2733 next_user->vregs_[next_index] = HUserRecord<HEnvironment*>(this, before_env_use_node);
2734 }
2735 }
2736
2737 HInstruction* previous_;
2738 HInstruction* next_;
2739 HBasicBlock* block_;
2740 const uint32_t dex_pc_;
2741
2742 // An instruction gets an id when it is added to the graph.
2743 // It reflects creation order. A negative id means the instruction
2744 // has not been added to the graph.
2745 int id_;
2746
2747 // When doing liveness analysis, instructions that have uses get an SSA index.
2748 int ssa_index_;
2749
2750 // Packed fields.
2751 uint32_t packed_fields_;
2752
2753 // List of instructions that have this instruction as input.
2754 HUseList<HInstruction*> uses_;
2755
2756 // List of environments that contain this instruction.
2757 HUseList<HEnvironment*> env_uses_;
2758
2759 // The environment associated with this instruction. Not null if the instruction
2760 // might jump out of the method.
2761 HEnvironment* environment_;
2762
2763 // Set by the code generator.
2764 LocationSummary* locations_;
2765
2766 // Set by the liveness analysis.
2767 LiveInterval* live_interval_;
2768
2769 // Set by the liveness analysis, this is the position in a linear
2770 // order of blocks where this instruction's live interval start.
2771 size_t lifetime_position_;
2772
2773 SideEffects side_effects_;
2774
2775 // The reference handle part of the reference type info.
2776 // The IsExact() flag is stored in packed fields.
2777 // TODO: for primitive types this should be marked as invalid.
2778 ReferenceTypeInfo::TypeHandle reference_type_handle_;
2779
2780 friend class GraphChecker;
2781 friend class HBasicBlock;
2782 friend class HEnvironment;
2783 friend class HGraph;
2784 friend class HInstructionList;
2785 };
2786
2787 std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs);
2788 std::ostream& operator<<(std::ostream& os, const HInstruction::NoArgsDump rhs);
2789 std::ostream& operator<<(std::ostream& os, const HInstruction::ArgsDump rhs);
2790 std::ostream& operator<<(std::ostream& os, const HUseList<HInstruction*>& lst);
2791 std::ostream& operator<<(std::ostream& os, const HUseList<HEnvironment*>& lst);
2792
2793 // Forward declarations for friends
2794 template <typename InnerIter> struct HSTLInstructionIterator;
2795
2796 // Iterates over the instructions, while preserving the next instruction
2797 // in case the current instruction gets removed from the list by the user
2798 // of this iterator.
2799 class HInstructionIterator : public ValueObject {
2800 public:
HInstructionIterator(const HInstructionList & instructions)2801 explicit HInstructionIterator(const HInstructionList& instructions)
2802 : instruction_(instructions.first_instruction_) {
2803 next_ = Done() ? nullptr : instruction_->GetNext();
2804 }
2805
Done()2806 bool Done() const { return instruction_ == nullptr; }
Current()2807 HInstruction* Current() const { return instruction_; }
Advance()2808 void Advance() {
2809 instruction_ = next_;
2810 next_ = Done() ? nullptr : instruction_->GetNext();
2811 }
2812
2813 private:
HInstructionIterator()2814 HInstructionIterator() : instruction_(nullptr), next_(nullptr) {}
2815
2816 HInstruction* instruction_;
2817 HInstruction* next_;
2818
2819 friend struct HSTLInstructionIterator<HInstructionIterator>;
2820 };
2821
2822 // Iterates over the instructions without saving the next instruction,
2823 // therefore handling changes in the graph potentially made by the user
2824 // of this iterator.
2825 class HInstructionIteratorHandleChanges : public ValueObject {
2826 public:
2827 explicit HInstructionIteratorHandleChanges(const HInstructionList& instructions)
2828 : instruction_(instructions.first_instruction_) {
2829 }
2830
2831 bool Done() const { return instruction_ == nullptr; }
2832 HInstruction* Current() const { return instruction_; }
2833 void Advance() {
2834 instruction_ = instruction_->GetNext();
2835 }
2836
2837 private:
2838 HInstructionIteratorHandleChanges() : instruction_(nullptr) {}
2839
2840 HInstruction* instruction_;
2841
2842 friend struct HSTLInstructionIterator<HInstructionIteratorHandleChanges>;
2843 };
2844
2845
2846 class HBackwardInstructionIterator : public ValueObject {
2847 public:
2848 explicit HBackwardInstructionIterator(const HInstructionList& instructions)
2849 : instruction_(instructions.last_instruction_) {
2850 next_ = Done() ? nullptr : instruction_->GetPrevious();
2851 }
2852
2853 bool Done() const { return instruction_ == nullptr; }
2854 HInstruction* Current() const { return instruction_; }
2855 void Advance() {
2856 instruction_ = next_;
2857 next_ = Done() ? nullptr : instruction_->GetPrevious();
2858 }
2859
2860 private:
2861 HBackwardInstructionIterator() : instruction_(nullptr), next_(nullptr) {}
2862
2863 HInstruction* instruction_;
2864 HInstruction* next_;
2865
2866 friend struct HSTLInstructionIterator<HBackwardInstructionIterator>;
2867 };
2868
2869 template <typename InnerIter>
2870 struct HSTLInstructionIterator : public ValueObject,
2871 public std::iterator<std::forward_iterator_tag, HInstruction*> {
2872 public:
2873 static_assert(std::is_same_v<InnerIter, HBackwardInstructionIterator> ||
2874 std::is_same_v<InnerIter, HInstructionIterator> ||
2875 std::is_same_v<InnerIter, HInstructionIteratorHandleChanges>,
2876 "Unknown wrapped iterator!");
2877
2878 explicit HSTLInstructionIterator(InnerIter inner) : inner_(inner) {}
2879 HInstruction* operator*() const {
2880 DCHECK(inner_.Current() != nullptr);
2881 return inner_.Current();
2882 }
2883
2884 HSTLInstructionIterator<InnerIter>& operator++() {
2885 DCHECK(*this != HSTLInstructionIterator<InnerIter>::EndIter());
2886 inner_.Advance();
2887 return *this;
2888 }
2889
2890 HSTLInstructionIterator<InnerIter> operator++(int) {
2891 HSTLInstructionIterator<InnerIter> prev(*this);
2892 ++(*this);
2893 return prev;
2894 }
2895
2896 bool operator==(const HSTLInstructionIterator<InnerIter>& other) const {
2897 return inner_.Current() == other.inner_.Current();
2898 }
2899
2900 bool operator!=(const HSTLInstructionIterator<InnerIter>& other) const {
2901 return !(*this == other);
2902 }
2903
2904 static HSTLInstructionIterator<InnerIter> EndIter() {
2905 return HSTLInstructionIterator<InnerIter>(InnerIter());
2906 }
2907
2908 private:
2909 InnerIter inner_;
2910 };
2911
2912 template <typename InnerIter>
2913 IterationRange<HSTLInstructionIterator<InnerIter>> MakeSTLInstructionIteratorRange(InnerIter iter) {
2914 return MakeIterationRange(HSTLInstructionIterator<InnerIter>(iter),
2915 HSTLInstructionIterator<InnerIter>::EndIter());
2916 }
2917
2918 class HVariableInputSizeInstruction : public HInstruction {
2919 public:
2920 using HInstruction::GetInputRecords; // Keep the const version visible.
2921 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() override {
2922 return ArrayRef<HUserRecord<HInstruction*>>(inputs_);
2923 }
2924
2925 void AddInput(HInstruction* input);
2926 void InsertInputAt(size_t index, HInstruction* input);
2927 void RemoveInputAt(size_t index);
2928
2929 // Removes all the inputs.
2930 // Also removes this instructions from each input's use list
2931 // (for non-environment uses only).
2932 void RemoveAllInputs();
2933
2934 protected:
2935 HVariableInputSizeInstruction(InstructionKind inst_kind,
2936 SideEffects side_effects,
2937 uint32_t dex_pc,
2938 ArenaAllocator* allocator,
2939 size_t number_of_inputs,
2940 ArenaAllocKind kind)
2941 : HInstruction(inst_kind, side_effects, dex_pc),
2942 inputs_(number_of_inputs, allocator->Adapter(kind)) {}
2943 HVariableInputSizeInstruction(InstructionKind inst_kind,
2944 DataType::Type type,
2945 SideEffects side_effects,
2946 uint32_t dex_pc,
2947 ArenaAllocator* allocator,
2948 size_t number_of_inputs,
2949 ArenaAllocKind kind)
2950 : HInstruction(inst_kind, type, side_effects, dex_pc),
2951 inputs_(number_of_inputs, allocator->Adapter(kind)) {}
2952
2953 DEFAULT_COPY_CONSTRUCTOR(VariableInputSizeInstruction);
2954
2955 ArenaVector<HUserRecord<HInstruction*>> inputs_;
2956 };
2957
2958 template<size_t N>
2959 class HExpression : public HInstruction {
2960 public:
2961 HExpression<N>(InstructionKind kind, SideEffects side_effects, uint32_t dex_pc)
2962 : HInstruction(kind, side_effects, dex_pc), inputs_() {}
2963 HExpression<N>(InstructionKind kind,
2964 DataType::Type type,
2965 SideEffects side_effects,
2966 uint32_t dex_pc)
2967 : HInstruction(kind, type, side_effects, dex_pc), inputs_() {}
2968 virtual ~HExpression() {}
2969
2970 using HInstruction::GetInputRecords; // Keep the const version visible.
2971 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
2972 return ArrayRef<HUserRecord<HInstruction*>>(inputs_);
2973 }
2974
2975 protected:
2976 DEFAULT_COPY_CONSTRUCTOR(Expression<N>);
2977
2978 private:
2979 std::array<HUserRecord<HInstruction*>, N> inputs_;
2980
2981 friend class SsaBuilder;
2982 };
2983
2984 // HExpression specialization for N=0.
2985 template<>
2986 class HExpression<0> : public HInstruction {
2987 public:
2988 using HInstruction::HInstruction;
2989
2990 virtual ~HExpression() {}
2991
2992 using HInstruction::GetInputRecords; // Keep the const version visible.
2993 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
2994 return ArrayRef<HUserRecord<HInstruction*>>();
2995 }
2996
2997 protected:
2998 DEFAULT_COPY_CONSTRUCTOR(Expression<0>);
2999
3000 private:
3001 friend class SsaBuilder;
3002 };
3003
3004 class HMethodEntryHook : public HExpression<0> {
3005 public:
3006 explicit HMethodEntryHook(uint32_t dex_pc)
3007 : HExpression(kMethodEntryHook, SideEffects::All(), dex_pc) {}
3008
3009 bool NeedsEnvironment() const override {
3010 return true;
3011 }
3012
3013 bool CanThrow() const override { return true; }
3014
3015 DECLARE_INSTRUCTION(MethodEntryHook);
3016
3017 protected:
3018 DEFAULT_COPY_CONSTRUCTOR(MethodEntryHook);
3019 };
3020
3021 class HMethodExitHook : public HExpression<1> {
3022 public:
3023 HMethodExitHook(HInstruction* value, uint32_t dex_pc)
3024 : HExpression(kMethodExitHook, SideEffects::All(), dex_pc) {
3025 SetRawInputAt(0, value);
3026 }
3027
3028 bool NeedsEnvironment() const override {
3029 return true;
3030 }
3031
3032 bool CanThrow() const override { return true; }
3033
3034 DECLARE_INSTRUCTION(MethodExitHook);
3035
3036 protected:
3037 DEFAULT_COPY_CONSTRUCTOR(MethodExitHook);
3038 };
3039
3040 // Represents dex's RETURN_VOID opcode. A HReturnVoid is a control flow
3041 // instruction that branches to the exit block.
3042 class HReturnVoid final : public HExpression<0> {
3043 public:
3044 explicit HReturnVoid(uint32_t dex_pc = kNoDexPc)
3045 : HExpression(kReturnVoid, SideEffects::None(), dex_pc) {
3046 }
3047
3048 bool IsControlFlow() const override { return true; }
3049
3050 DECLARE_INSTRUCTION(ReturnVoid);
3051
3052 protected:
3053 DEFAULT_COPY_CONSTRUCTOR(ReturnVoid);
3054 };
3055
3056 // Represents dex's RETURN opcodes. A HReturn is a control flow
3057 // instruction that branches to the exit block.
3058 class HReturn final : public HExpression<1> {
3059 public:
3060 explicit HReturn(HInstruction* value, uint32_t dex_pc = kNoDexPc)
3061 : HExpression(kReturn, SideEffects::None(), dex_pc) {
3062 SetRawInputAt(0, value);
3063 }
3064
3065 bool IsControlFlow() const override { return true; }
3066
3067 DECLARE_INSTRUCTION(Return);
3068
3069 protected:
3070 DEFAULT_COPY_CONSTRUCTOR(Return);
3071 };
3072
3073 class HPhi final : public HVariableInputSizeInstruction {
3074 public:
3075 HPhi(ArenaAllocator* allocator,
3076 uint32_t reg_number,
3077 size_t number_of_inputs,
3078 DataType::Type type,
3079 uint32_t dex_pc = kNoDexPc)
3080 : HVariableInputSizeInstruction(
3081 kPhi,
3082 ToPhiType(type),
3083 SideEffects::None(),
3084 dex_pc,
3085 allocator,
3086 number_of_inputs,
3087 kArenaAllocPhiInputs),
3088 reg_number_(reg_number) {
3089 DCHECK_NE(GetType(), DataType::Type::kVoid);
3090 // Phis are constructed live and marked dead if conflicting or unused.
3091 // Individual steps of SsaBuilder should assume that if a phi has been
3092 // marked dead, it can be ignored and will be removed by SsaPhiElimination.
3093 SetPackedFlag<kFlagIsLive>(true);
3094 SetPackedFlag<kFlagCanBeNull>(true);
3095 }
3096
3097 bool IsClonable() const override { return true; }
3098
3099 // Returns a type equivalent to the given `type`, but that a `HPhi` can hold.
3100 static DataType::Type ToPhiType(DataType::Type type) {
3101 return DataType::Kind(type);
3102 }
3103
3104 bool IsCatchPhi() const { return GetBlock()->IsCatchBlock(); }
3105
3106 void SetType(DataType::Type new_type) {
3107 // Make sure that only valid type changes occur. The following are allowed:
3108 // (1) int -> float/ref (primitive type propagation),
3109 // (2) long -> double (primitive type propagation).
3110 DCHECK(GetType() == new_type ||
3111 (GetType() == DataType::Type::kInt32 && new_type == DataType::Type::kFloat32) ||
3112 (GetType() == DataType::Type::kInt32 && new_type == DataType::Type::kReference) ||
3113 (GetType() == DataType::Type::kInt64 && new_type == DataType::Type::kFloat64));
3114 SetPackedField<TypeField>(new_type);
3115 }
3116
3117 bool CanBeNull() const override { return GetPackedFlag<kFlagCanBeNull>(); }
3118 void SetCanBeNull(bool can_be_null) { SetPackedFlag<kFlagCanBeNull>(can_be_null); }
3119
3120 uint32_t GetRegNumber() const { return reg_number_; }
3121
3122 void SetDead() { SetPackedFlag<kFlagIsLive>(false); }
3123 void SetLive() { SetPackedFlag<kFlagIsLive>(true); }
3124 bool IsDead() const { return !IsLive(); }
3125 bool IsLive() const { return GetPackedFlag<kFlagIsLive>(); }
3126
3127 bool IsVRegEquivalentOf(const HInstruction* other) const {
3128 return other != nullptr
3129 && other->IsPhi()
3130 && other->AsPhi()->GetBlock() == GetBlock()
3131 && other->AsPhi()->GetRegNumber() == GetRegNumber();
3132 }
3133
3134 bool HasEquivalentPhi() const {
3135 if (GetPrevious() != nullptr && GetPrevious()->AsPhi()->GetRegNumber() == GetRegNumber()) {
3136 return true;
3137 }
3138 if (GetNext() != nullptr && GetNext()->AsPhi()->GetRegNumber() == GetRegNumber()) {
3139 return true;
3140 }
3141 return false;
3142 }
3143
3144 // Returns the next equivalent phi (starting from the current one) or null if there is none.
3145 // An equivalent phi is a phi having the same dex register and type.
3146 // It assumes that phis with the same dex register are adjacent.
3147 HPhi* GetNextEquivalentPhiWithSameType() {
3148 HInstruction* next = GetNext();
3149 while (next != nullptr && next->AsPhi()->GetRegNumber() == reg_number_) {
3150 if (next->GetType() == GetType()) {
3151 return next->AsPhi();
3152 }
3153 next = next->GetNext();
3154 }
3155 return nullptr;
3156 }
3157
3158 DECLARE_INSTRUCTION(Phi);
3159
3160 protected:
3161 DEFAULT_COPY_CONSTRUCTOR(Phi);
3162
3163 private:
3164 static constexpr size_t kFlagIsLive = HInstruction::kNumberOfGenericPackedBits;
3165 static constexpr size_t kFlagCanBeNull = kFlagIsLive + 1;
3166 static constexpr size_t kNumberOfPhiPackedBits = kFlagCanBeNull + 1;
3167 static_assert(kNumberOfPhiPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
3168
3169 const uint32_t reg_number_;
3170 };
3171
3172 // The exit instruction is the only instruction of the exit block.
3173 // Instructions aborting the method (HThrow and HReturn) must branch to the
3174 // exit block.
3175 class HExit final : public HExpression<0> {
3176 public:
3177 explicit HExit(uint32_t dex_pc = kNoDexPc)
3178 : HExpression(kExit, SideEffects::None(), dex_pc) {
3179 }
3180
3181 bool IsControlFlow() const override { return true; }
3182
3183 DECLARE_INSTRUCTION(Exit);
3184
3185 protected:
3186 DEFAULT_COPY_CONSTRUCTOR(Exit);
3187 };
3188
3189 // Jumps from one block to another.
3190 class HGoto final : public HExpression<0> {
3191 public:
3192 explicit HGoto(uint32_t dex_pc = kNoDexPc)
3193 : HExpression(kGoto, SideEffects::None(), dex_pc) {
3194 }
3195
3196 bool IsClonable() const override { return true; }
3197 bool IsControlFlow() const override { return true; }
3198
3199 HBasicBlock* GetSuccessor() const {
3200 return GetBlock()->GetSingleSuccessor();
3201 }
3202
3203 DECLARE_INSTRUCTION(Goto);
3204
3205 protected:
3206 DEFAULT_COPY_CONSTRUCTOR(Goto);
3207 };
3208
3209 class HConstant : public HExpression<0> {
3210 public:
3211 explicit HConstant(InstructionKind kind, DataType::Type type, uint32_t dex_pc = kNoDexPc)
3212 : HExpression(kind, type, SideEffects::None(), dex_pc) {
3213 }
3214
3215 bool CanBeMoved() const override { return true; }
3216
3217 // Is this constant -1 in the arithmetic sense?
3218 virtual bool IsMinusOne() const { return false; }
3219 // Is this constant 0 in the arithmetic sense?
3220 virtual bool IsArithmeticZero() const { return false; }
3221 // Is this constant a 0-bit pattern?
3222 virtual bool IsZeroBitPattern() const { return false; }
3223 // Is this constant 1 in the arithmetic sense?
3224 virtual bool IsOne() const { return false; }
3225
3226 virtual uint64_t GetValueAsUint64() const = 0;
3227
3228 DECLARE_ABSTRACT_INSTRUCTION(Constant);
3229
3230 protected:
3231 DEFAULT_COPY_CONSTRUCTOR(Constant);
3232 };
3233
3234 class HNullConstant final : public HConstant {
3235 public:
3236 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
3237 return true;
3238 }
3239
3240 uint64_t GetValueAsUint64() const override { return 0; }
3241
3242 size_t ComputeHashCode() const override { return 0; }
3243
3244 // The null constant representation is a 0-bit pattern.
3245 bool IsZeroBitPattern() const override { return true; }
3246
3247 DECLARE_INSTRUCTION(NullConstant);
3248
3249 protected:
3250 DEFAULT_COPY_CONSTRUCTOR(NullConstant);
3251
3252 private:
3253 explicit HNullConstant(uint32_t dex_pc = kNoDexPc)
3254 : HConstant(kNullConstant, DataType::Type::kReference, dex_pc) {
3255 }
3256
3257 friend class HGraph;
3258 };
3259
3260 // Constants of the type int. Those can be from Dex instructions, or
3261 // synthesized (for example with the if-eqz instruction).
3262 class HIntConstant final : public HConstant {
3263 public:
3264 int32_t GetValue() const { return value_; }
3265
3266 uint64_t GetValueAsUint64() const override {
3267 return static_cast<uint64_t>(static_cast<uint32_t>(value_));
3268 }
3269
3270 bool InstructionDataEquals(const HInstruction* other) const override {
3271 DCHECK(other->IsIntConstant()) << other->DebugName();
3272 return other->AsIntConstant()->value_ == value_;
3273 }
3274
3275 size_t ComputeHashCode() const override { return GetValue(); }
3276
3277 bool IsMinusOne() const override { return GetValue() == -1; }
3278 bool IsArithmeticZero() const override { return GetValue() == 0; }
3279 bool IsZeroBitPattern() const override { return GetValue() == 0; }
3280 bool IsOne() const override { return GetValue() == 1; }
3281
3282 // Integer constants are used to encode Boolean values as well,
3283 // where 1 means true and 0 means false.
3284 bool IsTrue() const { return GetValue() == 1; }
3285 bool IsFalse() const { return GetValue() == 0; }
3286
3287 DECLARE_INSTRUCTION(IntConstant);
3288
3289 protected:
3290 DEFAULT_COPY_CONSTRUCTOR(IntConstant);
3291
3292 private:
3293 explicit HIntConstant(int32_t value, uint32_t dex_pc = kNoDexPc)
3294 : HConstant(kIntConstant, DataType::Type::kInt32, dex_pc), value_(value) {
3295 }
3296 explicit HIntConstant(bool value, uint32_t dex_pc = kNoDexPc)
3297 : HConstant(kIntConstant, DataType::Type::kInt32, dex_pc),
3298 value_(value ? 1 : 0) {
3299 }
3300
3301 const int32_t value_;
3302
3303 friend class HGraph;
3304 ART_FRIEND_TEST(GraphTest, InsertInstructionBefore);
3305 ART_FRIEND_TYPED_TEST(ParallelMoveTest, ConstantLast);
3306 };
3307
3308 class HLongConstant final : public HConstant {
3309 public:
3310 int64_t GetValue() const { return value_; }
3311
3312 uint64_t GetValueAsUint64() const override { return value_; }
3313
3314 bool InstructionDataEquals(const HInstruction* other) const override {
3315 DCHECK(other->IsLongConstant()) << other->DebugName();
3316 return other->AsLongConstant()->value_ == value_;
3317 }
3318
3319 size_t ComputeHashCode() const override { return static_cast<size_t>(GetValue()); }
3320
3321 bool IsMinusOne() const override { return GetValue() == -1; }
3322 bool IsArithmeticZero() const override { return GetValue() == 0; }
3323 bool IsZeroBitPattern() const override { return GetValue() == 0; }
3324 bool IsOne() const override { return GetValue() == 1; }
3325
3326 DECLARE_INSTRUCTION(LongConstant);
3327
3328 protected:
3329 DEFAULT_COPY_CONSTRUCTOR(LongConstant);
3330
3331 private:
3332 explicit HLongConstant(int64_t value, uint32_t dex_pc = kNoDexPc)
3333 : HConstant(kLongConstant, DataType::Type::kInt64, dex_pc),
3334 value_(value) {
3335 }
3336
3337 const int64_t value_;
3338
3339 friend class HGraph;
3340 };
3341
3342 class HFloatConstant final : public HConstant {
3343 public:
3344 float GetValue() const { return value_; }
3345
3346 uint64_t GetValueAsUint64() const override {
3347 return static_cast<uint64_t>(bit_cast<uint32_t, float>(value_));
3348 }
3349
3350 bool InstructionDataEquals(const HInstruction* other) const override {
3351 DCHECK(other->IsFloatConstant()) << other->DebugName();
3352 return other->AsFloatConstant()->GetValueAsUint64() == GetValueAsUint64();
3353 }
3354
3355 size_t ComputeHashCode() const override { return static_cast<size_t>(GetValue()); }
3356
3357 bool IsMinusOne() const override {
3358 return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>((-1.0f));
3359 }
3360 bool IsArithmeticZero() const override {
3361 return std::fpclassify(value_) == FP_ZERO;
3362 }
3363 bool IsArithmeticPositiveZero() const {
3364 return IsArithmeticZero() && !std::signbit(value_);
3365 }
3366 bool IsArithmeticNegativeZero() const {
3367 return IsArithmeticZero() && std::signbit(value_);
3368 }
3369 bool IsZeroBitPattern() const override {
3370 return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>(0.0f);
3371 }
3372 bool IsOne() const override {
3373 return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>(1.0f);
3374 }
3375 bool IsNaN() const {
3376 return std::isnan(value_);
3377 }
3378
3379 DECLARE_INSTRUCTION(FloatConstant);
3380
3381 protected:
3382 DEFAULT_COPY_CONSTRUCTOR(FloatConstant);
3383
3384 private:
3385 explicit HFloatConstant(float value, uint32_t dex_pc = kNoDexPc)
3386 : HConstant(kFloatConstant, DataType::Type::kFloat32, dex_pc),
3387 value_(value) {
3388 }
3389 explicit HFloatConstant(int32_t value, uint32_t dex_pc = kNoDexPc)
3390 : HConstant(kFloatConstant, DataType::Type::kFloat32, dex_pc),
3391 value_(bit_cast<float, int32_t>(value)) {
3392 }
3393
3394 const float value_;
3395
3396 // Only the SsaBuilder and HGraph can create floating-point constants.
3397 friend class SsaBuilder;
3398 friend class HGraph;
3399 };
3400
3401 class HDoubleConstant final : public HConstant {
3402 public:
3403 double GetValue() const { return value_; }
3404
3405 uint64_t GetValueAsUint64() const override { return bit_cast<uint64_t, double>(value_); }
3406
3407 bool InstructionDataEquals(const HInstruction* other) const override {
3408 DCHECK(other->IsDoubleConstant()) << other->DebugName();
3409 return other->AsDoubleConstant()->GetValueAsUint64() == GetValueAsUint64();
3410 }
3411
3412 size_t ComputeHashCode() const override { return static_cast<size_t>(GetValue()); }
3413
3414 bool IsMinusOne() const override {
3415 return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>((-1.0));
3416 }
3417 bool IsArithmeticZero() const override {
3418 return std::fpclassify(value_) == FP_ZERO;
3419 }
3420 bool IsArithmeticPositiveZero() const {
3421 return IsArithmeticZero() && !std::signbit(value_);
3422 }
3423 bool IsArithmeticNegativeZero() const {
3424 return IsArithmeticZero() && std::signbit(value_);
3425 }
3426 bool IsZeroBitPattern() const override {
3427 return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>((0.0));
3428 }
3429 bool IsOne() const override {
3430 return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>(1.0);
3431 }
3432 bool IsNaN() const {
3433 return std::isnan(value_);
3434 }
3435
3436 DECLARE_INSTRUCTION(DoubleConstant);
3437
3438 protected:
3439 DEFAULT_COPY_CONSTRUCTOR(DoubleConstant);
3440
3441 private:
3442 explicit HDoubleConstant(double value, uint32_t dex_pc = kNoDexPc)
3443 : HConstant(kDoubleConstant, DataType::Type::kFloat64, dex_pc),
3444 value_(value) {
3445 }
3446 explicit HDoubleConstant(int64_t value, uint32_t dex_pc = kNoDexPc)
3447 : HConstant(kDoubleConstant, DataType::Type::kFloat64, dex_pc),
3448 value_(bit_cast<double, int64_t>(value)) {
3449 }
3450
3451 const double value_;
3452
3453 // Only the SsaBuilder and HGraph can create floating-point constants.
3454 friend class SsaBuilder;
3455 friend class HGraph;
3456 };
3457
3458 // Conditional branch. A block ending with an HIf instruction must have
3459 // two successors.
3460 class HIf final : public HExpression<1> {
3461 public:
3462 explicit HIf(HInstruction* input, uint32_t dex_pc = kNoDexPc)
3463 : HExpression(kIf, SideEffects::None(), dex_pc) {
3464 SetRawInputAt(0, input);
3465 }
3466
3467 bool IsClonable() const override { return true; }
3468 bool IsControlFlow() const override { return true; }
3469
3470 HBasicBlock* IfTrueSuccessor() const {
3471 return GetBlock()->GetSuccessors()[0];
3472 }
3473
3474 HBasicBlock* IfFalseSuccessor() const {
3475 return GetBlock()->GetSuccessors()[1];
3476 }
3477
3478 DECLARE_INSTRUCTION(If);
3479
3480 protected:
3481 DEFAULT_COPY_CONSTRUCTOR(If);
3482 };
3483
3484
3485 // Abstract instruction which marks the beginning and/or end of a try block and
3486 // links it to the respective exception handlers. Behaves the same as a Goto in
3487 // non-exceptional control flow.
3488 // Normal-flow successor is stored at index zero, exception handlers under
3489 // higher indices in no particular order.
3490 class HTryBoundary final : public HExpression<0> {
3491 public:
3492 enum class BoundaryKind {
3493 kEntry,
3494 kExit,
3495 kLast = kExit
3496 };
3497
3498 // SideEffects::CanTriggerGC prevents instructions with SideEffects::DependOnGC to be alive
3499 // across the catch block entering edges as GC might happen during throwing an exception.
3500 // TryBoundary with BoundaryKind::kExit is conservatively used for that as there is no
3501 // HInstruction which a catch block must start from.
3502 explicit HTryBoundary(BoundaryKind kind, uint32_t dex_pc = kNoDexPc)
3503 : HExpression(kTryBoundary,
3504 (kind == BoundaryKind::kExit) ? SideEffects::CanTriggerGC()
3505 : SideEffects::None(),
3506 dex_pc) {
3507 SetPackedField<BoundaryKindField>(kind);
3508 }
3509
3510 bool IsControlFlow() const override { return true; }
3511
3512 // Returns the block's non-exceptional successor (index zero).
3513 HBasicBlock* GetNormalFlowSuccessor() const { return GetBlock()->GetSuccessors()[0]; }
3514
3515 ArrayRef<HBasicBlock* const> GetExceptionHandlers() const {
3516 return ArrayRef<HBasicBlock* const>(GetBlock()->GetSuccessors()).SubArray(1u);
3517 }
3518
3519 // Returns whether `handler` is among its exception handlers (non-zero index
3520 // successors).
3521 bool HasExceptionHandler(const HBasicBlock& handler) const {
3522 DCHECK(handler.IsCatchBlock());
3523 return GetBlock()->HasSuccessor(&handler, 1u /* Skip first successor. */);
3524 }
3525
3526 // If not present already, adds `handler` to its block's list of exception
3527 // handlers.
3528 void AddExceptionHandler(HBasicBlock* handler) {
3529 if (!HasExceptionHandler(*handler)) {
3530 GetBlock()->AddSuccessor(handler);
3531 }
3532 }
3533
3534 BoundaryKind GetBoundaryKind() const { return GetPackedField<BoundaryKindField>(); }
3535 bool IsEntry() const { return GetBoundaryKind() == BoundaryKind::kEntry; }
3536
3537 bool HasSameExceptionHandlersAs(const HTryBoundary& other) const;
3538
3539 DECLARE_INSTRUCTION(TryBoundary);
3540
3541 protected:
3542 DEFAULT_COPY_CONSTRUCTOR(TryBoundary);
3543
3544 private:
3545 static constexpr size_t kFieldBoundaryKind = kNumberOfGenericPackedBits;
3546 static constexpr size_t kFieldBoundaryKindSize =
3547 MinimumBitsToStore(static_cast<size_t>(BoundaryKind::kLast));
3548 static constexpr size_t kNumberOfTryBoundaryPackedBits =
3549 kFieldBoundaryKind + kFieldBoundaryKindSize;
3550 static_assert(kNumberOfTryBoundaryPackedBits <= kMaxNumberOfPackedBits,
3551 "Too many packed fields.");
3552 using BoundaryKindField = BitField<BoundaryKind, kFieldBoundaryKind, kFieldBoundaryKindSize>;
3553 };
3554
3555 // Deoptimize to interpreter, upon checking a condition.
3556 class HDeoptimize final : public HVariableInputSizeInstruction {
3557 public:
3558 // Use this constructor when the `HDeoptimize` acts as a barrier, where no code can move
3559 // across.
3560 HDeoptimize(ArenaAllocator* allocator,
3561 HInstruction* cond,
3562 DeoptimizationKind kind,
3563 uint32_t dex_pc)
3564 : HVariableInputSizeInstruction(
3565 kDeoptimize,
3566 SideEffects::All(),
3567 dex_pc,
3568 allocator,
3569 /* number_of_inputs= */ 1,
3570 kArenaAllocMisc) {
3571 SetPackedFlag<kFieldCanBeMoved>(false);
3572 SetPackedField<DeoptimizeKindField>(kind);
3573 SetRawInputAt(0, cond);
3574 }
3575
3576 bool IsClonable() const override { return true; }
3577
3578 // Use this constructor when the `HDeoptimize` guards an instruction, and any user
3579 // that relies on the deoptimization to pass should have its input be the `HDeoptimize`
3580 // instead of `guard`.
3581 // We set CanTriggerGC to prevent any intermediate address to be live
3582 // at the point of the `HDeoptimize`.
3583 HDeoptimize(ArenaAllocator* allocator,
3584 HInstruction* cond,
3585 HInstruction* guard,
3586 DeoptimizationKind kind,
3587 uint32_t dex_pc)
3588 : HVariableInputSizeInstruction(
3589 kDeoptimize,
3590 guard->GetType(),
3591 SideEffects::CanTriggerGC(),
3592 dex_pc,
3593 allocator,
3594 /* number_of_inputs= */ 2,
3595 kArenaAllocMisc) {
3596 SetPackedFlag<kFieldCanBeMoved>(true);
3597 SetPackedField<DeoptimizeKindField>(kind);
3598 SetRawInputAt(0, cond);
3599 SetRawInputAt(1, guard);
3600 }
3601
3602 bool CanBeMoved() const override { return GetPackedFlag<kFieldCanBeMoved>(); }
3603
3604 bool InstructionDataEquals(const HInstruction* other) const override {
3605 return (other->CanBeMoved() == CanBeMoved()) && (other->AsDeoptimize()->GetKind() == GetKind());
3606 }
3607
3608 bool NeedsEnvironment() const override { return true; }
3609
3610 bool CanThrow() const override { return true; }
3611
3612 DeoptimizationKind GetDeoptimizationKind() const { return GetPackedField<DeoptimizeKindField>(); }
3613
3614 bool GuardsAnInput() const {
3615 return InputCount() == 2;
3616 }
3617
3618 HInstruction* GuardedInput() const {
3619 DCHECK(GuardsAnInput());
3620 return InputAt(1);
3621 }
3622
3623 void RemoveGuard() {
3624 RemoveInputAt(1);
3625 }
3626
3627 DECLARE_INSTRUCTION(Deoptimize);
3628
3629 protected:
3630 DEFAULT_COPY_CONSTRUCTOR(Deoptimize);
3631
3632 private:
3633 static constexpr size_t kFieldCanBeMoved = kNumberOfGenericPackedBits;
3634 static constexpr size_t kFieldDeoptimizeKind = kNumberOfGenericPackedBits + 1;
3635 static constexpr size_t kFieldDeoptimizeKindSize =
3636 MinimumBitsToStore(static_cast<size_t>(DeoptimizationKind::kLast));
3637 static constexpr size_t kNumberOfDeoptimizePackedBits =
3638 kFieldDeoptimizeKind + kFieldDeoptimizeKindSize;
3639 static_assert(kNumberOfDeoptimizePackedBits <= kMaxNumberOfPackedBits,
3640 "Too many packed fields.");
3641 using DeoptimizeKindField =
3642 BitField<DeoptimizationKind, kFieldDeoptimizeKind, kFieldDeoptimizeKindSize>;
3643 };
3644
3645 // Represents a should_deoptimize flag. Currently used for CHA-based devirtualization.
3646 // The compiled code checks this flag value in a guard before devirtualized call and
3647 // if it's true, starts to do deoptimization.
3648 // It has a 4-byte slot on stack.
3649 // TODO: allocate a register for this flag.
3650 class HShouldDeoptimizeFlag final : public HVariableInputSizeInstruction {
3651 public:
3652 // CHA guards are only optimized in a separate pass and it has no side effects
3653 // with regard to other passes.
3654 HShouldDeoptimizeFlag(ArenaAllocator* allocator, uint32_t dex_pc)
3655 : HVariableInputSizeInstruction(kShouldDeoptimizeFlag,
3656 DataType::Type::kInt32,
3657 SideEffects::None(),
3658 dex_pc,
3659 allocator,
3660 0,
3661 kArenaAllocCHA) {
3662 }
3663
3664 // We do all CHA guard elimination/motion in a single pass, after which there is no
3665 // further guard elimination/motion since a guard might have been used for justification
3666 // of the elimination of another guard. Therefore, we pretend this guard cannot be moved
3667 // to avoid other optimizations trying to move it.
3668 bool CanBeMoved() const override { return false; }
3669
3670 DECLARE_INSTRUCTION(ShouldDeoptimizeFlag);
3671
3672 protected:
3673 DEFAULT_COPY_CONSTRUCTOR(ShouldDeoptimizeFlag);
3674 };
3675
3676 // Represents the ArtMethod that was passed as a first argument to
3677 // the method. It is used by instructions that depend on it, like
3678 // instructions that work with the dex cache.
3679 class HCurrentMethod final : public HExpression<0> {
3680 public:
3681 explicit HCurrentMethod(DataType::Type type, uint32_t dex_pc = kNoDexPc)
3682 : HExpression(kCurrentMethod, type, SideEffects::None(), dex_pc) {
3683 }
3684
3685 DECLARE_INSTRUCTION(CurrentMethod);
3686
3687 protected:
3688 DEFAULT_COPY_CONSTRUCTOR(CurrentMethod);
3689 };
3690
3691 // Fetches an ArtMethod from the virtual table or the interface method table
3692 // of a class.
3693 class HClassTableGet final : public HExpression<1> {
3694 public:
3695 enum class TableKind {
3696 kVTable,
3697 kIMTable,
3698 kLast = kIMTable
3699 };
3700 HClassTableGet(HInstruction* cls,
3701 DataType::Type type,
3702 TableKind kind,
3703 size_t index,
3704 uint32_t dex_pc)
3705 : HExpression(kClassTableGet, type, SideEffects::None(), dex_pc),
3706 index_(index) {
3707 SetPackedField<TableKindField>(kind);
3708 SetRawInputAt(0, cls);
3709 }
3710
3711 bool IsClonable() const override { return true; }
3712 bool CanBeMoved() const override { return true; }
3713 bool InstructionDataEquals(const HInstruction* other) const override {
3714 return other->AsClassTableGet()->GetIndex() == index_ &&
3715 other->AsClassTableGet()->GetPackedFields() == GetPackedFields();
3716 }
3717
3718 TableKind GetTableKind() const { return GetPackedField<TableKindField>(); }
3719 size_t GetIndex() const { return index_; }
3720
3721 DECLARE_INSTRUCTION(ClassTableGet);
3722
3723 protected:
3724 DEFAULT_COPY_CONSTRUCTOR(ClassTableGet);
3725
3726 private:
3727 static constexpr size_t kFieldTableKind = kNumberOfGenericPackedBits;
3728 static constexpr size_t kFieldTableKindSize =
3729 MinimumBitsToStore(static_cast<size_t>(TableKind::kLast));
3730 static constexpr size_t kNumberOfClassTableGetPackedBits = kFieldTableKind + kFieldTableKindSize;
3731 static_assert(kNumberOfClassTableGetPackedBits <= kMaxNumberOfPackedBits,
3732 "Too many packed fields.");
3733 using TableKindField = BitField<TableKind, kFieldTableKind, kFieldTableKind>;
3734
3735 // The index of the ArtMethod in the table.
3736 const size_t index_;
3737 };
3738
3739 // PackedSwitch (jump table). A block ending with a PackedSwitch instruction will
3740 // have one successor for each entry in the switch table, and the final successor
3741 // will be the block containing the next Dex opcode.
3742 class HPackedSwitch final : public HExpression<1> {
3743 public:
3744 HPackedSwitch(int32_t start_value,
3745 uint32_t num_entries,
3746 HInstruction* input,
3747 uint32_t dex_pc = kNoDexPc)
3748 : HExpression(kPackedSwitch, SideEffects::None(), dex_pc),
3749 start_value_(start_value),
3750 num_entries_(num_entries) {
3751 SetRawInputAt(0, input);
3752 }
3753
3754 bool IsClonable() const override { return true; }
3755
3756 bool IsControlFlow() const override { return true; }
3757
3758 int32_t GetStartValue() const { return start_value_; }
3759
3760 uint32_t GetNumEntries() const { return num_entries_; }
3761
3762 HBasicBlock* GetDefaultBlock() const {
3763 // Last entry is the default block.
3764 return GetBlock()->GetSuccessors()[num_entries_];
3765 }
3766 DECLARE_INSTRUCTION(PackedSwitch);
3767
3768 protected:
3769 DEFAULT_COPY_CONSTRUCTOR(PackedSwitch);
3770
3771 private:
3772 const int32_t start_value_;
3773 const uint32_t num_entries_;
3774 };
3775
3776 class HUnaryOperation : public HExpression<1> {
3777 public:
3778 HUnaryOperation(InstructionKind kind,
3779 DataType::Type result_type,
3780 HInstruction* input,
3781 uint32_t dex_pc = kNoDexPc)
3782 : HExpression(kind, result_type, SideEffects::None(), dex_pc) {
3783 SetRawInputAt(0, input);
3784 }
3785
3786 // All of the UnaryOperation instructions are clonable.
3787 bool IsClonable() const override { return true; }
3788
3789 HInstruction* GetInput() const { return InputAt(0); }
3790 DataType::Type GetResultType() const { return GetType(); }
3791
3792 bool CanBeMoved() const override { return true; }
3793 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
3794 return true;
3795 }
3796
3797 // Try to statically evaluate `this` and return a HConstant
3798 // containing the result of this evaluation. If `this` cannot
3799 // be evaluated as a constant, return null.
3800 HConstant* TryStaticEvaluation() const;
3801
3802 // Apply this operation to `x`.
3803 virtual HConstant* Evaluate(HIntConstant* x) const = 0;
3804 virtual HConstant* Evaluate(HLongConstant* x) const = 0;
3805 virtual HConstant* Evaluate(HFloatConstant* x) const = 0;
3806 virtual HConstant* Evaluate(HDoubleConstant* x) const = 0;
3807
3808 DECLARE_ABSTRACT_INSTRUCTION(UnaryOperation);
3809
3810 protected:
3811 DEFAULT_COPY_CONSTRUCTOR(UnaryOperation);
3812 };
3813
3814 class HBinaryOperation : public HExpression<2> {
3815 public:
3816 HBinaryOperation(InstructionKind kind,
3817 DataType::Type result_type,
3818 HInstruction* left,
3819 HInstruction* right,
3820 SideEffects side_effects = SideEffects::None(),
3821 uint32_t dex_pc = kNoDexPc)
3822 : HExpression(kind, result_type, side_effects, dex_pc) {
3823 SetRawInputAt(0, left);
3824 SetRawInputAt(1, right);
3825 }
3826
3827 // All of the BinaryOperation instructions are clonable.
3828 bool IsClonable() const override { return true; }
3829
3830 HInstruction* GetLeft() const { return InputAt(0); }
3831 HInstruction* GetRight() const { return InputAt(1); }
3832 DataType::Type GetResultType() const { return GetType(); }
3833
3834 virtual bool IsCommutative() const { return false; }
3835
3836 // Put constant on the right.
3837 // Returns whether order is changed.
3838 bool OrderInputsWithConstantOnTheRight() {
3839 HInstruction* left = InputAt(0);
3840 HInstruction* right = InputAt(1);
3841 if (left->IsConstant() && !right->IsConstant()) {
3842 ReplaceInput(right, 0);
3843 ReplaceInput(left, 1);
3844 return true;
3845 }
3846 return false;
3847 }
3848
3849 // Order inputs by instruction id, but favor constant on the right side.
3850 // This helps GVN for commutative ops.
3851 void OrderInputs() {
3852 DCHECK(IsCommutative());
3853 HInstruction* left = InputAt(0);
3854 HInstruction* right = InputAt(1);
3855 if (left == right || (!left->IsConstant() && right->IsConstant())) {
3856 return;
3857 }
3858 if (OrderInputsWithConstantOnTheRight()) {
3859 return;
3860 }
3861 // Order according to instruction id.
3862 if (left->GetId() > right->GetId()) {
3863 ReplaceInput(right, 0);
3864 ReplaceInput(left, 1);
3865 }
3866 }
3867
3868 bool CanBeMoved() const override { return true; }
3869 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
3870 return true;
3871 }
3872
3873 // Try to statically evaluate `this` and return a HConstant
3874 // containing the result of this evaluation. If `this` cannot
3875 // be evaluated as a constant, return null.
3876 HConstant* TryStaticEvaluation() const;
3877
3878 // Apply this operation to `x` and `y`.
3879 virtual HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED,
3880 HNullConstant* y ATTRIBUTE_UNUSED) const {
3881 LOG(FATAL) << DebugName() << " is not defined for the (null, null) case.";
3882 UNREACHABLE();
3883 }
3884 virtual HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const = 0;
3885 virtual HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const = 0;
3886 virtual HConstant* Evaluate(HLongConstant* x ATTRIBUTE_UNUSED,
3887 HIntConstant* y ATTRIBUTE_UNUSED) const {
3888 LOG(FATAL) << DebugName() << " is not defined for the (long, int) case.";
3889 UNREACHABLE();
3890 }
3891 virtual HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const = 0;
3892 virtual HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const = 0;
3893
3894 // Returns an input that can legally be used as the right input and is
3895 // constant, or null.
3896 HConstant* GetConstantRight() const;
3897
3898 // If `GetConstantRight()` returns one of the input, this returns the other
3899 // one. Otherwise it returns null.
3900 HInstruction* GetLeastConstantLeft() const;
3901
3902 DECLARE_ABSTRACT_INSTRUCTION(BinaryOperation);
3903
3904 protected:
3905 DEFAULT_COPY_CONSTRUCTOR(BinaryOperation);
3906 };
3907
3908 // The comparison bias applies for floating point operations and indicates how NaN
3909 // comparisons are treated:
3910 enum class ComparisonBias { // private marker to avoid generate-operator-out.py from processing.
3911 kNoBias, // bias is not applicable (i.e. for long operation)
3912 kGtBias, // return 1 for NaN comparisons
3913 kLtBias, // return -1 for NaN comparisons
3914 kLast = kLtBias
3915 };
3916
3917 std::ostream& operator<<(std::ostream& os, ComparisonBias rhs);
3918
3919 class HCondition : public HBinaryOperation {
3920 public:
3921 HCondition(InstructionKind kind,
3922 HInstruction* first,
3923 HInstruction* second,
3924 uint32_t dex_pc = kNoDexPc)
3925 : HBinaryOperation(kind,
3926 DataType::Type::kBool,
3927 first,
3928 second,
3929 SideEffects::None(),
3930 dex_pc) {
3931 SetPackedField<ComparisonBiasField>(ComparisonBias::kNoBias);
3932 }
3933
3934 // For code generation purposes, returns whether this instruction is just before
3935 // `instruction`, and disregard moves in between.
3936 bool IsBeforeWhenDisregardMoves(HInstruction* instruction) const;
3937
3938 DECLARE_ABSTRACT_INSTRUCTION(Condition);
3939
3940 virtual IfCondition GetCondition() const = 0;
3941
3942 virtual IfCondition GetOppositeCondition() const = 0;
3943
3944 bool IsGtBias() const { return GetBias() == ComparisonBias::kGtBias; }
3945 bool IsLtBias() const { return GetBias() == ComparisonBias::kLtBias; }
3946
3947 ComparisonBias GetBias() const { return GetPackedField<ComparisonBiasField>(); }
3948 void SetBias(ComparisonBias bias) { SetPackedField<ComparisonBiasField>(bias); }
3949
3950 bool InstructionDataEquals(const HInstruction* other) const override {
3951 return GetPackedFields() == other->AsCondition()->GetPackedFields();
3952 }
3953
3954 bool IsFPConditionTrueIfNaN() const {
3955 DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
3956 IfCondition if_cond = GetCondition();
3957 if (if_cond == kCondNE) {
3958 return true;
3959 } else if (if_cond == kCondEQ) {
3960 return false;
3961 }
3962 return ((if_cond == kCondGT) || (if_cond == kCondGE)) && IsGtBias();
3963 }
3964
3965 bool IsFPConditionFalseIfNaN() const {
3966 DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
3967 IfCondition if_cond = GetCondition();
3968 if (if_cond == kCondEQ) {
3969 return true;
3970 } else if (if_cond == kCondNE) {
3971 return false;
3972 }
3973 return ((if_cond == kCondLT) || (if_cond == kCondLE)) && IsGtBias();
3974 }
3975
3976 protected:
3977 // Needed if we merge a HCompare into a HCondition.
3978 static constexpr size_t kFieldComparisonBias = kNumberOfGenericPackedBits;
3979 static constexpr size_t kFieldComparisonBiasSize =
3980 MinimumBitsToStore(static_cast<size_t>(ComparisonBias::kLast));
3981 static constexpr size_t kNumberOfConditionPackedBits =
3982 kFieldComparisonBias + kFieldComparisonBiasSize;
3983 static_assert(kNumberOfConditionPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
3984 using ComparisonBiasField =
3985 BitField<ComparisonBias, kFieldComparisonBias, kFieldComparisonBiasSize>;
3986
3987 template <typename T>
3988 int32_t Compare(T x, T y) const { return x > y ? 1 : (x < y ? -1 : 0); }
3989
3990 template <typename T>
3991 int32_t CompareFP(T x, T y) const {
3992 DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
3993 DCHECK_NE(GetBias(), ComparisonBias::kNoBias);
3994 // Handle the bias.
3995 return std::isunordered(x, y) ? (IsGtBias() ? 1 : -1) : Compare(x, y);
3996 }
3997
3998 // Return an integer constant containing the result of a condition evaluated at compile time.
3999 HIntConstant* MakeConstantCondition(bool value, uint32_t dex_pc) const {
4000 return GetBlock()->GetGraph()->GetIntConstant(value, dex_pc);
4001 }
4002
4003 DEFAULT_COPY_CONSTRUCTOR(Condition);
4004 };
4005
4006 // Instruction to check if two inputs are equal to each other.
4007 class HEqual final : public HCondition {
4008 public:
4009 HEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4010 : HCondition(kEqual, first, second, dex_pc) {
4011 }
4012
4013 bool IsCommutative() const override { return true; }
4014
4015 HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED,
4016 HNullConstant* y ATTRIBUTE_UNUSED) const override {
4017 return MakeConstantCondition(true, GetDexPc());
4018 }
4019 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4020 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4021 }
4022 // In the following Evaluate methods, a HCompare instruction has
4023 // been merged into this HEqual instruction; evaluate it as
4024 // `Compare(x, y) == 0`.
4025 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4026 return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0),
4027 GetDexPc());
4028 }
4029 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4030 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4031 }
4032 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4033 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4034 }
4035
4036 DECLARE_INSTRUCTION(Equal);
4037
4038 IfCondition GetCondition() const override {
4039 return kCondEQ;
4040 }
4041
4042 IfCondition GetOppositeCondition() const override {
4043 return kCondNE;
4044 }
4045
4046 protected:
4047 DEFAULT_COPY_CONSTRUCTOR(Equal);
4048
4049 private:
4050 template <typename T> static bool Compute(T x, T y) { return x == y; }
4051 };
4052
4053 class HNotEqual final : public HCondition {
4054 public:
4055 HNotEqual(HInstruction* first, HInstruction* second,
4056 uint32_t dex_pc = kNoDexPc)
4057 : HCondition(kNotEqual, first, second, dex_pc) {
4058 }
4059
4060 bool IsCommutative() const override { return true; }
4061
4062 HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED,
4063 HNullConstant* y ATTRIBUTE_UNUSED) const override {
4064 return MakeConstantCondition(false, GetDexPc());
4065 }
4066 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4067 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4068 }
4069 // In the following Evaluate methods, a HCompare instruction has
4070 // been merged into this HNotEqual instruction; evaluate it as
4071 // `Compare(x, y) != 0`.
4072 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4073 return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
4074 }
4075 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4076 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4077 }
4078 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4079 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4080 }
4081
4082 DECLARE_INSTRUCTION(NotEqual);
4083
4084 IfCondition GetCondition() const override {
4085 return kCondNE;
4086 }
4087
4088 IfCondition GetOppositeCondition() const override {
4089 return kCondEQ;
4090 }
4091
4092 protected:
4093 DEFAULT_COPY_CONSTRUCTOR(NotEqual);
4094
4095 private:
4096 template <typename T> static bool Compute(T x, T y) { return x != y; }
4097 };
4098
4099 class HLessThan final : public HCondition {
4100 public:
4101 HLessThan(HInstruction* first, HInstruction* second,
4102 uint32_t dex_pc = kNoDexPc)
4103 : HCondition(kLessThan, first, second, dex_pc) {
4104 }
4105
4106 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4107 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4108 }
4109 // In the following Evaluate methods, a HCompare instruction has
4110 // been merged into this HLessThan instruction; evaluate it as
4111 // `Compare(x, y) < 0`.
4112 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4113 return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
4114 }
4115 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4116 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4117 }
4118 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4119 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4120 }
4121
4122 DECLARE_INSTRUCTION(LessThan);
4123
4124 IfCondition GetCondition() const override {
4125 return kCondLT;
4126 }
4127
4128 IfCondition GetOppositeCondition() const override {
4129 return kCondGE;
4130 }
4131
4132 protected:
4133 DEFAULT_COPY_CONSTRUCTOR(LessThan);
4134
4135 private:
4136 template <typename T> static bool Compute(T x, T y) { return x < y; }
4137 };
4138
4139 class HLessThanOrEqual final : public HCondition {
4140 public:
4141 HLessThanOrEqual(HInstruction* first, HInstruction* second,
4142 uint32_t dex_pc = kNoDexPc)
4143 : HCondition(kLessThanOrEqual, first, second, dex_pc) {
4144 }
4145
4146 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4147 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4148 }
4149 // In the following Evaluate methods, a HCompare instruction has
4150 // been merged into this HLessThanOrEqual instruction; evaluate it as
4151 // `Compare(x, y) <= 0`.
4152 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4153 return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
4154 }
4155 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4156 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4157 }
4158 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4159 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4160 }
4161
4162 DECLARE_INSTRUCTION(LessThanOrEqual);
4163
4164 IfCondition GetCondition() const override {
4165 return kCondLE;
4166 }
4167
4168 IfCondition GetOppositeCondition() const override {
4169 return kCondGT;
4170 }
4171
4172 protected:
4173 DEFAULT_COPY_CONSTRUCTOR(LessThanOrEqual);
4174
4175 private:
4176 template <typename T> static bool Compute(T x, T y) { return x <= y; }
4177 };
4178
4179 class HGreaterThan final : public HCondition {
4180 public:
4181 HGreaterThan(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4182 : HCondition(kGreaterThan, first, second, dex_pc) {
4183 }
4184
4185 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4186 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4187 }
4188 // In the following Evaluate methods, a HCompare instruction has
4189 // been merged into this HGreaterThan instruction; evaluate it as
4190 // `Compare(x, y) > 0`.
4191 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4192 return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
4193 }
4194 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4195 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4196 }
4197 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4198 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4199 }
4200
4201 DECLARE_INSTRUCTION(GreaterThan);
4202
4203 IfCondition GetCondition() const override {
4204 return kCondGT;
4205 }
4206
4207 IfCondition GetOppositeCondition() const override {
4208 return kCondLE;
4209 }
4210
4211 protected:
4212 DEFAULT_COPY_CONSTRUCTOR(GreaterThan);
4213
4214 private:
4215 template <typename T> static bool Compute(T x, T y) { return x > y; }
4216 };
4217
4218 class HGreaterThanOrEqual final : public HCondition {
4219 public:
4220 HGreaterThanOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4221 : HCondition(kGreaterThanOrEqual, first, second, dex_pc) {
4222 }
4223
4224 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4225 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4226 }
4227 // In the following Evaluate methods, a HCompare instruction has
4228 // been merged into this HGreaterThanOrEqual instruction; evaluate it as
4229 // `Compare(x, y) >= 0`.
4230 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4231 return MakeConstantCondition(Compute(Compare(x->GetValue(), y->GetValue()), 0), GetDexPc());
4232 }
4233 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4234 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4235 }
4236 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4237 return MakeConstantCondition(Compute(CompareFP(x->GetValue(), y->GetValue()), 0), GetDexPc());
4238 }
4239
4240 DECLARE_INSTRUCTION(GreaterThanOrEqual);
4241
4242 IfCondition GetCondition() const override {
4243 return kCondGE;
4244 }
4245
4246 IfCondition GetOppositeCondition() const override {
4247 return kCondLT;
4248 }
4249
4250 protected:
4251 DEFAULT_COPY_CONSTRUCTOR(GreaterThanOrEqual);
4252
4253 private:
4254 template <typename T> static bool Compute(T x, T y) { return x >= y; }
4255 };
4256
4257 class HBelow final : public HCondition {
4258 public:
4259 HBelow(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4260 : HCondition(kBelow, first, second, dex_pc) {
4261 }
4262
4263 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4264 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4265 }
4266 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4267 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4268 }
4269 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
4270 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
4271 LOG(FATAL) << DebugName() << " is not defined for float values";
4272 UNREACHABLE();
4273 }
4274 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
4275 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
4276 LOG(FATAL) << DebugName() << " is not defined for double values";
4277 UNREACHABLE();
4278 }
4279
4280 DECLARE_INSTRUCTION(Below);
4281
4282 IfCondition GetCondition() const override {
4283 return kCondB;
4284 }
4285
4286 IfCondition GetOppositeCondition() const override {
4287 return kCondAE;
4288 }
4289
4290 protected:
4291 DEFAULT_COPY_CONSTRUCTOR(Below);
4292
4293 private:
4294 template <typename T> static bool Compute(T x, T y) {
4295 return MakeUnsigned(x) < MakeUnsigned(y);
4296 }
4297 };
4298
4299 class HBelowOrEqual final : public HCondition {
4300 public:
4301 HBelowOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4302 : HCondition(kBelowOrEqual, first, second, dex_pc) {
4303 }
4304
4305 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4306 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4307 }
4308 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4309 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4310 }
4311 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
4312 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
4313 LOG(FATAL) << DebugName() << " is not defined for float values";
4314 UNREACHABLE();
4315 }
4316 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
4317 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
4318 LOG(FATAL) << DebugName() << " is not defined for double values";
4319 UNREACHABLE();
4320 }
4321
4322 DECLARE_INSTRUCTION(BelowOrEqual);
4323
4324 IfCondition GetCondition() const override {
4325 return kCondBE;
4326 }
4327
4328 IfCondition GetOppositeCondition() const override {
4329 return kCondA;
4330 }
4331
4332 protected:
4333 DEFAULT_COPY_CONSTRUCTOR(BelowOrEqual);
4334
4335 private:
4336 template <typename T> static bool Compute(T x, T y) {
4337 return MakeUnsigned(x) <= MakeUnsigned(y);
4338 }
4339 };
4340
4341 class HAbove final : public HCondition {
4342 public:
4343 HAbove(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4344 : HCondition(kAbove, first, second, dex_pc) {
4345 }
4346
4347 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4348 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4349 }
4350 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4351 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4352 }
4353 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
4354 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
4355 LOG(FATAL) << DebugName() << " is not defined for float values";
4356 UNREACHABLE();
4357 }
4358 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
4359 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
4360 LOG(FATAL) << DebugName() << " is not defined for double values";
4361 UNREACHABLE();
4362 }
4363
4364 DECLARE_INSTRUCTION(Above);
4365
4366 IfCondition GetCondition() const override {
4367 return kCondA;
4368 }
4369
4370 IfCondition GetOppositeCondition() const override {
4371 return kCondBE;
4372 }
4373
4374 protected:
4375 DEFAULT_COPY_CONSTRUCTOR(Above);
4376
4377 private:
4378 template <typename T> static bool Compute(T x, T y) {
4379 return MakeUnsigned(x) > MakeUnsigned(y);
4380 }
4381 };
4382
4383 class HAboveOrEqual final : public HCondition {
4384 public:
4385 HAboveOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc)
4386 : HCondition(kAboveOrEqual, first, second, dex_pc) {
4387 }
4388
4389 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4390 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4391 }
4392 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4393 return MakeConstantCondition(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4394 }
4395 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
4396 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
4397 LOG(FATAL) << DebugName() << " is not defined for float values";
4398 UNREACHABLE();
4399 }
4400 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
4401 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
4402 LOG(FATAL) << DebugName() << " is not defined for double values";
4403 UNREACHABLE();
4404 }
4405
4406 DECLARE_INSTRUCTION(AboveOrEqual);
4407
4408 IfCondition GetCondition() const override {
4409 return kCondAE;
4410 }
4411
4412 IfCondition GetOppositeCondition() const override {
4413 return kCondB;
4414 }
4415
4416 protected:
4417 DEFAULT_COPY_CONSTRUCTOR(AboveOrEqual);
4418
4419 private:
4420 template <typename T> static bool Compute(T x, T y) {
4421 return MakeUnsigned(x) >= MakeUnsigned(y);
4422 }
4423 };
4424
4425 // Instruction to check how two inputs compare to each other.
4426 // Result is 0 if input0 == input1, 1 if input0 > input1, or -1 if input0 < input1.
4427 class HCompare final : public HBinaryOperation {
4428 public:
4429 // Note that `comparison_type` is the type of comparison performed
4430 // between the comparison's inputs, not the type of the instantiated
4431 // HCompare instruction (which is always DataType::Type::kInt).
4432 HCompare(DataType::Type comparison_type,
4433 HInstruction* first,
4434 HInstruction* second,
4435 ComparisonBias bias,
4436 uint32_t dex_pc)
4437 : HBinaryOperation(kCompare,
4438 DataType::Type::kInt32,
4439 first,
4440 second,
4441 SideEffectsForArchRuntimeCalls(comparison_type),
4442 dex_pc) {
4443 SetPackedField<ComparisonBiasField>(bias);
4444 }
4445
4446 template <typename T>
4447 int32_t Compute(T x, T y) const { return x > y ? 1 : (x < y ? -1 : 0); }
4448
4449 template <typename T>
4450 int32_t ComputeFP(T x, T y) const {
4451 DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
4452 DCHECK_NE(GetBias(), ComparisonBias::kNoBias);
4453 // Handle the bias.
4454 return std::isunordered(x, y) ? (IsGtBias() ? 1 : -1) : Compute(x, y);
4455 }
4456
4457 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
4458 // Note that there is no "cmp-int" Dex instruction so we shouldn't
4459 // reach this code path when processing a freshly built HIR
4460 // graph. However HCompare integer instructions can be synthesized
4461 // by the instruction simplifier to implement IntegerCompare and
4462 // IntegerSignum intrinsics, so we have to handle this case.
4463 return MakeConstantComparison(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4464 }
4465 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
4466 return MakeConstantComparison(Compute(x->GetValue(), y->GetValue()), GetDexPc());
4467 }
4468 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
4469 return MakeConstantComparison(ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
4470 }
4471 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
4472 return MakeConstantComparison(ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
4473 }
4474
4475 bool InstructionDataEquals(const HInstruction* other) const override {
4476 return GetPackedFields() == other->AsCompare()->GetPackedFields();
4477 }
4478
4479 ComparisonBias GetBias() const { return GetPackedField<ComparisonBiasField>(); }
4480
4481 // Does this compare instruction have a "gt bias" (vs an "lt bias")?
4482 // Only meaningful for floating-point comparisons.
4483 bool IsGtBias() const {
4484 DCHECK(DataType::IsFloatingPointType(InputAt(0)->GetType())) << InputAt(0)->GetType();
4485 return GetBias() == ComparisonBias::kGtBias;
4486 }
4487
4488 static SideEffects SideEffectsForArchRuntimeCalls(DataType::Type type ATTRIBUTE_UNUSED) {
4489 // Comparisons do not require a runtime call in any back end.
4490 return SideEffects::None();
4491 }
4492
4493 DECLARE_INSTRUCTION(Compare);
4494
4495 protected:
4496 static constexpr size_t kFieldComparisonBias = kNumberOfGenericPackedBits;
4497 static constexpr size_t kFieldComparisonBiasSize =
4498 MinimumBitsToStore(static_cast<size_t>(ComparisonBias::kLast));
4499 static constexpr size_t kNumberOfComparePackedBits =
4500 kFieldComparisonBias + kFieldComparisonBiasSize;
4501 static_assert(kNumberOfComparePackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
4502 using ComparisonBiasField =
4503 BitField<ComparisonBias, kFieldComparisonBias, kFieldComparisonBiasSize>;
4504
4505 // Return an integer constant containing the result of a comparison evaluated at compile time.
4506 HIntConstant* MakeConstantComparison(int32_t value, uint32_t dex_pc) const {
4507 DCHECK(value == -1 || value == 0 || value == 1) << value;
4508 return GetBlock()->GetGraph()->GetIntConstant(value, dex_pc);
4509 }
4510
4511 DEFAULT_COPY_CONSTRUCTOR(Compare);
4512 };
4513
4514 class HNewInstance final : public HExpression<1> {
4515 public:
4516 HNewInstance(HInstruction* cls,
4517 uint32_t dex_pc,
4518 dex::TypeIndex type_index,
4519 const DexFile& dex_file,
4520 bool finalizable,
4521 QuickEntrypointEnum entrypoint)
4522 : HExpression(kNewInstance,
4523 DataType::Type::kReference,
4524 SideEffects::CanTriggerGC(),
4525 dex_pc),
4526 type_index_(type_index),
4527 dex_file_(dex_file),
4528 entrypoint_(entrypoint) {
4529 SetPackedFlag<kFlagFinalizable>(finalizable);
4530 SetPackedFlag<kFlagPartialMaterialization>(false);
4531 SetRawInputAt(0, cls);
4532 }
4533
4534 bool IsClonable() const override { return true; }
4535
4536 void SetPartialMaterialization() {
4537 SetPackedFlag<kFlagPartialMaterialization>(true);
4538 }
4539
4540 dex::TypeIndex GetTypeIndex() const { return type_index_; }
4541 const DexFile& GetDexFile() const { return dex_file_; }
4542
4543 // Calls runtime so needs an environment.
4544 bool NeedsEnvironment() const override { return true; }
4545
4546 // Can throw errors when out-of-memory or if it's not instantiable/accessible.
4547 bool CanThrow() const override { return true; }
4548 bool OnlyThrowsAsyncExceptions() const override {
4549 return !IsFinalizable() && !NeedsChecks();
4550 }
4551
4552 bool NeedsChecks() const {
4553 return entrypoint_ == kQuickAllocObjectWithChecks;
4554 }
4555
4556 bool IsFinalizable() const { return GetPackedFlag<kFlagFinalizable>(); }
4557
4558 bool CanBeNull() const override { return false; }
4559
4560 bool IsPartialMaterialization() const {
4561 return GetPackedFlag<kFlagPartialMaterialization>();
4562 }
4563
4564 QuickEntrypointEnum GetEntrypoint() const { return entrypoint_; }
4565
4566 void SetEntrypoint(QuickEntrypointEnum entrypoint) {
4567 entrypoint_ = entrypoint;
4568 }
4569
4570 HLoadClass* GetLoadClass() const {
4571 HInstruction* input = InputAt(0);
4572 if (input->IsClinitCheck()) {
4573 input = input->InputAt(0);
4574 }
4575 DCHECK(input->IsLoadClass());
4576 return input->AsLoadClass();
4577 }
4578
4579 bool IsStringAlloc() const;
4580
4581 DECLARE_INSTRUCTION(NewInstance);
4582
4583 protected:
4584 DEFAULT_COPY_CONSTRUCTOR(NewInstance);
4585
4586 private:
4587 static constexpr size_t kFlagFinalizable = kNumberOfGenericPackedBits;
4588 static constexpr size_t kFlagPartialMaterialization = kFlagFinalizable + 1;
4589 static constexpr size_t kNumberOfNewInstancePackedBits = kFlagPartialMaterialization + 1;
4590 static_assert(kNumberOfNewInstancePackedBits <= kMaxNumberOfPackedBits,
4591 "Too many packed fields.");
4592
4593 const dex::TypeIndex type_index_;
4594 const DexFile& dex_file_;
4595 QuickEntrypointEnum entrypoint_;
4596 };
4597
4598 enum IntrinsicNeedsEnvironment {
4599 kNoEnvironment, // Intrinsic does not require an environment.
4600 kNeedsEnvironment // Intrinsic requires an environment.
4601 };
4602
4603 enum IntrinsicSideEffects {
4604 kNoSideEffects, // Intrinsic does not have any heap memory side effects.
4605 kReadSideEffects, // Intrinsic may read heap memory.
4606 kWriteSideEffects, // Intrinsic may write heap memory.
4607 kAllSideEffects // Intrinsic may read or write heap memory, or trigger GC.
4608 };
4609
4610 enum IntrinsicExceptions {
4611 kNoThrow, // Intrinsic does not throw any exceptions.
4612 kCanThrow // Intrinsic may throw exceptions.
4613 };
4614
4615 // Determines how to load an ArtMethod*.
4616 enum class MethodLoadKind {
4617 // Use a String init ArtMethod* loaded from Thread entrypoints.
4618 kStringInit,
4619
4620 // Use the method's own ArtMethod* loaded by the register allocator.
4621 kRecursive,
4622
4623 // Use PC-relative boot image ArtMethod* address that will be known at link time.
4624 // Used for boot image methods referenced by boot image code.
4625 kBootImageLinkTimePcRelative,
4626
4627 // Load from an entry in the .data.bimg.rel.ro using a PC-relative load.
4628 // Used for app->boot calls with relocatable image.
4629 kBootImageRelRo,
4630
4631 // Load from an entry in the .bss section using a PC-relative load.
4632 // Used for methods outside boot image referenced by AOT-compiled app and boot image code.
4633 kBssEntry,
4634
4635 // Use ArtMethod* at a known address, embed the direct address in the code.
4636 // Used for for JIT-compiled calls.
4637 kJitDirectAddress,
4638
4639 // Make a runtime call to resolve and call the method. This is the last-resort-kind
4640 // used when other kinds are unimplemented on a particular architecture.
4641 kRuntimeCall,
4642 };
4643
4644 // Determines the location of the code pointer of an invoke.
4645 enum class CodePtrLocation {
4646 // Recursive call, use local PC-relative call instruction.
4647 kCallSelf,
4648
4649 // Use native pointer from the Artmethod*.
4650 // Used for @CriticalNative to avoid going through the compiled stub. This call goes through
4651 // a special resolution stub if the class is not initialized or no native code is registered.
4652 kCallCriticalNative,
4653
4654 // Use code pointer from the ArtMethod*.
4655 // Used when we don't know the target code. This is also the last-resort-kind used when
4656 // other kinds are unimplemented or impractical (i.e. slow) on a particular architecture.
4657 kCallArtMethod,
4658 };
4659
4660 static inline bool IsPcRelativeMethodLoadKind(MethodLoadKind load_kind) {
4661 return load_kind == MethodLoadKind::kBootImageLinkTimePcRelative ||
4662 load_kind == MethodLoadKind::kBootImageRelRo ||
4663 load_kind == MethodLoadKind::kBssEntry;
4664 }
4665
4666 class HInvoke : public HVariableInputSizeInstruction {
4667 public:
4668 bool NeedsEnvironment() const override;
4669
4670 void SetArgumentAt(size_t index, HInstruction* argument) {
4671 SetRawInputAt(index, argument);
4672 }
4673
4674 // Return the number of arguments. This number can be lower than
4675 // the number of inputs returned by InputCount(), as some invoke
4676 // instructions (e.g. HInvokeStaticOrDirect) can have non-argument
4677 // inputs at the end of their list of inputs.
4678 uint32_t GetNumberOfArguments() const { return number_of_arguments_; }
4679
4680 InvokeType GetInvokeType() const {
4681 return GetPackedField<InvokeTypeField>();
4682 }
4683
4684 Intrinsics GetIntrinsic() const {
4685 return intrinsic_;
4686 }
4687
4688 void SetIntrinsic(Intrinsics intrinsic,
4689 IntrinsicNeedsEnvironment needs_env,
4690 IntrinsicSideEffects side_effects,
4691 IntrinsicExceptions exceptions);
4692
4693 bool IsFromInlinedInvoke() const {
4694 return GetEnvironment()->IsFromInlinedInvoke();
4695 }
4696
4697 void SetCanThrow(bool can_throw) { SetPackedFlag<kFlagCanThrow>(can_throw); }
4698
4699 bool CanThrow() const override { return GetPackedFlag<kFlagCanThrow>(); }
4700
4701 void SetAlwaysThrows(bool always_throws) { SetPackedFlag<kFlagAlwaysThrows>(always_throws); }
4702
4703 bool AlwaysThrows() const override { return GetPackedFlag<kFlagAlwaysThrows>(); }
4704
4705 bool CanBeMoved() const override { return IsIntrinsic() && !DoesAnyWrite(); }
4706
4707 bool InstructionDataEquals(const HInstruction* other) const override {
4708 return intrinsic_ != Intrinsics::kNone && intrinsic_ == other->AsInvoke()->intrinsic_;
4709 }
4710
4711 uint32_t* GetIntrinsicOptimizations() {
4712 return &intrinsic_optimizations_;
4713 }
4714
4715 const uint32_t* GetIntrinsicOptimizations() const {
4716 return &intrinsic_optimizations_;
4717 }
4718
4719 bool IsIntrinsic() const { return intrinsic_ != Intrinsics::kNone; }
4720
4721 ArtMethod* GetResolvedMethod() const { return resolved_method_; }
4722 void SetResolvedMethod(ArtMethod* method);
4723
4724 MethodReference GetMethodReference() const { return method_reference_; }
4725
4726 const MethodReference GetResolvedMethodReference() const {
4727 return resolved_method_reference_;
4728 }
4729
4730 DECLARE_ABSTRACT_INSTRUCTION(Invoke);
4731
4732 protected:
4733 static constexpr size_t kFieldInvokeType = kNumberOfGenericPackedBits;
4734 static constexpr size_t kFieldInvokeTypeSize =
4735 MinimumBitsToStore(static_cast<size_t>(kMaxInvokeType));
4736 static constexpr size_t kFlagCanThrow = kFieldInvokeType + kFieldInvokeTypeSize;
4737 static constexpr size_t kFlagAlwaysThrows = kFlagCanThrow + 1;
4738 static constexpr size_t kNumberOfInvokePackedBits = kFlagAlwaysThrows + 1;
4739 static_assert(kNumberOfInvokePackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
4740 using InvokeTypeField = BitField<InvokeType, kFieldInvokeType, kFieldInvokeTypeSize>;
4741
4742 HInvoke(InstructionKind kind,
4743 ArenaAllocator* allocator,
4744 uint32_t number_of_arguments,
4745 uint32_t number_of_other_inputs,
4746 DataType::Type return_type,
4747 uint32_t dex_pc,
4748 MethodReference method_reference,
4749 ArtMethod* resolved_method,
4750 MethodReference resolved_method_reference,
4751 InvokeType invoke_type)
4752 : HVariableInputSizeInstruction(
4753 kind,
4754 return_type,
4755 SideEffects::AllExceptGCDependency(), // Assume write/read on all fields/arrays.
4756 dex_pc,
4757 allocator,
4758 number_of_arguments + number_of_other_inputs,
4759 kArenaAllocInvokeInputs),
4760 number_of_arguments_(number_of_arguments),
4761 method_reference_(method_reference),
4762 resolved_method_reference_(resolved_method_reference),
4763 intrinsic_(Intrinsics::kNone),
4764 intrinsic_optimizations_(0) {
4765 SetPackedField<InvokeTypeField>(invoke_type);
4766 SetPackedFlag<kFlagCanThrow>(true);
4767 SetResolvedMethod(resolved_method);
4768 }
4769
4770 DEFAULT_COPY_CONSTRUCTOR(Invoke);
4771
4772 uint32_t number_of_arguments_;
4773 ArtMethod* resolved_method_;
4774 const MethodReference method_reference_;
4775 // Cached values of the resolved method, to avoid needing the mutator lock.
4776 const MethodReference resolved_method_reference_;
4777 Intrinsics intrinsic_;
4778
4779 // A magic word holding optimizations for intrinsics. See intrinsics.h.
4780 uint32_t intrinsic_optimizations_;
4781 };
4782
4783 class HInvokeUnresolved final : public HInvoke {
4784 public:
4785 HInvokeUnresolved(ArenaAllocator* allocator,
4786 uint32_t number_of_arguments,
4787 DataType::Type return_type,
4788 uint32_t dex_pc,
4789 MethodReference method_reference,
4790 InvokeType invoke_type)
4791 : HInvoke(kInvokeUnresolved,
4792 allocator,
4793 number_of_arguments,
4794 /* number_of_other_inputs= */ 0u,
4795 return_type,
4796 dex_pc,
4797 method_reference,
4798 nullptr,
4799 MethodReference(nullptr, 0u),
4800 invoke_type) {
4801 }
4802
4803 bool IsClonable() const override { return true; }
4804
4805 DECLARE_INSTRUCTION(InvokeUnresolved);
4806
4807 protected:
4808 DEFAULT_COPY_CONSTRUCTOR(InvokeUnresolved);
4809 };
4810
4811 class HInvokePolymorphic final : public HInvoke {
4812 public:
4813 HInvokePolymorphic(ArenaAllocator* allocator,
4814 uint32_t number_of_arguments,
4815 DataType::Type return_type,
4816 uint32_t dex_pc,
4817 MethodReference method_reference,
4818 // resolved_method is the ArtMethod object corresponding to the polymorphic
4819 // method (e.g. VarHandle.get), resolved using the class linker. It is needed
4820 // to pass intrinsic information to the HInvokePolymorphic node.
4821 ArtMethod* resolved_method,
4822 MethodReference resolved_method_reference,
4823 dex::ProtoIndex proto_idx)
4824 : HInvoke(kInvokePolymorphic,
4825 allocator,
4826 number_of_arguments,
4827 /* number_of_other_inputs= */ 0u,
4828 return_type,
4829 dex_pc,
4830 method_reference,
4831 resolved_method,
4832 resolved_method_reference,
4833 kPolymorphic),
4834 proto_idx_(proto_idx) {
4835 }
4836
4837 bool IsClonable() const override { return true; }
4838
4839 dex::ProtoIndex GetProtoIndex() { return proto_idx_; }
4840
4841 DECLARE_INSTRUCTION(InvokePolymorphic);
4842
4843 protected:
4844 dex::ProtoIndex proto_idx_;
4845 DEFAULT_COPY_CONSTRUCTOR(InvokePolymorphic);
4846 };
4847
4848 class HInvokeCustom final : public HInvoke {
4849 public:
4850 HInvokeCustom(ArenaAllocator* allocator,
4851 uint32_t number_of_arguments,
4852 uint32_t call_site_index,
4853 DataType::Type return_type,
4854 uint32_t dex_pc,
4855 MethodReference method_reference)
4856 : HInvoke(kInvokeCustom,
4857 allocator,
4858 number_of_arguments,
4859 /* number_of_other_inputs= */ 0u,
4860 return_type,
4861 dex_pc,
4862 method_reference,
4863 /* resolved_method= */ nullptr,
4864 MethodReference(nullptr, 0u),
4865 kStatic),
4866 call_site_index_(call_site_index) {
4867 }
4868
4869 uint32_t GetCallSiteIndex() const { return call_site_index_; }
4870
4871 bool IsClonable() const override { return true; }
4872
4873 DECLARE_INSTRUCTION(InvokeCustom);
4874
4875 protected:
4876 DEFAULT_COPY_CONSTRUCTOR(InvokeCustom);
4877
4878 private:
4879 uint32_t call_site_index_;
4880 };
4881
4882 class HInvokeStaticOrDirect final : public HInvoke {
4883 public:
4884 // Requirements of this method call regarding the class
4885 // initialization (clinit) check of its declaring class.
4886 enum class ClinitCheckRequirement { // private marker to avoid generate-operator-out.py from processing.
4887 kNone, // Class already initialized.
4888 kExplicit, // Static call having explicit clinit check as last input.
4889 kImplicit, // Static call implicitly requiring a clinit check.
4890 kLast = kImplicit
4891 };
4892
4893 struct DispatchInfo {
4894 MethodLoadKind method_load_kind;
4895 CodePtrLocation code_ptr_location;
4896 // The method load data holds
4897 // - thread entrypoint offset for kStringInit method if this is a string init invoke.
4898 // Note that there are multiple string init methods, each having its own offset.
4899 // - the method address for kDirectAddress
4900 uint64_t method_load_data;
4901 };
4902
4903 HInvokeStaticOrDirect(ArenaAllocator* allocator,
4904 uint32_t number_of_arguments,
4905 DataType::Type return_type,
4906 uint32_t dex_pc,
4907 MethodReference method_reference,
4908 ArtMethod* resolved_method,
4909 DispatchInfo dispatch_info,
4910 InvokeType invoke_type,
4911 MethodReference resolved_method_reference,
4912 ClinitCheckRequirement clinit_check_requirement)
4913 : HInvoke(kInvokeStaticOrDirect,
4914 allocator,
4915 number_of_arguments,
4916 // There is potentially one extra argument for the HCurrentMethod input,
4917 // and one other if the clinit check is explicit. These can be removed later.
4918 (NeedsCurrentMethodInput(dispatch_info) ? 1u : 0u) +
4919 (clinit_check_requirement == ClinitCheckRequirement::kExplicit ? 1u : 0u),
4920 return_type,
4921 dex_pc,
4922 method_reference,
4923 resolved_method,
4924 resolved_method_reference,
4925 invoke_type),
4926 dispatch_info_(dispatch_info) {
4927 SetPackedField<ClinitCheckRequirementField>(clinit_check_requirement);
4928 }
4929
4930 bool IsClonable() const override { return true; }
4931 bool NeedsBss() const override {
4932 return GetMethodLoadKind() == MethodLoadKind::kBssEntry;
4933 }
4934
4935 void SetDispatchInfo(DispatchInfo dispatch_info) {
4936 bool had_current_method_input = HasCurrentMethodInput();
4937 bool needs_current_method_input = NeedsCurrentMethodInput(dispatch_info);
4938
4939 // Using the current method is the default and once we find a better
4940 // method load kind, we should not go back to using the current method.
4941 DCHECK(had_current_method_input || !needs_current_method_input);
4942
4943 if (had_current_method_input && !needs_current_method_input) {
4944 DCHECK_EQ(InputAt(GetCurrentMethodIndex()), GetBlock()->GetGraph()->GetCurrentMethod());
4945 RemoveInputAt(GetCurrentMethodIndex());
4946 }
4947 dispatch_info_ = dispatch_info;
4948 }
4949
4950 DispatchInfo GetDispatchInfo() const {
4951 return dispatch_info_;
4952 }
4953
4954 using HInstruction::GetInputRecords; // Keep the const version visible.
4955 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() override {
4956 ArrayRef<HUserRecord<HInstruction*>> input_records = HInvoke::GetInputRecords();
4957 if (kIsDebugBuild && IsStaticWithExplicitClinitCheck()) {
4958 DCHECK(!input_records.empty());
4959 DCHECK_GT(input_records.size(), GetNumberOfArguments());
4960 HInstruction* last_input = input_records.back().GetInstruction();
4961 // Note: `last_input` may be null during arguments setup.
4962 if (last_input != nullptr) {
4963 // `last_input` is the last input of a static invoke marked as having
4964 // an explicit clinit check. It must either be:
4965 // - an art::HClinitCheck instruction, set by art::HGraphBuilder; or
4966 // - an art::HLoadClass instruction, set by art::PrepareForRegisterAllocation.
4967 DCHECK(last_input->IsClinitCheck() || last_input->IsLoadClass()) << last_input->DebugName();
4968 }
4969 }
4970 return input_records;
4971 }
4972
4973 bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const override {
4974 // We do not access the method via object reference, so we cannot do an implicit null check.
4975 // TODO: for intrinsics we can generate implicit null checks.
4976 return false;
4977 }
4978
4979 bool CanBeNull() const override {
4980 return GetType() == DataType::Type::kReference && !IsStringInit();
4981 }
4982
4983 MethodLoadKind GetMethodLoadKind() const { return dispatch_info_.method_load_kind; }
4984 CodePtrLocation GetCodePtrLocation() const {
4985 // We do CHA analysis after sharpening. When a method has CHA inlining, it
4986 // cannot call itself, as if the CHA optmization is invalid we want to make
4987 // sure the method is never executed again. So, while sharpening can return
4988 // kCallSelf, we bypass it here if there is a CHA optimization.
4989 if (dispatch_info_.code_ptr_location == CodePtrLocation::kCallSelf &&
4990 GetBlock()->GetGraph()->HasShouldDeoptimizeFlag()) {
4991 return CodePtrLocation::kCallArtMethod;
4992 } else {
4993 return dispatch_info_.code_ptr_location;
4994 }
4995 }
4996 bool IsRecursive() const { return GetMethodLoadKind() == MethodLoadKind::kRecursive; }
4997 bool IsStringInit() const { return GetMethodLoadKind() == MethodLoadKind::kStringInit; }
4998 bool HasMethodAddress() const { return GetMethodLoadKind() == MethodLoadKind::kJitDirectAddress; }
4999 bool HasPcRelativeMethodLoadKind() const {
5000 return IsPcRelativeMethodLoadKind(GetMethodLoadKind());
5001 }
5002
5003 QuickEntrypointEnum GetStringInitEntryPoint() const {
5004 DCHECK(IsStringInit());
5005 return static_cast<QuickEntrypointEnum>(dispatch_info_.method_load_data);
5006 }
5007
5008 uint64_t GetMethodAddress() const {
5009 DCHECK(HasMethodAddress());
5010 return dispatch_info_.method_load_data;
5011 }
5012
5013 const DexFile& GetDexFileForPcRelativeDexCache() const;
5014
5015 ClinitCheckRequirement GetClinitCheckRequirement() const {
5016 return GetPackedField<ClinitCheckRequirementField>();
5017 }
5018
5019 // Is this instruction a call to a static method?
5020 bool IsStatic() const {
5021 return GetInvokeType() == kStatic;
5022 }
5023
5024 // Does this method load kind need the current method as an input?
5025 static bool NeedsCurrentMethodInput(DispatchInfo dispatch_info) {
5026 return dispatch_info.method_load_kind == MethodLoadKind::kRecursive ||
5027 dispatch_info.method_load_kind == MethodLoadKind::kRuntimeCall ||
5028 dispatch_info.code_ptr_location == CodePtrLocation::kCallCriticalNative;
5029 }
5030
5031 // Get the index of the current method input.
5032 size_t GetCurrentMethodIndex() const {
5033 DCHECK(HasCurrentMethodInput());
5034 return GetCurrentMethodIndexUnchecked();
5035 }
5036 size_t GetCurrentMethodIndexUnchecked() const {
5037 return GetNumberOfArguments();
5038 }
5039
5040 // Check if the method has a current method input.
5041 bool HasCurrentMethodInput() const {
5042 if (NeedsCurrentMethodInput(GetDispatchInfo())) {
5043 DCHECK(InputAt(GetCurrentMethodIndexUnchecked()) == nullptr || // During argument setup.
5044 InputAt(GetCurrentMethodIndexUnchecked())->IsCurrentMethod());
5045 return true;
5046 } else {
5047 DCHECK(InputCount() == GetCurrentMethodIndexUnchecked() ||
5048 InputAt(GetCurrentMethodIndexUnchecked()) == nullptr || // During argument setup.
5049 !InputAt(GetCurrentMethodIndexUnchecked())->IsCurrentMethod());
5050 return false;
5051 }
5052 }
5053
5054 // Get the index of the special input.
5055 size_t GetSpecialInputIndex() const {
5056 DCHECK(HasSpecialInput());
5057 return GetSpecialInputIndexUnchecked();
5058 }
5059 size_t GetSpecialInputIndexUnchecked() const {
5060 return GetNumberOfArguments() + (HasCurrentMethodInput() ? 1u : 0u);
5061 }
5062
5063 // Check if the method has a special input.
5064 bool HasSpecialInput() const {
5065 size_t other_inputs =
5066 GetSpecialInputIndexUnchecked() + (IsStaticWithExplicitClinitCheck() ? 1u : 0u);
5067 size_t input_count = InputCount();
5068 DCHECK_LE(input_count - other_inputs, 1u) << other_inputs << " " << input_count;
5069 return other_inputs != input_count;
5070 }
5071
5072 void AddSpecialInput(HInstruction* input) {
5073 // We allow only one special input.
5074 DCHECK(!HasSpecialInput());
5075 InsertInputAt(GetSpecialInputIndexUnchecked(), input);
5076 }
5077
5078 // Remove the HClinitCheck or the replacement HLoadClass (set as last input by
5079 // PrepareForRegisterAllocation::VisitClinitCheck() in lieu of the initial HClinitCheck)
5080 // instruction; only relevant for static calls with explicit clinit check.
5081 void RemoveExplicitClinitCheck(ClinitCheckRequirement new_requirement) {
5082 DCHECK(IsStaticWithExplicitClinitCheck());
5083 size_t last_input_index = inputs_.size() - 1u;
5084 HInstruction* last_input = inputs_.back().GetInstruction();
5085 DCHECK(last_input != nullptr);
5086 DCHECK(last_input->IsLoadClass() || last_input->IsClinitCheck()) << last_input->DebugName();
5087 RemoveAsUserOfInput(last_input_index);
5088 inputs_.pop_back();
5089 SetPackedField<ClinitCheckRequirementField>(new_requirement);
5090 DCHECK(!IsStaticWithExplicitClinitCheck());
5091 }
5092
5093 // Is this a call to a static method whose declaring class has an
5094 // explicit initialization check in the graph?
5095 bool IsStaticWithExplicitClinitCheck() const {
5096 return IsStatic() && (GetClinitCheckRequirement() == ClinitCheckRequirement::kExplicit);
5097 }
5098
5099 // Is this a call to a static method whose declaring class has an
5100 // implicit intialization check requirement?
5101 bool IsStaticWithImplicitClinitCheck() const {
5102 return IsStatic() && (GetClinitCheckRequirement() == ClinitCheckRequirement::kImplicit);
5103 }
5104
5105 DECLARE_INSTRUCTION(InvokeStaticOrDirect);
5106
5107 protected:
5108 DEFAULT_COPY_CONSTRUCTOR(InvokeStaticOrDirect);
5109
5110 private:
5111 static constexpr size_t kFieldClinitCheckRequirement = kNumberOfInvokePackedBits;
5112 static constexpr size_t kFieldClinitCheckRequirementSize =
5113 MinimumBitsToStore(static_cast<size_t>(ClinitCheckRequirement::kLast));
5114 static constexpr size_t kNumberOfInvokeStaticOrDirectPackedBits =
5115 kFieldClinitCheckRequirement + kFieldClinitCheckRequirementSize;
5116 static_assert(kNumberOfInvokeStaticOrDirectPackedBits <= kMaxNumberOfPackedBits,
5117 "Too many packed fields.");
5118 using ClinitCheckRequirementField = BitField<ClinitCheckRequirement,
5119 kFieldClinitCheckRequirement,
5120 kFieldClinitCheckRequirementSize>;
5121
5122 DispatchInfo dispatch_info_;
5123 };
5124 std::ostream& operator<<(std::ostream& os, MethodLoadKind rhs);
5125 std::ostream& operator<<(std::ostream& os, CodePtrLocation rhs);
5126 std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs);
5127
5128 class HInvokeVirtual final : public HInvoke {
5129 public:
5130 HInvokeVirtual(ArenaAllocator* allocator,
5131 uint32_t number_of_arguments,
5132 DataType::Type return_type,
5133 uint32_t dex_pc,
5134 MethodReference method_reference,
5135 ArtMethod* resolved_method,
5136 MethodReference resolved_method_reference,
5137 uint32_t vtable_index)
5138 : HInvoke(kInvokeVirtual,
5139 allocator,
5140 number_of_arguments,
5141 0u,
5142 return_type,
5143 dex_pc,
5144 method_reference,
5145 resolved_method,
5146 resolved_method_reference,
5147 kVirtual),
5148 vtable_index_(vtable_index) {
5149 }
5150
5151 bool IsClonable() const override { return true; }
5152
5153 bool CanBeNull() const override {
5154 switch (GetIntrinsic()) {
5155 case Intrinsics::kThreadCurrentThread:
5156 case Intrinsics::kStringBufferAppend:
5157 case Intrinsics::kStringBufferToString:
5158 case Intrinsics::kStringBuilderAppendObject:
5159 case Intrinsics::kStringBuilderAppendString:
5160 case Intrinsics::kStringBuilderAppendCharSequence:
5161 case Intrinsics::kStringBuilderAppendCharArray:
5162 case Intrinsics::kStringBuilderAppendBoolean:
5163 case Intrinsics::kStringBuilderAppendChar:
5164 case Intrinsics::kStringBuilderAppendInt:
5165 case Intrinsics::kStringBuilderAppendLong:
5166 case Intrinsics::kStringBuilderAppendFloat:
5167 case Intrinsics::kStringBuilderAppendDouble:
5168 case Intrinsics::kStringBuilderToString:
5169 return false;
5170 default:
5171 return HInvoke::CanBeNull();
5172 }
5173 }
5174
5175 bool CanDoImplicitNullCheckOn(HInstruction* obj) const override;
5176
5177 uint32_t GetVTableIndex() const { return vtable_index_; }
5178
5179 DECLARE_INSTRUCTION(InvokeVirtual);
5180
5181 protected:
5182 DEFAULT_COPY_CONSTRUCTOR(InvokeVirtual);
5183
5184 private:
5185 // Cached value of the resolved method, to avoid needing the mutator lock.
5186 const uint32_t vtable_index_;
5187 };
5188
5189 class HInvokeInterface final : public HInvoke {
5190 public:
5191 HInvokeInterface(ArenaAllocator* allocator,
5192 uint32_t number_of_arguments,
5193 DataType::Type return_type,
5194 uint32_t dex_pc,
5195 MethodReference method_reference,
5196 ArtMethod* resolved_method,
5197 MethodReference resolved_method_reference,
5198 uint32_t imt_index,
5199 MethodLoadKind load_kind)
5200 : HInvoke(kInvokeInterface,
5201 allocator,
5202 number_of_arguments + (NeedsCurrentMethod(load_kind) ? 1 : 0),
5203 0u,
5204 return_type,
5205 dex_pc,
5206 method_reference,
5207 resolved_method,
5208 resolved_method_reference,
5209 kInterface),
5210 imt_index_(imt_index),
5211 hidden_argument_load_kind_(load_kind) {
5212 }
5213
5214 static bool NeedsCurrentMethod(MethodLoadKind load_kind) {
5215 return load_kind == MethodLoadKind::kRecursive;
5216 }
5217
5218 bool IsClonable() const override { return true; }
5219 bool NeedsBss() const override {
5220 return GetHiddenArgumentLoadKind() == MethodLoadKind::kBssEntry;
5221 }
5222
5223 bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
5224 // TODO: Add implicit null checks in intrinsics.
5225 return (obj == InputAt(0)) && !IsIntrinsic();
5226 }
5227
5228 size_t GetSpecialInputIndex() const {
5229 return GetNumberOfArguments();
5230 }
5231
5232 void AddSpecialInput(HInstruction* input) {
5233 InsertInputAt(GetSpecialInputIndex(), input);
5234 }
5235
5236 uint32_t GetImtIndex() const { return imt_index_; }
5237 MethodLoadKind GetHiddenArgumentLoadKind() const { return hidden_argument_load_kind_; }
5238
5239 DECLARE_INSTRUCTION(InvokeInterface);
5240
5241 protected:
5242 DEFAULT_COPY_CONSTRUCTOR(InvokeInterface);
5243
5244 private:
5245 // Cached value of the resolved method, to avoid needing the mutator lock.
5246 const uint32_t imt_index_;
5247
5248 // How the hidden argument (the interface method) is being loaded.
5249 const MethodLoadKind hidden_argument_load_kind_;
5250 };
5251
5252 class HNeg final : public HUnaryOperation {
5253 public:
5254 HNeg(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
5255 : HUnaryOperation(kNeg, result_type, input, dex_pc) {
5256 DCHECK_EQ(result_type, DataType::Kind(input->GetType()));
5257 }
5258
5259 template <typename T> static T Compute(T x) { return -x; }
5260
5261 HConstant* Evaluate(HIntConstant* x) const override {
5262 return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc());
5263 }
5264 HConstant* Evaluate(HLongConstant* x) const override {
5265 return GetBlock()->GetGraph()->GetLongConstant(Compute(x->GetValue()), GetDexPc());
5266 }
5267 HConstant* Evaluate(HFloatConstant* x) const override {
5268 return GetBlock()->GetGraph()->GetFloatConstant(Compute(x->GetValue()), GetDexPc());
5269 }
5270 HConstant* Evaluate(HDoubleConstant* x) const override {
5271 return GetBlock()->GetGraph()->GetDoubleConstant(Compute(x->GetValue()), GetDexPc());
5272 }
5273
5274 DECLARE_INSTRUCTION(Neg);
5275
5276 protected:
5277 DEFAULT_COPY_CONSTRUCTOR(Neg);
5278 };
5279
5280 class HNewArray final : public HExpression<2> {
5281 public:
5282 HNewArray(HInstruction* cls, HInstruction* length, uint32_t dex_pc, size_t component_size_shift)
5283 : HExpression(kNewArray, DataType::Type::kReference, SideEffects::CanTriggerGC(), dex_pc) {
5284 SetRawInputAt(0, cls);
5285 SetRawInputAt(1, length);
5286 SetPackedField<ComponentSizeShiftField>(component_size_shift);
5287 }
5288
5289 bool IsClonable() const override { return true; }
5290
5291 // Calls runtime so needs an environment.
5292 bool NeedsEnvironment() const override { return true; }
5293
5294 // May throw NegativeArraySizeException, OutOfMemoryError, etc.
5295 bool CanThrow() const override { return true; }
5296
5297 bool CanBeNull() const override { return false; }
5298
5299 HLoadClass* GetLoadClass() const {
5300 DCHECK(InputAt(0)->IsLoadClass());
5301 return InputAt(0)->AsLoadClass();
5302 }
5303
5304 HInstruction* GetLength() const {
5305 return InputAt(1);
5306 }
5307
5308 size_t GetComponentSizeShift() {
5309 return GetPackedField<ComponentSizeShiftField>();
5310 }
5311
5312 DECLARE_INSTRUCTION(NewArray);
5313
5314 protected:
5315 DEFAULT_COPY_CONSTRUCTOR(NewArray);
5316
5317 private:
5318 static constexpr size_t kFieldComponentSizeShift = kNumberOfGenericPackedBits;
5319 static constexpr size_t kFieldComponentSizeShiftSize = MinimumBitsToStore(3u);
5320 static constexpr size_t kNumberOfNewArrayPackedBits =
5321 kFieldComponentSizeShift + kFieldComponentSizeShiftSize;
5322 static_assert(kNumberOfNewArrayPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
5323 using ComponentSizeShiftField =
5324 BitField<size_t, kFieldComponentSizeShift, kFieldComponentSizeShift>;
5325 };
5326
5327 class HAdd final : public HBinaryOperation {
5328 public:
5329 HAdd(DataType::Type result_type,
5330 HInstruction* left,
5331 HInstruction* right,
5332 uint32_t dex_pc = kNoDexPc)
5333 : HBinaryOperation(kAdd, result_type, left, right, SideEffects::None(), dex_pc) {
5334 }
5335
5336 bool IsCommutative() const override { return true; }
5337
5338 template <typename T> static T Compute(T x, T y) { return x + y; }
5339
5340 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5341 return GetBlock()->GetGraph()->GetIntConstant(
5342 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5343 }
5344 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5345 return GetBlock()->GetGraph()->GetLongConstant(
5346 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5347 }
5348 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
5349 return GetBlock()->GetGraph()->GetFloatConstant(
5350 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5351 }
5352 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
5353 return GetBlock()->GetGraph()->GetDoubleConstant(
5354 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5355 }
5356
5357 DECLARE_INSTRUCTION(Add);
5358
5359 protected:
5360 DEFAULT_COPY_CONSTRUCTOR(Add);
5361 };
5362
5363 class HSub final : public HBinaryOperation {
5364 public:
5365 HSub(DataType::Type result_type,
5366 HInstruction* left,
5367 HInstruction* right,
5368 uint32_t dex_pc = kNoDexPc)
5369 : HBinaryOperation(kSub, result_type, left, right, SideEffects::None(), dex_pc) {
5370 }
5371
5372 template <typename T> static T Compute(T x, T y) { return x - y; }
5373
5374 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5375 return GetBlock()->GetGraph()->GetIntConstant(
5376 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5377 }
5378 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5379 return GetBlock()->GetGraph()->GetLongConstant(
5380 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5381 }
5382 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
5383 return GetBlock()->GetGraph()->GetFloatConstant(
5384 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5385 }
5386 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
5387 return GetBlock()->GetGraph()->GetDoubleConstant(
5388 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5389 }
5390
5391 DECLARE_INSTRUCTION(Sub);
5392
5393 protected:
5394 DEFAULT_COPY_CONSTRUCTOR(Sub);
5395 };
5396
5397 class HMul final : public HBinaryOperation {
5398 public:
5399 HMul(DataType::Type result_type,
5400 HInstruction* left,
5401 HInstruction* right,
5402 uint32_t dex_pc = kNoDexPc)
5403 : HBinaryOperation(kMul, result_type, left, right, SideEffects::None(), dex_pc) {
5404 }
5405
5406 bool IsCommutative() const override { return true; }
5407
5408 template <typename T> static T Compute(T x, T y) { return x * y; }
5409
5410 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5411 return GetBlock()->GetGraph()->GetIntConstant(
5412 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5413 }
5414 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5415 return GetBlock()->GetGraph()->GetLongConstant(
5416 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5417 }
5418 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
5419 return GetBlock()->GetGraph()->GetFloatConstant(
5420 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5421 }
5422 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
5423 return GetBlock()->GetGraph()->GetDoubleConstant(
5424 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5425 }
5426
5427 DECLARE_INSTRUCTION(Mul);
5428
5429 protected:
5430 DEFAULT_COPY_CONSTRUCTOR(Mul);
5431 };
5432
5433 class HDiv final : public HBinaryOperation {
5434 public:
5435 HDiv(DataType::Type result_type,
5436 HInstruction* left,
5437 HInstruction* right,
5438 uint32_t dex_pc)
5439 : HBinaryOperation(kDiv, result_type, left, right, SideEffects::None(), dex_pc) {
5440 }
5441
5442 template <typename T>
5443 T ComputeIntegral(T x, T y) const {
5444 DCHECK(!DataType::IsFloatingPointType(GetType())) << GetType();
5445 // Our graph structure ensures we never have 0 for `y` during
5446 // constant folding.
5447 DCHECK_NE(y, 0);
5448 // Special case -1 to avoid getting a SIGFPE on x86(_64).
5449 return (y == -1) ? -x : x / y;
5450 }
5451
5452 template <typename T>
5453 T ComputeFP(T x, T y) const {
5454 DCHECK(DataType::IsFloatingPointType(GetType())) << GetType();
5455 return x / y;
5456 }
5457
5458 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5459 return GetBlock()->GetGraph()->GetIntConstant(
5460 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5461 }
5462 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5463 return GetBlock()->GetGraph()->GetLongConstant(
5464 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5465 }
5466 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
5467 return GetBlock()->GetGraph()->GetFloatConstant(
5468 ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
5469 }
5470 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
5471 return GetBlock()->GetGraph()->GetDoubleConstant(
5472 ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
5473 }
5474
5475 DECLARE_INSTRUCTION(Div);
5476
5477 protected:
5478 DEFAULT_COPY_CONSTRUCTOR(Div);
5479 };
5480
5481 class HRem final : public HBinaryOperation {
5482 public:
5483 HRem(DataType::Type result_type,
5484 HInstruction* left,
5485 HInstruction* right,
5486 uint32_t dex_pc)
5487 : HBinaryOperation(kRem, result_type, left, right, SideEffects::None(), dex_pc) {
5488 }
5489
5490 template <typename T>
5491 T ComputeIntegral(T x, T y) const {
5492 DCHECK(!DataType::IsFloatingPointType(GetType())) << GetType();
5493 // Our graph structure ensures we never have 0 for `y` during
5494 // constant folding.
5495 DCHECK_NE(y, 0);
5496 // Special case -1 to avoid getting a SIGFPE on x86(_64).
5497 return (y == -1) ? 0 : x % y;
5498 }
5499
5500 template <typename T>
5501 T ComputeFP(T x, T y) const {
5502 DCHECK(DataType::IsFloatingPointType(GetType())) << GetType();
5503 return std::fmod(x, y);
5504 }
5505
5506 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5507 return GetBlock()->GetGraph()->GetIntConstant(
5508 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5509 }
5510 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5511 return GetBlock()->GetGraph()->GetLongConstant(
5512 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5513 }
5514 HConstant* Evaluate(HFloatConstant* x, HFloatConstant* y) const override {
5515 return GetBlock()->GetGraph()->GetFloatConstant(
5516 ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
5517 }
5518 HConstant* Evaluate(HDoubleConstant* x, HDoubleConstant* y) const override {
5519 return GetBlock()->GetGraph()->GetDoubleConstant(
5520 ComputeFP(x->GetValue(), y->GetValue()), GetDexPc());
5521 }
5522
5523 DECLARE_INSTRUCTION(Rem);
5524
5525 protected:
5526 DEFAULT_COPY_CONSTRUCTOR(Rem);
5527 };
5528
5529 class HMin final : public HBinaryOperation {
5530 public:
5531 HMin(DataType::Type result_type,
5532 HInstruction* left,
5533 HInstruction* right,
5534 uint32_t dex_pc)
5535 : HBinaryOperation(kMin, result_type, left, right, SideEffects::None(), dex_pc) {}
5536
5537 bool IsCommutative() const override { return true; }
5538
5539 // Evaluation for integral values.
5540 template <typename T> static T ComputeIntegral(T x, T y) {
5541 return (x <= y) ? x : y;
5542 }
5543
5544 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5545 return GetBlock()->GetGraph()->GetIntConstant(
5546 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5547 }
5548 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5549 return GetBlock()->GetGraph()->GetLongConstant(
5550 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5551 }
5552 // TODO: Evaluation for floating-point values.
5553 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
5554 HFloatConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
5555 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
5556 HDoubleConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
5557
5558 DECLARE_INSTRUCTION(Min);
5559
5560 protected:
5561 DEFAULT_COPY_CONSTRUCTOR(Min);
5562 };
5563
5564 class HMax final : public HBinaryOperation {
5565 public:
5566 HMax(DataType::Type result_type,
5567 HInstruction* left,
5568 HInstruction* right,
5569 uint32_t dex_pc)
5570 : HBinaryOperation(kMax, result_type, left, right, SideEffects::None(), dex_pc) {}
5571
5572 bool IsCommutative() const override { return true; }
5573
5574 // Evaluation for integral values.
5575 template <typename T> static T ComputeIntegral(T x, T y) {
5576 return (x >= y) ? x : y;
5577 }
5578
5579 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5580 return GetBlock()->GetGraph()->GetIntConstant(
5581 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5582 }
5583 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5584 return GetBlock()->GetGraph()->GetLongConstant(
5585 ComputeIntegral(x->GetValue(), y->GetValue()), GetDexPc());
5586 }
5587 // TODO: Evaluation for floating-point values.
5588 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
5589 HFloatConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
5590 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
5591 HDoubleConstant* y ATTRIBUTE_UNUSED) const override { return nullptr; }
5592
5593 DECLARE_INSTRUCTION(Max);
5594
5595 protected:
5596 DEFAULT_COPY_CONSTRUCTOR(Max);
5597 };
5598
5599 class HAbs final : public HUnaryOperation {
5600 public:
5601 HAbs(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
5602 : HUnaryOperation(kAbs, result_type, input, dex_pc) {}
5603
5604 // Evaluation for integral values.
5605 template <typename T> static T ComputeIntegral(T x) {
5606 return x < 0 ? -x : x;
5607 }
5608
5609 // Evaluation for floating-point values.
5610 // Note, as a "quality of implementation", rather than pure "spec compliance",
5611 // we require that Math.abs() clears the sign bit (but changes nothing else)
5612 // for all floating-point numbers, including NaN (signaling NaN may become quiet though).
5613 // http://b/30758343
5614 template <typename T, typename S> static T ComputeFP(T x) {
5615 S bits = bit_cast<S, T>(x);
5616 return bit_cast<T, S>(bits & std::numeric_limits<S>::max());
5617 }
5618
5619 HConstant* Evaluate(HIntConstant* x) const override {
5620 return GetBlock()->GetGraph()->GetIntConstant(ComputeIntegral(x->GetValue()), GetDexPc());
5621 }
5622 HConstant* Evaluate(HLongConstant* x) const override {
5623 return GetBlock()->GetGraph()->GetLongConstant(ComputeIntegral(x->GetValue()), GetDexPc());
5624 }
5625 HConstant* Evaluate(HFloatConstant* x) const override {
5626 return GetBlock()->GetGraph()->GetFloatConstant(
5627 ComputeFP<float, int32_t>(x->GetValue()), GetDexPc());
5628 }
5629 HConstant* Evaluate(HDoubleConstant* x) const override {
5630 return GetBlock()->GetGraph()->GetDoubleConstant(
5631 ComputeFP<double, int64_t>(x->GetValue()), GetDexPc());
5632 }
5633
5634 DECLARE_INSTRUCTION(Abs);
5635
5636 protected:
5637 DEFAULT_COPY_CONSTRUCTOR(Abs);
5638 };
5639
5640 class HDivZeroCheck final : public HExpression<1> {
5641 public:
5642 // `HDivZeroCheck` can trigger GC, as it may call the `ArithmeticException`
5643 // constructor. However it can only do it on a fatal slow path so execution never returns to the
5644 // instruction following the current one; thus 'SideEffects::None()' is used.
5645 HDivZeroCheck(HInstruction* value, uint32_t dex_pc)
5646 : HExpression(kDivZeroCheck, value->GetType(), SideEffects::None(), dex_pc) {
5647 SetRawInputAt(0, value);
5648 }
5649
5650 bool IsClonable() const override { return true; }
5651 bool CanBeMoved() const override { return true; }
5652
5653 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
5654 return true;
5655 }
5656
5657 bool NeedsEnvironment() const override { return true; }
5658 bool CanThrow() const override { return true; }
5659
5660 DECLARE_INSTRUCTION(DivZeroCheck);
5661
5662 protected:
5663 DEFAULT_COPY_CONSTRUCTOR(DivZeroCheck);
5664 };
5665
5666 class HShl final : public HBinaryOperation {
5667 public:
5668 HShl(DataType::Type result_type,
5669 HInstruction* value,
5670 HInstruction* distance,
5671 uint32_t dex_pc = kNoDexPc)
5672 : HBinaryOperation(kShl, result_type, value, distance, SideEffects::None(), dex_pc) {
5673 DCHECK_EQ(result_type, DataType::Kind(value->GetType()));
5674 DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(distance->GetType()));
5675 }
5676
5677 template <typename T>
5678 static T Compute(T value, int32_t distance, int32_t max_shift_distance) {
5679 return value << (distance & max_shift_distance);
5680 }
5681
5682 HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
5683 return GetBlock()->GetGraph()->GetIntConstant(
5684 Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
5685 }
5686 HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
5687 return GetBlock()->GetGraph()->GetLongConstant(
5688 Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
5689 }
5690 HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
5691 HLongConstant* distance ATTRIBUTE_UNUSED) const override {
5692 LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
5693 UNREACHABLE();
5694 }
5695 HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
5696 HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
5697 LOG(FATAL) << DebugName() << " is not defined for float values";
5698 UNREACHABLE();
5699 }
5700 HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
5701 HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
5702 LOG(FATAL) << DebugName() << " is not defined for double values";
5703 UNREACHABLE();
5704 }
5705
5706 DECLARE_INSTRUCTION(Shl);
5707
5708 protected:
5709 DEFAULT_COPY_CONSTRUCTOR(Shl);
5710 };
5711
5712 class HShr final : public HBinaryOperation {
5713 public:
5714 HShr(DataType::Type result_type,
5715 HInstruction* value,
5716 HInstruction* distance,
5717 uint32_t dex_pc = kNoDexPc)
5718 : HBinaryOperation(kShr, result_type, value, distance, SideEffects::None(), dex_pc) {
5719 DCHECK_EQ(result_type, DataType::Kind(value->GetType()));
5720 DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(distance->GetType()));
5721 }
5722
5723 template <typename T>
5724 static T Compute(T value, int32_t distance, int32_t max_shift_distance) {
5725 return value >> (distance & max_shift_distance);
5726 }
5727
5728 HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
5729 return GetBlock()->GetGraph()->GetIntConstant(
5730 Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
5731 }
5732 HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
5733 return GetBlock()->GetGraph()->GetLongConstant(
5734 Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
5735 }
5736 HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
5737 HLongConstant* distance ATTRIBUTE_UNUSED) const override {
5738 LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
5739 UNREACHABLE();
5740 }
5741 HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
5742 HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
5743 LOG(FATAL) << DebugName() << " is not defined for float values";
5744 UNREACHABLE();
5745 }
5746 HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
5747 HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
5748 LOG(FATAL) << DebugName() << " is not defined for double values";
5749 UNREACHABLE();
5750 }
5751
5752 DECLARE_INSTRUCTION(Shr);
5753
5754 protected:
5755 DEFAULT_COPY_CONSTRUCTOR(Shr);
5756 };
5757
5758 class HUShr final : public HBinaryOperation {
5759 public:
5760 HUShr(DataType::Type result_type,
5761 HInstruction* value,
5762 HInstruction* distance,
5763 uint32_t dex_pc = kNoDexPc)
5764 : HBinaryOperation(kUShr, result_type, value, distance, SideEffects::None(), dex_pc) {
5765 DCHECK_EQ(result_type, DataType::Kind(value->GetType()));
5766 DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(distance->GetType()));
5767 }
5768
5769 template <typename T>
5770 static T Compute(T value, int32_t distance, int32_t max_shift_distance) {
5771 using V = std::make_unsigned_t<T>;
5772 V ux = static_cast<V>(value);
5773 return static_cast<T>(ux >> (distance & max_shift_distance));
5774 }
5775
5776 HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
5777 return GetBlock()->GetGraph()->GetIntConstant(
5778 Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
5779 }
5780 HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
5781 return GetBlock()->GetGraph()->GetLongConstant(
5782 Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
5783 }
5784 HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
5785 HLongConstant* distance ATTRIBUTE_UNUSED) const override {
5786 LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
5787 UNREACHABLE();
5788 }
5789 HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
5790 HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
5791 LOG(FATAL) << DebugName() << " is not defined for float values";
5792 UNREACHABLE();
5793 }
5794 HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
5795 HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
5796 LOG(FATAL) << DebugName() << " is not defined for double values";
5797 UNREACHABLE();
5798 }
5799
5800 DECLARE_INSTRUCTION(UShr);
5801
5802 protected:
5803 DEFAULT_COPY_CONSTRUCTOR(UShr);
5804 };
5805
5806 class HAnd final : public HBinaryOperation {
5807 public:
5808 HAnd(DataType::Type result_type,
5809 HInstruction* left,
5810 HInstruction* right,
5811 uint32_t dex_pc = kNoDexPc)
5812 : HBinaryOperation(kAnd, result_type, left, right, SideEffects::None(), dex_pc) {
5813 }
5814
5815 bool IsCommutative() const override { return true; }
5816
5817 template <typename T> static T Compute(T x, T y) { return x & y; }
5818
5819 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5820 return GetBlock()->GetGraph()->GetIntConstant(
5821 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5822 }
5823 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5824 return GetBlock()->GetGraph()->GetLongConstant(
5825 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5826 }
5827 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
5828 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
5829 LOG(FATAL) << DebugName() << " is not defined for float values";
5830 UNREACHABLE();
5831 }
5832 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
5833 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
5834 LOG(FATAL) << DebugName() << " is not defined for double values";
5835 UNREACHABLE();
5836 }
5837
5838 DECLARE_INSTRUCTION(And);
5839
5840 protected:
5841 DEFAULT_COPY_CONSTRUCTOR(And);
5842 };
5843
5844 class HOr final : public HBinaryOperation {
5845 public:
5846 HOr(DataType::Type result_type,
5847 HInstruction* left,
5848 HInstruction* right,
5849 uint32_t dex_pc = kNoDexPc)
5850 : HBinaryOperation(kOr, result_type, left, right, SideEffects::None(), dex_pc) {
5851 }
5852
5853 bool IsCommutative() const override { return true; }
5854
5855 template <typename T> static T Compute(T x, T y) { return x | y; }
5856
5857 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5858 return GetBlock()->GetGraph()->GetIntConstant(
5859 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5860 }
5861 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5862 return GetBlock()->GetGraph()->GetLongConstant(
5863 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5864 }
5865 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
5866 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
5867 LOG(FATAL) << DebugName() << " is not defined for float values";
5868 UNREACHABLE();
5869 }
5870 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
5871 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
5872 LOG(FATAL) << DebugName() << " is not defined for double values";
5873 UNREACHABLE();
5874 }
5875
5876 DECLARE_INSTRUCTION(Or);
5877
5878 protected:
5879 DEFAULT_COPY_CONSTRUCTOR(Or);
5880 };
5881
5882 class HXor final : public HBinaryOperation {
5883 public:
5884 HXor(DataType::Type result_type,
5885 HInstruction* left,
5886 HInstruction* right,
5887 uint32_t dex_pc = kNoDexPc)
5888 : HBinaryOperation(kXor, result_type, left, right, SideEffects::None(), dex_pc) {
5889 }
5890
5891 bool IsCommutative() const override { return true; }
5892
5893 template <typename T> static T Compute(T x, T y) { return x ^ y; }
5894
5895 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const override {
5896 return GetBlock()->GetGraph()->GetIntConstant(
5897 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5898 }
5899 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const override {
5900 return GetBlock()->GetGraph()->GetLongConstant(
5901 Compute(x->GetValue(), y->GetValue()), GetDexPc());
5902 }
5903 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED,
5904 HFloatConstant* y ATTRIBUTE_UNUSED) const override {
5905 LOG(FATAL) << DebugName() << " is not defined for float values";
5906 UNREACHABLE();
5907 }
5908 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED,
5909 HDoubleConstant* y ATTRIBUTE_UNUSED) const override {
5910 LOG(FATAL) << DebugName() << " is not defined for double values";
5911 UNREACHABLE();
5912 }
5913
5914 DECLARE_INSTRUCTION(Xor);
5915
5916 protected:
5917 DEFAULT_COPY_CONSTRUCTOR(Xor);
5918 };
5919
5920 class HRor final : public HBinaryOperation {
5921 public:
5922 HRor(DataType::Type result_type, HInstruction* value, HInstruction* distance)
5923 : HBinaryOperation(kRor, result_type, value, distance) {
5924 }
5925
5926 template <typename T>
5927 static T Compute(T value, int32_t distance, int32_t max_shift_value) {
5928 using V = std::make_unsigned_t<T>;
5929 V ux = static_cast<V>(value);
5930 if ((distance & max_shift_value) == 0) {
5931 return static_cast<T>(ux);
5932 } else {
5933 const V reg_bits = sizeof(T) * 8;
5934 return static_cast<T>(ux >> (distance & max_shift_value)) |
5935 (value << (reg_bits - (distance & max_shift_value)));
5936 }
5937 }
5938
5939 HConstant* Evaluate(HIntConstant* value, HIntConstant* distance) const override {
5940 return GetBlock()->GetGraph()->GetIntConstant(
5941 Compute(value->GetValue(), distance->GetValue(), kMaxIntShiftDistance), GetDexPc());
5942 }
5943 HConstant* Evaluate(HLongConstant* value, HIntConstant* distance) const override {
5944 return GetBlock()->GetGraph()->GetLongConstant(
5945 Compute(value->GetValue(), distance->GetValue(), kMaxLongShiftDistance), GetDexPc());
5946 }
5947 HConstant* Evaluate(HLongConstant* value ATTRIBUTE_UNUSED,
5948 HLongConstant* distance ATTRIBUTE_UNUSED) const override {
5949 LOG(FATAL) << DebugName() << " is not defined for the (long, long) case.";
5950 UNREACHABLE();
5951 }
5952 HConstant* Evaluate(HFloatConstant* value ATTRIBUTE_UNUSED,
5953 HFloatConstant* distance ATTRIBUTE_UNUSED) const override {
5954 LOG(FATAL) << DebugName() << " is not defined for float values";
5955 UNREACHABLE();
5956 }
5957 HConstant* Evaluate(HDoubleConstant* value ATTRIBUTE_UNUSED,
5958 HDoubleConstant* distance ATTRIBUTE_UNUSED) const override {
5959 LOG(FATAL) << DebugName() << " is not defined for double values";
5960 UNREACHABLE();
5961 }
5962
5963 DECLARE_INSTRUCTION(Ror);
5964
5965 protected:
5966 DEFAULT_COPY_CONSTRUCTOR(Ror);
5967 };
5968
5969 // The value of a parameter in this method. Its location depends on
5970 // the calling convention.
5971 class HParameterValue final : public HExpression<0> {
5972 public:
5973 HParameterValue(const DexFile& dex_file,
5974 dex::TypeIndex type_index,
5975 uint8_t index,
5976 DataType::Type parameter_type,
5977 bool is_this = false)
5978 : HExpression(kParameterValue, parameter_type, SideEffects::None(), kNoDexPc),
5979 dex_file_(dex_file),
5980 type_index_(type_index),
5981 index_(index) {
5982 SetPackedFlag<kFlagIsThis>(is_this);
5983 SetPackedFlag<kFlagCanBeNull>(!is_this);
5984 }
5985
5986 const DexFile& GetDexFile() const { return dex_file_; }
5987 dex::TypeIndex GetTypeIndex() const { return type_index_; }
5988 uint8_t GetIndex() const { return index_; }
5989 bool IsThis() const { return GetPackedFlag<kFlagIsThis>(); }
5990
5991 bool CanBeNull() const override { return GetPackedFlag<kFlagCanBeNull>(); }
5992 void SetCanBeNull(bool can_be_null) { SetPackedFlag<kFlagCanBeNull>(can_be_null); }
5993
5994 DECLARE_INSTRUCTION(ParameterValue);
5995
5996 protected:
5997 DEFAULT_COPY_CONSTRUCTOR(ParameterValue);
5998
5999 private:
6000 // Whether or not the parameter value corresponds to 'this' argument.
6001 static constexpr size_t kFlagIsThis = kNumberOfGenericPackedBits;
6002 static constexpr size_t kFlagCanBeNull = kFlagIsThis + 1;
6003 static constexpr size_t kNumberOfParameterValuePackedBits = kFlagCanBeNull + 1;
6004 static_assert(kNumberOfParameterValuePackedBits <= kMaxNumberOfPackedBits,
6005 "Too many packed fields.");
6006
6007 const DexFile& dex_file_;
6008 const dex::TypeIndex type_index_;
6009 // The index of this parameter in the parameters list. Must be less
6010 // than HGraph::number_of_in_vregs_.
6011 const uint8_t index_;
6012 };
6013
6014 class HNot final : public HUnaryOperation {
6015 public:
6016 HNot(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
6017 : HUnaryOperation(kNot, result_type, input, dex_pc) {
6018 }
6019
6020 bool CanBeMoved() const override { return true; }
6021 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6022 return true;
6023 }
6024
6025 template <typename T> static T Compute(T x) { return ~x; }
6026
6027 HConstant* Evaluate(HIntConstant* x) const override {
6028 return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc());
6029 }
6030 HConstant* Evaluate(HLongConstant* x) const override {
6031 return GetBlock()->GetGraph()->GetLongConstant(Compute(x->GetValue()), GetDexPc());
6032 }
6033 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED) const override {
6034 LOG(FATAL) << DebugName() << " is not defined for float values";
6035 UNREACHABLE();
6036 }
6037 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED) const override {
6038 LOG(FATAL) << DebugName() << " is not defined for double values";
6039 UNREACHABLE();
6040 }
6041
6042 DECLARE_INSTRUCTION(Not);
6043
6044 protected:
6045 DEFAULT_COPY_CONSTRUCTOR(Not);
6046 };
6047
6048 class HBooleanNot final : public HUnaryOperation {
6049 public:
6050 explicit HBooleanNot(HInstruction* input, uint32_t dex_pc = kNoDexPc)
6051 : HUnaryOperation(kBooleanNot, DataType::Type::kBool, input, dex_pc) {
6052 }
6053
6054 bool CanBeMoved() const override { return true; }
6055 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6056 return true;
6057 }
6058
6059 template <typename T> static bool Compute(T x) {
6060 DCHECK(IsUint<1>(x)) << x;
6061 return !x;
6062 }
6063
6064 HConstant* Evaluate(HIntConstant* x) const override {
6065 return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc());
6066 }
6067 HConstant* Evaluate(HLongConstant* x ATTRIBUTE_UNUSED) const override {
6068 LOG(FATAL) << DebugName() << " is not defined for long values";
6069 UNREACHABLE();
6070 }
6071 HConstant* Evaluate(HFloatConstant* x ATTRIBUTE_UNUSED) const override {
6072 LOG(FATAL) << DebugName() << " is not defined for float values";
6073 UNREACHABLE();
6074 }
6075 HConstant* Evaluate(HDoubleConstant* x ATTRIBUTE_UNUSED) const override {
6076 LOG(FATAL) << DebugName() << " is not defined for double values";
6077 UNREACHABLE();
6078 }
6079
6080 DECLARE_INSTRUCTION(BooleanNot);
6081
6082 protected:
6083 DEFAULT_COPY_CONSTRUCTOR(BooleanNot);
6084 };
6085
6086 class HTypeConversion final : public HExpression<1> {
6087 public:
6088 // Instantiate a type conversion of `input` to `result_type`.
6089 HTypeConversion(DataType::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc)
6090 : HExpression(kTypeConversion, result_type, SideEffects::None(), dex_pc) {
6091 SetRawInputAt(0, input);
6092 // Invariant: We should never generate a conversion to a Boolean value.
6093 DCHECK_NE(DataType::Type::kBool, result_type);
6094 }
6095
6096 HInstruction* GetInput() const { return InputAt(0); }
6097 DataType::Type GetInputType() const { return GetInput()->GetType(); }
6098 DataType::Type GetResultType() const { return GetType(); }
6099
6100 bool IsClonable() const override { return true; }
6101 bool CanBeMoved() const override { return true; }
6102 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6103 return true;
6104 }
6105 // Return whether the conversion is implicit. This includes conversion to the same type.
6106 bool IsImplicitConversion() const {
6107 return DataType::IsTypeConversionImplicit(GetInputType(), GetResultType());
6108 }
6109
6110 // Try to statically evaluate the conversion and return a HConstant
6111 // containing the result. If the input cannot be converted, return nullptr.
6112 HConstant* TryStaticEvaluation() const;
6113
6114 DECLARE_INSTRUCTION(TypeConversion);
6115
6116 protected:
6117 DEFAULT_COPY_CONSTRUCTOR(TypeConversion);
6118 };
6119
6120 static constexpr uint32_t kNoRegNumber = -1;
6121
6122 class HNullCheck final : public HExpression<1> {
6123 public:
6124 // `HNullCheck` can trigger GC, as it may call the `NullPointerException`
6125 // constructor. However it can only do it on a fatal slow path so execution never returns to the
6126 // instruction following the current one; thus 'SideEffects::None()' is used.
6127 HNullCheck(HInstruction* value, uint32_t dex_pc)
6128 : HExpression(kNullCheck, value->GetType(), SideEffects::None(), dex_pc) {
6129 SetRawInputAt(0, value);
6130 }
6131
6132 bool IsClonable() const override { return true; }
6133 bool CanBeMoved() const override { return true; }
6134 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6135 return true;
6136 }
6137
6138 bool NeedsEnvironment() const override { return true; }
6139
6140 bool CanThrow() const override { return true; }
6141
6142 bool CanBeNull() const override { return false; }
6143
6144 DECLARE_INSTRUCTION(NullCheck);
6145
6146 protected:
6147 DEFAULT_COPY_CONSTRUCTOR(NullCheck);
6148 };
6149
6150 // Embeds an ArtField and all the information required by the compiler. We cache
6151 // that information to avoid requiring the mutator lock every time we need it.
6152 class FieldInfo : public ValueObject {
6153 public:
6154 FieldInfo(ArtField* field,
6155 MemberOffset field_offset,
6156 DataType::Type field_type,
6157 bool is_volatile,
6158 uint32_t index,
6159 uint16_t declaring_class_def_index,
6160 const DexFile& dex_file)
6161 : field_(field),
6162 field_offset_(field_offset),
6163 field_type_(field_type),
6164 is_volatile_(is_volatile),
6165 index_(index),
6166 declaring_class_def_index_(declaring_class_def_index),
6167 dex_file_(dex_file) {}
6168
6169 ArtField* GetField() const { return field_; }
6170 MemberOffset GetFieldOffset() const { return field_offset_; }
6171 DataType::Type GetFieldType() const { return field_type_; }
6172 uint32_t GetFieldIndex() const { return index_; }
6173 uint16_t GetDeclaringClassDefIndex() const { return declaring_class_def_index_;}
6174 const DexFile& GetDexFile() const { return dex_file_; }
6175 bool IsVolatile() const { return is_volatile_; }
6176
6177 bool Equals(const FieldInfo& other) const {
6178 return field_ == other.field_ &&
6179 field_offset_ == other.field_offset_ &&
6180 field_type_ == other.field_type_ &&
6181 is_volatile_ == other.is_volatile_ &&
6182 index_ == other.index_ &&
6183 declaring_class_def_index_ == other.declaring_class_def_index_ &&
6184 &dex_file_ == &other.dex_file_;
6185 }
6186
6187 std::ostream& Dump(std::ostream& os) const {
6188 os << field_ << ", off: " << field_offset_ << ", type: " << field_type_
6189 << ", volatile: " << std::boolalpha << is_volatile_ << ", index_: " << std::dec << index_
6190 << ", declaring_class: " << declaring_class_def_index_ << ", dex: " << dex_file_;
6191 return os;
6192 }
6193
6194 private:
6195 ArtField* const field_;
6196 const MemberOffset field_offset_;
6197 const DataType::Type field_type_;
6198 const bool is_volatile_;
6199 const uint32_t index_;
6200 const uint16_t declaring_class_def_index_;
6201 const DexFile& dex_file_;
6202 };
6203
6204 inline bool operator==(const FieldInfo& a, const FieldInfo& b) {
6205 return a.Equals(b);
6206 }
6207
6208 inline std::ostream& operator<<(std::ostream& os, const FieldInfo& a) {
6209 return a.Dump(os);
6210 }
6211
6212 class HInstanceFieldGet final : public HExpression<1> {
6213 public:
6214 HInstanceFieldGet(HInstruction* value,
6215 ArtField* field,
6216 DataType::Type field_type,
6217 MemberOffset field_offset,
6218 bool is_volatile,
6219 uint32_t field_idx,
6220 uint16_t declaring_class_def_index,
6221 const DexFile& dex_file,
6222 uint32_t dex_pc)
6223 : HExpression(kInstanceFieldGet,
6224 field_type,
6225 SideEffects::FieldReadOfType(field_type, is_volatile),
6226 dex_pc),
6227 field_info_(field,
6228 field_offset,
6229 field_type,
6230 is_volatile,
6231 field_idx,
6232 declaring_class_def_index,
6233 dex_file) {
6234 SetRawInputAt(0, value);
6235 }
6236
6237 bool IsClonable() const override { return true; }
6238 bool CanBeMoved() const override { return !IsVolatile(); }
6239
6240 bool InstructionDataEquals(const HInstruction* other) const override {
6241 const HInstanceFieldGet* other_get = other->AsInstanceFieldGet();
6242 return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue();
6243 }
6244
6245 bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
6246 return (obj == InputAt(0)) && art::CanDoImplicitNullCheckOn(GetFieldOffset().Uint32Value());
6247 }
6248
6249 size_t ComputeHashCode() const override {
6250 return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue();
6251 }
6252
6253 bool IsFieldAccess() const override { return true; }
6254 const FieldInfo& GetFieldInfo() const override { return field_info_; }
6255 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
6256 DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
6257 bool IsVolatile() const { return field_info_.IsVolatile(); }
6258
6259 void SetType(DataType::Type new_type) {
6260 DCHECK(DataType::IsIntegralType(GetType()));
6261 DCHECK(DataType::IsIntegralType(new_type));
6262 DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
6263 SetPackedField<TypeField>(new_type);
6264 }
6265
6266 DECLARE_INSTRUCTION(InstanceFieldGet);
6267
6268 protected:
6269 DEFAULT_COPY_CONSTRUCTOR(InstanceFieldGet);
6270
6271 private:
6272 const FieldInfo field_info_;
6273 };
6274
6275 class HPredicatedInstanceFieldGet final : public HExpression<2> {
6276 public:
6277 HPredicatedInstanceFieldGet(HInstanceFieldGet* orig,
6278 HInstruction* target,
6279 HInstruction* default_val)
6280 : HExpression(kPredicatedInstanceFieldGet,
6281 orig->GetFieldType(),
6282 orig->GetSideEffects(),
6283 orig->GetDexPc()),
6284 field_info_(orig->GetFieldInfo()) {
6285 // NB Default-val is at 0 so we can avoid doing a move.
6286 SetRawInputAt(1, target);
6287 SetRawInputAt(0, default_val);
6288 }
6289
6290 HPredicatedInstanceFieldGet(HInstruction* value,
6291 ArtField* field,
6292 HInstruction* default_value,
6293 DataType::Type field_type,
6294 MemberOffset field_offset,
6295 bool is_volatile,
6296 uint32_t field_idx,
6297 uint16_t declaring_class_def_index,
6298 const DexFile& dex_file,
6299 uint32_t dex_pc)
6300 : HExpression(kPredicatedInstanceFieldGet,
6301 field_type,
6302 SideEffects::FieldReadOfType(field_type, is_volatile),
6303 dex_pc),
6304 field_info_(field,
6305 field_offset,
6306 field_type,
6307 is_volatile,
6308 field_idx,
6309 declaring_class_def_index,
6310 dex_file) {
6311 SetRawInputAt(1, value);
6312 SetRawInputAt(0, default_value);
6313 }
6314
6315 bool IsClonable() const override {
6316 return true;
6317 }
6318 bool CanBeMoved() const override {
6319 return !IsVolatile();
6320 }
6321
6322 HInstruction* GetDefaultValue() const {
6323 return InputAt(0);
6324 }
6325 HInstruction* GetTarget() const {
6326 return InputAt(1);
6327 }
6328
6329 bool InstructionDataEquals(const HInstruction* other) const override {
6330 const HPredicatedInstanceFieldGet* other_get = other->AsPredicatedInstanceFieldGet();
6331 return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue() &&
6332 GetDefaultValue() == other_get->GetDefaultValue();
6333 }
6334
6335 bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
6336 return (obj == InputAt(0)) && art::CanDoImplicitNullCheckOn(GetFieldOffset().Uint32Value());
6337 }
6338
6339 size_t ComputeHashCode() const override {
6340 return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue();
6341 }
6342
6343 bool IsFieldAccess() const override { return true; }
6344 const FieldInfo& GetFieldInfo() const override { return field_info_; }
6345 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
6346 DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
6347 bool IsVolatile() const { return field_info_.IsVolatile(); }
6348
6349 void SetType(DataType::Type new_type) {
6350 DCHECK(DataType::IsIntegralType(GetType()));
6351 DCHECK(DataType::IsIntegralType(new_type));
6352 DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
6353 SetPackedField<TypeField>(new_type);
6354 }
6355
6356 DECLARE_INSTRUCTION(PredicatedInstanceFieldGet);
6357
6358 protected:
6359 DEFAULT_COPY_CONSTRUCTOR(PredicatedInstanceFieldGet);
6360
6361 private:
6362 const FieldInfo field_info_;
6363 };
6364
6365 class HInstanceFieldSet final : public HExpression<2> {
6366 public:
6367 HInstanceFieldSet(HInstruction* object,
6368 HInstruction* value,
6369 ArtField* field,
6370 DataType::Type field_type,
6371 MemberOffset field_offset,
6372 bool is_volatile,
6373 uint32_t field_idx,
6374 uint16_t declaring_class_def_index,
6375 const DexFile& dex_file,
6376 uint32_t dex_pc)
6377 : HExpression(kInstanceFieldSet,
6378 SideEffects::FieldWriteOfType(field_type, is_volatile),
6379 dex_pc),
6380 field_info_(field,
6381 field_offset,
6382 field_type,
6383 is_volatile,
6384 field_idx,
6385 declaring_class_def_index,
6386 dex_file) {
6387 SetPackedFlag<kFlagValueCanBeNull>(true);
6388 SetPackedFlag<kFlagIsPredicatedSet>(false);
6389 SetRawInputAt(0, object);
6390 SetRawInputAt(1, value);
6391 }
6392
6393 bool IsClonable() const override { return true; }
6394
6395 bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
6396 return (obj == InputAt(0)) && art::CanDoImplicitNullCheckOn(GetFieldOffset().Uint32Value());
6397 }
6398
6399 bool IsFieldAccess() const override { return true; }
6400 const FieldInfo& GetFieldInfo() const override { return field_info_; }
6401 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
6402 DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
6403 bool IsVolatile() const { return field_info_.IsVolatile(); }
6404 HInstruction* GetValue() const { return InputAt(1); }
6405 bool GetValueCanBeNull() const { return GetPackedFlag<kFlagValueCanBeNull>(); }
6406 void ClearValueCanBeNull() { SetPackedFlag<kFlagValueCanBeNull>(false); }
6407 bool GetIsPredicatedSet() const { return GetPackedFlag<kFlagIsPredicatedSet>(); }
6408 void SetIsPredicatedSet(bool value = true) { SetPackedFlag<kFlagIsPredicatedSet>(value); }
6409
6410 DECLARE_INSTRUCTION(InstanceFieldSet);
6411
6412 protected:
6413 DEFAULT_COPY_CONSTRUCTOR(InstanceFieldSet);
6414
6415 private:
6416 static constexpr size_t kFlagValueCanBeNull = kNumberOfGenericPackedBits;
6417 static constexpr size_t kFlagIsPredicatedSet = kFlagValueCanBeNull + 1;
6418 static constexpr size_t kNumberOfInstanceFieldSetPackedBits = kFlagIsPredicatedSet + 1;
6419 static_assert(kNumberOfInstanceFieldSetPackedBits <= kMaxNumberOfPackedBits,
6420 "Too many packed fields.");
6421
6422 const FieldInfo field_info_;
6423 };
6424
6425 class HArrayGet final : public HExpression<2> {
6426 public:
6427 HArrayGet(HInstruction* array,
6428 HInstruction* index,
6429 DataType::Type type,
6430 uint32_t dex_pc)
6431 : HArrayGet(array,
6432 index,
6433 type,
6434 SideEffects::ArrayReadOfType(type),
6435 dex_pc,
6436 /* is_string_char_at= */ false) {
6437 }
6438
6439 HArrayGet(HInstruction* array,
6440 HInstruction* index,
6441 DataType::Type type,
6442 SideEffects side_effects,
6443 uint32_t dex_pc,
6444 bool is_string_char_at)
6445 : HExpression(kArrayGet, type, side_effects, dex_pc) {
6446 SetPackedFlag<kFlagIsStringCharAt>(is_string_char_at);
6447 SetRawInputAt(0, array);
6448 SetRawInputAt(1, index);
6449 }
6450
6451 bool IsClonable() const override { return true; }
6452 bool CanBeMoved() const override { return true; }
6453 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6454 return true;
6455 }
6456 bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const override {
6457 // TODO: We can be smarter here.
6458 // Currently, unless the array is the result of NewArray, the array access is always
6459 // preceded by some form of null NullCheck necessary for the bounds check, usually
6460 // implicit null check on the ArrayLength input to BoundsCheck or Deoptimize for
6461 // dynamic BCE. There are cases when these could be removed to produce better code.
6462 // If we ever add optimizations to do so we should allow an implicit check here
6463 // (as long as the address falls in the first page).
6464 //
6465 // As an example of such fancy optimization, we could eliminate BoundsCheck for
6466 // a = cond ? new int[1] : null;
6467 // a[0]; // The Phi does not need bounds check for either input.
6468 return false;
6469 }
6470
6471 bool IsEquivalentOf(HArrayGet* other) const {
6472 bool result = (GetDexPc() == other->GetDexPc());
6473 if (kIsDebugBuild && result) {
6474 DCHECK_EQ(GetBlock(), other->GetBlock());
6475 DCHECK_EQ(GetArray(), other->GetArray());
6476 DCHECK_EQ(GetIndex(), other->GetIndex());
6477 if (DataType::IsIntOrLongType(GetType())) {
6478 DCHECK(DataType::IsFloatingPointType(other->GetType())) << other->GetType();
6479 } else {
6480 DCHECK(DataType::IsFloatingPointType(GetType())) << GetType();
6481 DCHECK(DataType::IsIntOrLongType(other->GetType())) << other->GetType();
6482 }
6483 }
6484 return result;
6485 }
6486
6487 bool IsStringCharAt() const { return GetPackedFlag<kFlagIsStringCharAt>(); }
6488
6489 HInstruction* GetArray() const { return InputAt(0); }
6490 HInstruction* GetIndex() const { return InputAt(1); }
6491
6492 void SetType(DataType::Type new_type) {
6493 DCHECK(DataType::IsIntegralType(GetType()));
6494 DCHECK(DataType::IsIntegralType(new_type));
6495 DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
6496 SetPackedField<TypeField>(new_type);
6497 }
6498
6499 DECLARE_INSTRUCTION(ArrayGet);
6500
6501 protected:
6502 DEFAULT_COPY_CONSTRUCTOR(ArrayGet);
6503
6504 private:
6505 // We treat a String as an array, creating the HArrayGet from String.charAt()
6506 // intrinsic in the instruction simplifier. We can always determine whether
6507 // a particular HArrayGet is actually a String.charAt() by looking at the type
6508 // of the input but that requires holding the mutator lock, so we prefer to use
6509 // a flag, so that code generators don't need to do the locking.
6510 static constexpr size_t kFlagIsStringCharAt = kNumberOfGenericPackedBits;
6511 static constexpr size_t kNumberOfArrayGetPackedBits = kFlagIsStringCharAt + 1;
6512 static_assert(kNumberOfArrayGetPackedBits <= HInstruction::kMaxNumberOfPackedBits,
6513 "Too many packed fields.");
6514 };
6515
6516 class HArraySet final : public HExpression<3> {
6517 public:
6518 HArraySet(HInstruction* array,
6519 HInstruction* index,
6520 HInstruction* value,
6521 DataType::Type expected_component_type,
6522 uint32_t dex_pc)
6523 : HArraySet(array,
6524 index,
6525 value,
6526 expected_component_type,
6527 // Make a best guess for side effects now, may be refined during SSA building.
6528 ComputeSideEffects(GetComponentType(value->GetType(), expected_component_type)),
6529 dex_pc) {
6530 }
6531
6532 HArraySet(HInstruction* array,
6533 HInstruction* index,
6534 HInstruction* value,
6535 DataType::Type expected_component_type,
6536 SideEffects side_effects,
6537 uint32_t dex_pc)
6538 : HExpression(kArraySet, side_effects, dex_pc) {
6539 SetPackedField<ExpectedComponentTypeField>(expected_component_type);
6540 SetPackedFlag<kFlagNeedsTypeCheck>(value->GetType() == DataType::Type::kReference);
6541 SetPackedFlag<kFlagValueCanBeNull>(true);
6542 SetPackedFlag<kFlagStaticTypeOfArrayIsObjectArray>(false);
6543 SetRawInputAt(0, array);
6544 SetRawInputAt(1, index);
6545 SetRawInputAt(2, value);
6546 }
6547
6548 bool IsClonable() const override { return true; }
6549
6550 bool NeedsEnvironment() const override {
6551 // We call a runtime method to throw ArrayStoreException.
6552 return NeedsTypeCheck();
6553 }
6554
6555 // Can throw ArrayStoreException.
6556 bool CanThrow() const override { return NeedsTypeCheck(); }
6557
6558 bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const override {
6559 // TODO: Same as for ArrayGet.
6560 return false;
6561 }
6562
6563 void ClearNeedsTypeCheck() {
6564 SetPackedFlag<kFlagNeedsTypeCheck>(false);
6565 }
6566
6567 void ClearValueCanBeNull() {
6568 SetPackedFlag<kFlagValueCanBeNull>(false);
6569 }
6570
6571 void SetStaticTypeOfArrayIsObjectArray() {
6572 SetPackedFlag<kFlagStaticTypeOfArrayIsObjectArray>(true);
6573 }
6574
6575 bool GetValueCanBeNull() const { return GetPackedFlag<kFlagValueCanBeNull>(); }
6576 bool NeedsTypeCheck() const { return GetPackedFlag<kFlagNeedsTypeCheck>(); }
6577 bool StaticTypeOfArrayIsObjectArray() const {
6578 return GetPackedFlag<kFlagStaticTypeOfArrayIsObjectArray>();
6579 }
6580
6581 HInstruction* GetArray() const { return InputAt(0); }
6582 HInstruction* GetIndex() const { return InputAt(1); }
6583 HInstruction* GetValue() const { return InputAt(2); }
6584
6585 DataType::Type GetComponentType() const {
6586 return GetComponentType(GetValue()->GetType(), GetRawExpectedComponentType());
6587 }
6588
6589 static DataType::Type GetComponentType(DataType::Type value_type,
6590 DataType::Type expected_component_type) {
6591 // The Dex format does not type floating point index operations. Since the
6592 // `expected_component_type` comes from SSA building and can therefore not
6593 // be correct, we also check what is the value type. If it is a floating
6594 // point type, we must use that type.
6595 return ((value_type == DataType::Type::kFloat32) || (value_type == DataType::Type::kFloat64))
6596 ? value_type
6597 : expected_component_type;
6598 }
6599
6600 DataType::Type GetRawExpectedComponentType() const {
6601 return GetPackedField<ExpectedComponentTypeField>();
6602 }
6603
6604 static SideEffects ComputeSideEffects(DataType::Type type) {
6605 return SideEffects::ArrayWriteOfType(type).Union(SideEffectsForArchRuntimeCalls(type));
6606 }
6607
6608 static SideEffects SideEffectsForArchRuntimeCalls(DataType::Type value_type) {
6609 return (value_type == DataType::Type::kReference) ? SideEffects::CanTriggerGC()
6610 : SideEffects::None();
6611 }
6612
6613 DECLARE_INSTRUCTION(ArraySet);
6614
6615 protected:
6616 DEFAULT_COPY_CONSTRUCTOR(ArraySet);
6617
6618 private:
6619 static constexpr size_t kFieldExpectedComponentType = kNumberOfGenericPackedBits;
6620 static constexpr size_t kFieldExpectedComponentTypeSize =
6621 MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
6622 static constexpr size_t kFlagNeedsTypeCheck =
6623 kFieldExpectedComponentType + kFieldExpectedComponentTypeSize;
6624 static constexpr size_t kFlagValueCanBeNull = kFlagNeedsTypeCheck + 1;
6625 // Cached information for the reference_type_info_ so that codegen
6626 // does not need to inspect the static type.
6627 static constexpr size_t kFlagStaticTypeOfArrayIsObjectArray = kFlagValueCanBeNull + 1;
6628 static constexpr size_t kNumberOfArraySetPackedBits =
6629 kFlagStaticTypeOfArrayIsObjectArray + 1;
6630 static_assert(kNumberOfArraySetPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
6631 using ExpectedComponentTypeField =
6632 BitField<DataType::Type, kFieldExpectedComponentType, kFieldExpectedComponentTypeSize>;
6633 };
6634
6635 class HArrayLength final : public HExpression<1> {
6636 public:
6637 HArrayLength(HInstruction* array, uint32_t dex_pc, bool is_string_length = false)
6638 : HExpression(kArrayLength, DataType::Type::kInt32, SideEffects::None(), dex_pc) {
6639 SetPackedFlag<kFlagIsStringLength>(is_string_length);
6640 // Note that arrays do not change length, so the instruction does not
6641 // depend on any write.
6642 SetRawInputAt(0, array);
6643 }
6644
6645 bool IsClonable() const override { return true; }
6646 bool CanBeMoved() const override { return true; }
6647 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6648 return true;
6649 }
6650 bool CanDoImplicitNullCheckOn(HInstruction* obj) const override {
6651 return obj == InputAt(0);
6652 }
6653
6654 bool IsStringLength() const { return GetPackedFlag<kFlagIsStringLength>(); }
6655
6656 DECLARE_INSTRUCTION(ArrayLength);
6657
6658 protected:
6659 DEFAULT_COPY_CONSTRUCTOR(ArrayLength);
6660
6661 private:
6662 // We treat a String as an array, creating the HArrayLength from String.length()
6663 // or String.isEmpty() intrinsic in the instruction simplifier. We can always
6664 // determine whether a particular HArrayLength is actually a String.length() by
6665 // looking at the type of the input but that requires holding the mutator lock, so
6666 // we prefer to use a flag, so that code generators don't need to do the locking.
6667 static constexpr size_t kFlagIsStringLength = kNumberOfGenericPackedBits;
6668 static constexpr size_t kNumberOfArrayLengthPackedBits = kFlagIsStringLength + 1;
6669 static_assert(kNumberOfArrayLengthPackedBits <= HInstruction::kMaxNumberOfPackedBits,
6670 "Too many packed fields.");
6671 };
6672
6673 class HBoundsCheck final : public HExpression<2> {
6674 public:
6675 // `HBoundsCheck` can trigger GC, as it may call the `IndexOutOfBoundsException`
6676 // constructor. However it can only do it on a fatal slow path so execution never returns to the
6677 // instruction following the current one; thus 'SideEffects::None()' is used.
6678 HBoundsCheck(HInstruction* index,
6679 HInstruction* length,
6680 uint32_t dex_pc,
6681 bool is_string_char_at = false)
6682 : HExpression(kBoundsCheck, index->GetType(), SideEffects::None(), dex_pc) {
6683 DCHECK_EQ(DataType::Type::kInt32, DataType::Kind(index->GetType()));
6684 SetPackedFlag<kFlagIsStringCharAt>(is_string_char_at);
6685 SetRawInputAt(0, index);
6686 SetRawInputAt(1, length);
6687 }
6688
6689 bool IsClonable() const override { return true; }
6690 bool CanBeMoved() const override { return true; }
6691 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
6692 return true;
6693 }
6694
6695 bool NeedsEnvironment() const override { return true; }
6696
6697 bool CanThrow() const override { return true; }
6698
6699 bool IsStringCharAt() const { return GetPackedFlag<kFlagIsStringCharAt>(); }
6700
6701 HInstruction* GetIndex() const { return InputAt(0); }
6702
6703 DECLARE_INSTRUCTION(BoundsCheck);
6704
6705 protected:
6706 DEFAULT_COPY_CONSTRUCTOR(BoundsCheck);
6707
6708 private:
6709 static constexpr size_t kFlagIsStringCharAt = kNumberOfGenericPackedBits;
6710 static constexpr size_t kNumberOfBoundsCheckPackedBits = kFlagIsStringCharAt + 1;
6711 static_assert(kNumberOfBoundsCheckPackedBits <= HInstruction::kMaxNumberOfPackedBits,
6712 "Too many packed fields.");
6713 };
6714
6715 class HSuspendCheck final : public HExpression<0> {
6716 public:
6717 explicit HSuspendCheck(uint32_t dex_pc = kNoDexPc)
6718 : HExpression(kSuspendCheck, SideEffects::CanTriggerGC(), dex_pc),
6719 slow_path_(nullptr) {
6720 }
6721
6722 bool IsClonable() const override { return true; }
6723
6724 bool NeedsEnvironment() const override {
6725 return true;
6726 }
6727
6728 void SetSlowPath(SlowPathCode* slow_path) { slow_path_ = slow_path; }
6729 SlowPathCode* GetSlowPath() const { return slow_path_; }
6730
6731 DECLARE_INSTRUCTION(SuspendCheck);
6732
6733 protected:
6734 DEFAULT_COPY_CONSTRUCTOR(SuspendCheck);
6735
6736 private:
6737 // Only used for code generation, in order to share the same slow path between back edges
6738 // of a same loop.
6739 SlowPathCode* slow_path_;
6740 };
6741
6742 // Pseudo-instruction which provides the native debugger with mapping information.
6743 // It ensures that we can generate line number and local variables at this point.
6744 class HNativeDebugInfo : public HExpression<0> {
6745 public:
6746 explicit HNativeDebugInfo(uint32_t dex_pc)
6747 : HExpression<0>(kNativeDebugInfo, SideEffects::None(), dex_pc) {
6748 }
6749
6750 bool NeedsEnvironment() const override {
6751 return true;
6752 }
6753
6754 DECLARE_INSTRUCTION(NativeDebugInfo);
6755
6756 protected:
6757 DEFAULT_COPY_CONSTRUCTOR(NativeDebugInfo);
6758 };
6759
6760 /**
6761 * Instruction to load a Class object.
6762 */
6763 class HLoadClass final : public HInstruction {
6764 public:
6765 // Determines how to load the Class.
6766 enum class LoadKind {
6767 // We cannot load this class. See HSharpening::SharpenLoadClass.
6768 kInvalid = -1,
6769
6770 // Use the Class* from the method's own ArtMethod*.
6771 kReferrersClass,
6772
6773 // Use PC-relative boot image Class* address that will be known at link time.
6774 // Used for boot image classes referenced by boot image code.
6775 kBootImageLinkTimePcRelative,
6776
6777 // Load from an entry in the .data.bimg.rel.ro using a PC-relative load.
6778 // Used for boot image classes referenced by apps in AOT-compiled code.
6779 kBootImageRelRo,
6780
6781 // Load from an entry in the .bss section using a PC-relative load.
6782 // Used for classes outside boot image referenced by AOT-compiled app and boot image code.
6783 kBssEntry,
6784
6785 // Load from an entry for public class in the .bss section using a PC-relative load.
6786 // Used for classes that were unresolved during AOT-compilation outside the literal
6787 // package of the compiling class. Such classes are accessible only if they are public
6788 // and the .bss entry shall therefore be filled only if the resolved class is public.
6789 kBssEntryPublic,
6790
6791 // Load from an entry for package class in the .bss section using a PC-relative load.
6792 // Used for classes that were unresolved during AOT-compilation but within the literal
6793 // package of the compiling class. Such classes are accessible if they are public or
6794 // in the same package which, given the literal package match, requires only matching
6795 // defining class loader and the .bss entry shall therefore be filled only if at least
6796 // one of those conditions holds. Note that all code in an oat file belongs to classes
6797 // with the same defining class loader.
6798 kBssEntryPackage,
6799
6800 // Use a known boot image Class* address, embedded in the code by the codegen.
6801 // Used for boot image classes referenced by apps in JIT-compiled code.
6802 kJitBootImageAddress,
6803
6804 // Load from the root table associated with the JIT compiled method.
6805 kJitTableAddress,
6806
6807 // Load using a simple runtime call. This is the fall-back load kind when
6808 // the codegen is unable to use another appropriate kind.
6809 kRuntimeCall,
6810
6811 kLast = kRuntimeCall
6812 };
6813
6814 HLoadClass(HCurrentMethod* current_method,
6815 dex::TypeIndex type_index,
6816 const DexFile& dex_file,
6817 Handle<mirror::Class> klass,
6818 bool is_referrers_class,
6819 uint32_t dex_pc,
6820 bool needs_access_check)
6821 : HInstruction(kLoadClass,
6822 DataType::Type::kReference,
6823 SideEffectsForArchRuntimeCalls(),
6824 dex_pc),
6825 special_input_(HUserRecord<HInstruction*>(current_method)),
6826 type_index_(type_index),
6827 dex_file_(dex_file),
6828 klass_(klass) {
6829 // Referrers class should not need access check. We never inline unverified
6830 // methods so we can't possibly end up in this situation.
6831 DCHECK_IMPLIES(is_referrers_class, !needs_access_check);
6832
6833 SetPackedField<LoadKindField>(
6834 is_referrers_class ? LoadKind::kReferrersClass : LoadKind::kRuntimeCall);
6835 SetPackedFlag<kFlagNeedsAccessCheck>(needs_access_check);
6836 SetPackedFlag<kFlagIsInBootImage>(false);
6837 SetPackedFlag<kFlagGenerateClInitCheck>(false);
6838 SetPackedFlag<kFlagValidLoadedClassRTI>(false);
6839 }
6840
6841 bool IsClonable() const override { return true; }
6842
6843 void SetLoadKind(LoadKind load_kind);
6844
6845 LoadKind GetLoadKind() const {
6846 return GetPackedField<LoadKindField>();
6847 }
6848
6849 bool HasPcRelativeLoadKind() const {
6850 return GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
6851 GetLoadKind() == LoadKind::kBootImageRelRo ||
6852 GetLoadKind() == LoadKind::kBssEntry ||
6853 GetLoadKind() == LoadKind::kBssEntryPublic ||
6854 GetLoadKind() == LoadKind::kBssEntryPackage;
6855 }
6856
6857 bool CanBeMoved() const override { return true; }
6858
6859 bool InstructionDataEquals(const HInstruction* other) const override;
6860
6861 size_t ComputeHashCode() const override { return type_index_.index_; }
6862
6863 bool CanBeNull() const override { return false; }
6864
6865 bool NeedsEnvironment() const override {
6866 return CanCallRuntime();
6867 }
6868 bool NeedsBss() const override {
6869 LoadKind load_kind = GetLoadKind();
6870 return load_kind == LoadKind::kBssEntry ||
6871 load_kind == LoadKind::kBssEntryPublic ||
6872 load_kind == LoadKind::kBssEntryPackage;
6873 }
6874
6875 void SetMustGenerateClinitCheck(bool generate_clinit_check) {
6876 SetPackedFlag<kFlagGenerateClInitCheck>(generate_clinit_check);
6877 }
6878
6879 bool CanCallRuntime() const {
6880 return NeedsAccessCheck() ||
6881 MustGenerateClinitCheck() ||
6882 GetLoadKind() == LoadKind::kRuntimeCall ||
6883 GetLoadKind() == LoadKind::kBssEntry;
6884 }
6885
6886 bool CanThrow() const override {
6887 return NeedsAccessCheck() ||
6888 MustGenerateClinitCheck() ||
6889 // If the class is in the boot image, the lookup in the runtime call cannot throw.
6890 ((GetLoadKind() == LoadKind::kRuntimeCall ||
6891 GetLoadKind() == LoadKind::kBssEntry) &&
6892 !IsInBootImage());
6893 }
6894
6895 ReferenceTypeInfo GetLoadedClassRTI() {
6896 if (GetPackedFlag<kFlagValidLoadedClassRTI>()) {
6897 // Note: The is_exact flag from the return value should not be used.
6898 return ReferenceTypeInfo::CreateUnchecked(klass_, /* is_exact= */ true);
6899 } else {
6900 return ReferenceTypeInfo::CreateInvalid();
6901 }
6902 }
6903
6904 // Loaded class RTI is marked as valid by RTP if the klass_ is admissible.
6905 void SetValidLoadedClassRTI() {
6906 DCHECK(klass_ != nullptr);
6907 SetPackedFlag<kFlagValidLoadedClassRTI>(true);
6908 }
6909
6910 dex::TypeIndex GetTypeIndex() const { return type_index_; }
6911 const DexFile& GetDexFile() const { return dex_file_; }
6912
6913 static SideEffects SideEffectsForArchRuntimeCalls() {
6914 return SideEffects::CanTriggerGC();
6915 }
6916
6917 bool IsReferrersClass() const { return GetLoadKind() == LoadKind::kReferrersClass; }
6918 bool NeedsAccessCheck() const { return GetPackedFlag<kFlagNeedsAccessCheck>(); }
6919 bool IsInBootImage() const { return GetPackedFlag<kFlagIsInBootImage>(); }
6920 bool MustGenerateClinitCheck() const { return GetPackedFlag<kFlagGenerateClInitCheck>(); }
6921
6922 bool MustResolveTypeOnSlowPath() const {
6923 // Check that this instruction has a slow path.
6924 LoadKind load_kind = GetLoadKind();
6925 DCHECK(load_kind != LoadKind::kRuntimeCall); // kRuntimeCall calls on main path.
6926 bool must_resolve_type_on_slow_path =
6927 load_kind == LoadKind::kBssEntry ||
6928 load_kind == LoadKind::kBssEntryPublic ||
6929 load_kind == LoadKind::kBssEntryPackage;
6930 DCHECK(must_resolve_type_on_slow_path || MustGenerateClinitCheck());
6931 return must_resolve_type_on_slow_path;
6932 }
6933
6934 void MarkInBootImage() {
6935 SetPackedFlag<kFlagIsInBootImage>(true);
6936 }
6937
6938 void AddSpecialInput(HInstruction* special_input);
6939
6940 using HInstruction::GetInputRecords; // Keep the const version visible.
6941 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
6942 return ArrayRef<HUserRecord<HInstruction*>>(
6943 &special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
6944 }
6945
6946 Handle<mirror::Class> GetClass() const {
6947 return klass_;
6948 }
6949
6950 DECLARE_INSTRUCTION(LoadClass);
6951
6952 protected:
6953 DEFAULT_COPY_CONSTRUCTOR(LoadClass);
6954
6955 private:
6956 static constexpr size_t kFlagNeedsAccessCheck = kNumberOfGenericPackedBits;
6957 static constexpr size_t kFlagIsInBootImage = kFlagNeedsAccessCheck + 1;
6958 // Whether this instruction must generate the initialization check.
6959 // Used for code generation.
6960 static constexpr size_t kFlagGenerateClInitCheck = kFlagIsInBootImage + 1;
6961 static constexpr size_t kFieldLoadKind = kFlagGenerateClInitCheck + 1;
6962 static constexpr size_t kFieldLoadKindSize =
6963 MinimumBitsToStore(static_cast<size_t>(LoadKind::kLast));
6964 static constexpr size_t kFlagValidLoadedClassRTI = kFieldLoadKind + kFieldLoadKindSize;
6965 static constexpr size_t kNumberOfLoadClassPackedBits = kFlagValidLoadedClassRTI + 1;
6966 static_assert(kNumberOfLoadClassPackedBits < kMaxNumberOfPackedBits, "Too many packed fields.");
6967 using LoadKindField = BitField<LoadKind, kFieldLoadKind, kFieldLoadKindSize>;
6968
6969 static bool HasTypeReference(LoadKind load_kind) {
6970 return load_kind == LoadKind::kReferrersClass ||
6971 load_kind == LoadKind::kBootImageLinkTimePcRelative ||
6972 load_kind == LoadKind::kBssEntry ||
6973 load_kind == LoadKind::kBssEntryPublic ||
6974 load_kind == LoadKind::kBssEntryPackage ||
6975 load_kind == LoadKind::kRuntimeCall;
6976 }
6977
6978 void SetLoadKindInternal(LoadKind load_kind);
6979
6980 // The special input is the HCurrentMethod for kRuntimeCall or kReferrersClass.
6981 // For other load kinds it's empty or possibly some architecture-specific instruction
6982 // for PC-relative loads, i.e. kBssEntry* or kBootImageLinkTimePcRelative.
6983 HUserRecord<HInstruction*> special_input_;
6984
6985 // A type index and dex file where the class can be accessed. The dex file can be:
6986 // - The compiling method's dex file if the class is defined there too.
6987 // - The compiling method's dex file if the class is referenced there.
6988 // - The dex file where the class is defined. When the load kind can only be
6989 // kBssEntry* or kRuntimeCall, we cannot emit code for this `HLoadClass`.
6990 const dex::TypeIndex type_index_;
6991 const DexFile& dex_file_;
6992
6993 Handle<mirror::Class> klass_;
6994 };
6995 std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs);
6996
6997 // Note: defined outside class to see operator<<(., HLoadClass::LoadKind).
6998 inline void HLoadClass::SetLoadKind(LoadKind load_kind) {
6999 // The load kind should be determined before inserting the instruction to the graph.
7000 DCHECK(GetBlock() == nullptr);
7001 DCHECK(GetEnvironment() == nullptr);
7002 SetPackedField<LoadKindField>(load_kind);
7003 if (load_kind != LoadKind::kRuntimeCall && load_kind != LoadKind::kReferrersClass) {
7004 special_input_ = HUserRecord<HInstruction*>(nullptr);
7005 }
7006 if (!NeedsEnvironment()) {
7007 SetSideEffects(SideEffects::None());
7008 }
7009 }
7010
7011 // Note: defined outside class to see operator<<(., HLoadClass::LoadKind).
7012 inline void HLoadClass::AddSpecialInput(HInstruction* special_input) {
7013 // The special input is used for PC-relative loads on some architectures,
7014 // including literal pool loads, which are PC-relative too.
7015 DCHECK(GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
7016 GetLoadKind() == LoadKind::kBootImageRelRo ||
7017 GetLoadKind() == LoadKind::kBssEntry ||
7018 GetLoadKind() == LoadKind::kBssEntryPublic ||
7019 GetLoadKind() == LoadKind::kBssEntryPackage ||
7020 GetLoadKind() == LoadKind::kJitBootImageAddress) << GetLoadKind();
7021 DCHECK(special_input_.GetInstruction() == nullptr);
7022 special_input_ = HUserRecord<HInstruction*>(special_input);
7023 special_input->AddUseAt(this, 0);
7024 }
7025
7026 class HLoadString final : public HInstruction {
7027 public:
7028 // Determines how to load the String.
7029 enum class LoadKind {
7030 // Use PC-relative boot image String* address that will be known at link time.
7031 // Used for boot image strings referenced by boot image code.
7032 kBootImageLinkTimePcRelative,
7033
7034 // Load from an entry in the .data.bimg.rel.ro using a PC-relative load.
7035 // Used for boot image strings referenced by apps in AOT-compiled code.
7036 kBootImageRelRo,
7037
7038 // Load from an entry in the .bss section using a PC-relative load.
7039 // Used for strings outside boot image referenced by AOT-compiled app and boot image code.
7040 kBssEntry,
7041
7042 // Use a known boot image String* address, embedded in the code by the codegen.
7043 // Used for boot image strings referenced by apps in JIT-compiled code.
7044 kJitBootImageAddress,
7045
7046 // Load from the root table associated with the JIT compiled method.
7047 kJitTableAddress,
7048
7049 // Load using a simple runtime call. This is the fall-back load kind when
7050 // the codegen is unable to use another appropriate kind.
7051 kRuntimeCall,
7052
7053 kLast = kRuntimeCall,
7054 };
7055
7056 HLoadString(HCurrentMethod* current_method,
7057 dex::StringIndex string_index,
7058 const DexFile& dex_file,
7059 uint32_t dex_pc)
7060 : HInstruction(kLoadString,
7061 DataType::Type::kReference,
7062 SideEffectsForArchRuntimeCalls(),
7063 dex_pc),
7064 special_input_(HUserRecord<HInstruction*>(current_method)),
7065 string_index_(string_index),
7066 dex_file_(dex_file) {
7067 SetPackedField<LoadKindField>(LoadKind::kRuntimeCall);
7068 }
7069
7070 bool IsClonable() const override { return true; }
7071 bool NeedsBss() const override {
7072 return GetLoadKind() == LoadKind::kBssEntry;
7073 }
7074
7075 void SetLoadKind(LoadKind load_kind);
7076
7077 LoadKind GetLoadKind() const {
7078 return GetPackedField<LoadKindField>();
7079 }
7080
7081 bool HasPcRelativeLoadKind() const {
7082 return GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
7083 GetLoadKind() == LoadKind::kBootImageRelRo ||
7084 GetLoadKind() == LoadKind::kBssEntry;
7085 }
7086
7087 const DexFile& GetDexFile() const {
7088 return dex_file_;
7089 }
7090
7091 dex::StringIndex GetStringIndex() const {
7092 return string_index_;
7093 }
7094
7095 Handle<mirror::String> GetString() const {
7096 return string_;
7097 }
7098
7099 void SetString(Handle<mirror::String> str) {
7100 string_ = str;
7101 }
7102
7103 bool CanBeMoved() const override { return true; }
7104
7105 bool InstructionDataEquals(const HInstruction* other) const override;
7106
7107 size_t ComputeHashCode() const override { return string_index_.index_; }
7108
7109 // Will call the runtime if we need to load the string through
7110 // the dex cache and the string is not guaranteed to be there yet.
7111 bool NeedsEnvironment() const override {
7112 LoadKind load_kind = GetLoadKind();
7113 if (load_kind == LoadKind::kBootImageLinkTimePcRelative ||
7114 load_kind == LoadKind::kBootImageRelRo ||
7115 load_kind == LoadKind::kJitBootImageAddress ||
7116 load_kind == LoadKind::kJitTableAddress) {
7117 return false;
7118 }
7119 return true;
7120 }
7121
7122 bool CanBeNull() const override { return false; }
7123 bool CanThrow() const override { return NeedsEnvironment(); }
7124
7125 static SideEffects SideEffectsForArchRuntimeCalls() {
7126 return SideEffects::CanTriggerGC();
7127 }
7128
7129 void AddSpecialInput(HInstruction* special_input);
7130
7131 using HInstruction::GetInputRecords; // Keep the const version visible.
7132 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
7133 return ArrayRef<HUserRecord<HInstruction*>>(
7134 &special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
7135 }
7136
7137 DECLARE_INSTRUCTION(LoadString);
7138
7139 protected:
7140 DEFAULT_COPY_CONSTRUCTOR(LoadString);
7141
7142 private:
7143 static constexpr size_t kFieldLoadKind = kNumberOfGenericPackedBits;
7144 static constexpr size_t kFieldLoadKindSize =
7145 MinimumBitsToStore(static_cast<size_t>(LoadKind::kLast));
7146 static constexpr size_t kNumberOfLoadStringPackedBits = kFieldLoadKind + kFieldLoadKindSize;
7147 static_assert(kNumberOfLoadStringPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
7148 using LoadKindField = BitField<LoadKind, kFieldLoadKind, kFieldLoadKindSize>;
7149
7150 void SetLoadKindInternal(LoadKind load_kind);
7151
7152 // The special input is the HCurrentMethod for kRuntimeCall.
7153 // For other load kinds it's empty or possibly some architecture-specific instruction
7154 // for PC-relative loads, i.e. kBssEntry or kBootImageLinkTimePcRelative.
7155 HUserRecord<HInstruction*> special_input_;
7156
7157 dex::StringIndex string_index_;
7158 const DexFile& dex_file_;
7159
7160 Handle<mirror::String> string_;
7161 };
7162 std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs);
7163
7164 // Note: defined outside class to see operator<<(., HLoadString::LoadKind).
7165 inline void HLoadString::SetLoadKind(LoadKind load_kind) {
7166 // The load kind should be determined before inserting the instruction to the graph.
7167 DCHECK(GetBlock() == nullptr);
7168 DCHECK(GetEnvironment() == nullptr);
7169 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
7170 SetPackedField<LoadKindField>(load_kind);
7171 if (load_kind != LoadKind::kRuntimeCall) {
7172 special_input_ = HUserRecord<HInstruction*>(nullptr);
7173 }
7174 if (!NeedsEnvironment()) {
7175 SetSideEffects(SideEffects::None());
7176 }
7177 }
7178
7179 // Note: defined outside class to see operator<<(., HLoadString::LoadKind).
7180 inline void HLoadString::AddSpecialInput(HInstruction* special_input) {
7181 // The special input is used for PC-relative loads on some architectures,
7182 // including literal pool loads, which are PC-relative too.
7183 DCHECK(GetLoadKind() == LoadKind::kBootImageLinkTimePcRelative ||
7184 GetLoadKind() == LoadKind::kBootImageRelRo ||
7185 GetLoadKind() == LoadKind::kBssEntry ||
7186 GetLoadKind() == LoadKind::kJitBootImageAddress) << GetLoadKind();
7187 // HLoadString::GetInputRecords() returns an empty array at this point,
7188 // so use the GetInputRecords() from the base class to set the input record.
7189 DCHECK(special_input_.GetInstruction() == nullptr);
7190 special_input_ = HUserRecord<HInstruction*>(special_input);
7191 special_input->AddUseAt(this, 0);
7192 }
7193
7194 class HLoadMethodHandle final : public HInstruction {
7195 public:
7196 HLoadMethodHandle(HCurrentMethod* current_method,
7197 uint16_t method_handle_idx,
7198 const DexFile& dex_file,
7199 uint32_t dex_pc)
7200 : HInstruction(kLoadMethodHandle,
7201 DataType::Type::kReference,
7202 SideEffectsForArchRuntimeCalls(),
7203 dex_pc),
7204 special_input_(HUserRecord<HInstruction*>(current_method)),
7205 method_handle_idx_(method_handle_idx),
7206 dex_file_(dex_file) {
7207 }
7208
7209 using HInstruction::GetInputRecords; // Keep the const version visible.
7210 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
7211 return ArrayRef<HUserRecord<HInstruction*>>(
7212 &special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
7213 }
7214
7215 bool IsClonable() const override { return true; }
7216
7217 uint16_t GetMethodHandleIndex() const { return method_handle_idx_; }
7218
7219 const DexFile& GetDexFile() const { return dex_file_; }
7220
7221 static SideEffects SideEffectsForArchRuntimeCalls() {
7222 return SideEffects::CanTriggerGC();
7223 }
7224
7225 DECLARE_INSTRUCTION(LoadMethodHandle);
7226
7227 protected:
7228 DEFAULT_COPY_CONSTRUCTOR(LoadMethodHandle);
7229
7230 private:
7231 // The special input is the HCurrentMethod for kRuntimeCall.
7232 HUserRecord<HInstruction*> special_input_;
7233
7234 const uint16_t method_handle_idx_;
7235 const DexFile& dex_file_;
7236 };
7237
7238 class HLoadMethodType final : public HInstruction {
7239 public:
7240 HLoadMethodType(HCurrentMethod* current_method,
7241 dex::ProtoIndex proto_index,
7242 const DexFile& dex_file,
7243 uint32_t dex_pc)
7244 : HInstruction(kLoadMethodType,
7245 DataType::Type::kReference,
7246 SideEffectsForArchRuntimeCalls(),
7247 dex_pc),
7248 special_input_(HUserRecord<HInstruction*>(current_method)),
7249 proto_index_(proto_index),
7250 dex_file_(dex_file) {
7251 }
7252
7253 using HInstruction::GetInputRecords; // Keep the const version visible.
7254 ArrayRef<HUserRecord<HInstruction*>> GetInputRecords() final {
7255 return ArrayRef<HUserRecord<HInstruction*>>(
7256 &special_input_, (special_input_.GetInstruction() != nullptr) ? 1u : 0u);
7257 }
7258
7259 bool IsClonable() const override { return true; }
7260
7261 dex::ProtoIndex GetProtoIndex() const { return proto_index_; }
7262
7263 const DexFile& GetDexFile() const { return dex_file_; }
7264
7265 static SideEffects SideEffectsForArchRuntimeCalls() {
7266 return SideEffects::CanTriggerGC();
7267 }
7268
7269 DECLARE_INSTRUCTION(LoadMethodType);
7270
7271 protected:
7272 DEFAULT_COPY_CONSTRUCTOR(LoadMethodType);
7273
7274 private:
7275 // The special input is the HCurrentMethod for kRuntimeCall.
7276 HUserRecord<HInstruction*> special_input_;
7277
7278 const dex::ProtoIndex proto_index_;
7279 const DexFile& dex_file_;
7280 };
7281
7282 /**
7283 * Performs an initialization check on its Class object input.
7284 */
7285 class HClinitCheck final : public HExpression<1> {
7286 public:
7287 HClinitCheck(HLoadClass* constant, uint32_t dex_pc)
7288 : HExpression(
7289 kClinitCheck,
7290 DataType::Type::kReference,
7291 SideEffects::AllExceptGCDependency(), // Assume write/read on all fields/arrays.
7292 dex_pc) {
7293 SetRawInputAt(0, constant);
7294 }
7295 // TODO: Make ClinitCheck clonable.
7296 bool CanBeMoved() const override { return true; }
7297 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
7298 return true;
7299 }
7300
7301 bool NeedsEnvironment() const override {
7302 // May call runtime to initialize the class.
7303 return true;
7304 }
7305
7306 bool CanThrow() const override { return true; }
7307
7308 HLoadClass* GetLoadClass() const {
7309 DCHECK(InputAt(0)->IsLoadClass());
7310 return InputAt(0)->AsLoadClass();
7311 }
7312
7313 DECLARE_INSTRUCTION(ClinitCheck);
7314
7315
7316 protected:
7317 DEFAULT_COPY_CONSTRUCTOR(ClinitCheck);
7318 };
7319
7320 class HStaticFieldGet final : public HExpression<1> {
7321 public:
7322 HStaticFieldGet(HInstruction* cls,
7323 ArtField* field,
7324 DataType::Type field_type,
7325 MemberOffset field_offset,
7326 bool is_volatile,
7327 uint32_t field_idx,
7328 uint16_t declaring_class_def_index,
7329 const DexFile& dex_file,
7330 uint32_t dex_pc)
7331 : HExpression(kStaticFieldGet,
7332 field_type,
7333 SideEffects::FieldReadOfType(field_type, is_volatile),
7334 dex_pc),
7335 field_info_(field,
7336 field_offset,
7337 field_type,
7338 is_volatile,
7339 field_idx,
7340 declaring_class_def_index,
7341 dex_file) {
7342 SetRawInputAt(0, cls);
7343 }
7344
7345
7346 bool IsClonable() const override { return true; }
7347 bool CanBeMoved() const override { return !IsVolatile(); }
7348
7349 bool InstructionDataEquals(const HInstruction* other) const override {
7350 const HStaticFieldGet* other_get = other->AsStaticFieldGet();
7351 return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue();
7352 }
7353
7354 size_t ComputeHashCode() const override {
7355 return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue();
7356 }
7357
7358 bool IsFieldAccess() const override { return true; }
7359 const FieldInfo& GetFieldInfo() const override { return field_info_; }
7360 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
7361 DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
7362 bool IsVolatile() const { return field_info_.IsVolatile(); }
7363
7364 void SetType(DataType::Type new_type) {
7365 DCHECK(DataType::IsIntegralType(GetType()));
7366 DCHECK(DataType::IsIntegralType(new_type));
7367 DCHECK_EQ(DataType::Size(GetType()), DataType::Size(new_type));
7368 SetPackedField<TypeField>(new_type);
7369 }
7370
7371 DECLARE_INSTRUCTION(StaticFieldGet);
7372
7373 protected:
7374 DEFAULT_COPY_CONSTRUCTOR(StaticFieldGet);
7375
7376 private:
7377 const FieldInfo field_info_;
7378 };
7379
7380 class HStaticFieldSet final : public HExpression<2> {
7381 public:
7382 HStaticFieldSet(HInstruction* cls,
7383 HInstruction* value,
7384 ArtField* field,
7385 DataType::Type field_type,
7386 MemberOffset field_offset,
7387 bool is_volatile,
7388 uint32_t field_idx,
7389 uint16_t declaring_class_def_index,
7390 const DexFile& dex_file,
7391 uint32_t dex_pc)
7392 : HExpression(kStaticFieldSet,
7393 SideEffects::FieldWriteOfType(field_type, is_volatile),
7394 dex_pc),
7395 field_info_(field,
7396 field_offset,
7397 field_type,
7398 is_volatile,
7399 field_idx,
7400 declaring_class_def_index,
7401 dex_file) {
7402 SetPackedFlag<kFlagValueCanBeNull>(true);
7403 SetRawInputAt(0, cls);
7404 SetRawInputAt(1, value);
7405 }
7406
7407 bool IsClonable() const override { return true; }
7408 bool IsFieldAccess() const override { return true; }
7409 const FieldInfo& GetFieldInfo() const override { return field_info_; }
7410 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); }
7411 DataType::Type GetFieldType() const { return field_info_.GetFieldType(); }
7412 bool IsVolatile() const { return field_info_.IsVolatile(); }
7413
7414 HInstruction* GetValue() const { return InputAt(1); }
7415 bool GetValueCanBeNull() const { return GetPackedFlag<kFlagValueCanBeNull>(); }
7416 void ClearValueCanBeNull() { SetPackedFlag<kFlagValueCanBeNull>(false); }
7417
7418 DECLARE_INSTRUCTION(StaticFieldSet);
7419
7420 protected:
7421 DEFAULT_COPY_CONSTRUCTOR(StaticFieldSet);
7422
7423 private:
7424 static constexpr size_t kFlagValueCanBeNull = kNumberOfGenericPackedBits;
7425 static constexpr size_t kNumberOfStaticFieldSetPackedBits = kFlagValueCanBeNull + 1;
7426 static_assert(kNumberOfStaticFieldSetPackedBits <= kMaxNumberOfPackedBits,
7427 "Too many packed fields.");
7428
7429 const FieldInfo field_info_;
7430 };
7431
7432 class HStringBuilderAppend final : public HVariableInputSizeInstruction {
7433 public:
7434 HStringBuilderAppend(HIntConstant* format,
7435 uint32_t number_of_arguments,
7436 ArenaAllocator* allocator,
7437 uint32_t dex_pc)
7438 : HVariableInputSizeInstruction(
7439 kStringBuilderAppend,
7440 DataType::Type::kReference,
7441 // The runtime call may read memory from inputs. It never writes outside
7442 // of the newly allocated result object (or newly allocated helper objects).
7443 SideEffects::AllReads().Union(SideEffects::CanTriggerGC()),
7444 dex_pc,
7445 allocator,
7446 number_of_arguments + /* format */ 1u,
7447 kArenaAllocInvokeInputs) {
7448 DCHECK_GE(number_of_arguments, 1u); // There must be something to append.
7449 SetRawInputAt(FormatIndex(), format);
7450 }
7451
7452 void SetArgumentAt(size_t index, HInstruction* argument) {
7453 DCHECK_LE(index, GetNumberOfArguments());
7454 SetRawInputAt(index, argument);
7455 }
7456
7457 // Return the number of arguments, excluding the format.
7458 size_t GetNumberOfArguments() const {
7459 DCHECK_GE(InputCount(), 1u);
7460 return InputCount() - 1u;
7461 }
7462
7463 size_t FormatIndex() const {
7464 return GetNumberOfArguments();
7465 }
7466
7467 HIntConstant* GetFormat() {
7468 return InputAt(FormatIndex())->AsIntConstant();
7469 }
7470
7471 bool NeedsEnvironment() const override { return true; }
7472
7473 bool CanThrow() const override { return true; }
7474
7475 bool CanBeNull() const override { return false; }
7476
7477 DECLARE_INSTRUCTION(StringBuilderAppend);
7478
7479 protected:
7480 DEFAULT_COPY_CONSTRUCTOR(StringBuilderAppend);
7481 };
7482
7483 class HUnresolvedInstanceFieldGet final : public HExpression<1> {
7484 public:
7485 HUnresolvedInstanceFieldGet(HInstruction* obj,
7486 DataType::Type field_type,
7487 uint32_t field_index,
7488 uint32_t dex_pc)
7489 : HExpression(kUnresolvedInstanceFieldGet,
7490 field_type,
7491 SideEffects::AllExceptGCDependency(),
7492 dex_pc),
7493 field_index_(field_index) {
7494 SetRawInputAt(0, obj);
7495 }
7496
7497 bool IsClonable() const override { return true; }
7498 bool NeedsEnvironment() const override { return true; }
7499 bool CanThrow() const override { return true; }
7500
7501 DataType::Type GetFieldType() const { return GetType(); }
7502 uint32_t GetFieldIndex() const { return field_index_; }
7503
7504 DECLARE_INSTRUCTION(UnresolvedInstanceFieldGet);
7505
7506 protected:
7507 DEFAULT_COPY_CONSTRUCTOR(UnresolvedInstanceFieldGet);
7508
7509 private:
7510 const uint32_t field_index_;
7511 };
7512
7513 class HUnresolvedInstanceFieldSet final : public HExpression<2> {
7514 public:
7515 HUnresolvedInstanceFieldSet(HInstruction* obj,
7516 HInstruction* value,
7517 DataType::Type field_type,
7518 uint32_t field_index,
7519 uint32_t dex_pc)
7520 : HExpression(kUnresolvedInstanceFieldSet, SideEffects::AllExceptGCDependency(), dex_pc),
7521 field_index_(field_index) {
7522 SetPackedField<FieldTypeField>(field_type);
7523 DCHECK_EQ(DataType::Kind(field_type), DataType::Kind(value->GetType()));
7524 SetRawInputAt(0, obj);
7525 SetRawInputAt(1, value);
7526 }
7527
7528 bool IsClonable() const override { return true; }
7529 bool NeedsEnvironment() const override { return true; }
7530 bool CanThrow() const override { return true; }
7531
7532 DataType::Type GetFieldType() const { return GetPackedField<FieldTypeField>(); }
7533 uint32_t GetFieldIndex() const { return field_index_; }
7534
7535 DECLARE_INSTRUCTION(UnresolvedInstanceFieldSet);
7536
7537 protected:
7538 DEFAULT_COPY_CONSTRUCTOR(UnresolvedInstanceFieldSet);
7539
7540 private:
7541 static constexpr size_t kFieldFieldType = HInstruction::kNumberOfGenericPackedBits;
7542 static constexpr size_t kFieldFieldTypeSize =
7543 MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
7544 static constexpr size_t kNumberOfUnresolvedStaticFieldSetPackedBits =
7545 kFieldFieldType + kFieldFieldTypeSize;
7546 static_assert(kNumberOfUnresolvedStaticFieldSetPackedBits <= HInstruction::kMaxNumberOfPackedBits,
7547 "Too many packed fields.");
7548 using FieldTypeField = BitField<DataType::Type, kFieldFieldType, kFieldFieldTypeSize>;
7549
7550 const uint32_t field_index_;
7551 };
7552
7553 class HUnresolvedStaticFieldGet final : public HExpression<0> {
7554 public:
7555 HUnresolvedStaticFieldGet(DataType::Type field_type,
7556 uint32_t field_index,
7557 uint32_t dex_pc)
7558 : HExpression(kUnresolvedStaticFieldGet,
7559 field_type,
7560 SideEffects::AllExceptGCDependency(),
7561 dex_pc),
7562 field_index_(field_index) {
7563 }
7564
7565 bool IsClonable() const override { return true; }
7566 bool NeedsEnvironment() const override { return true; }
7567 bool CanThrow() const override { return true; }
7568
7569 DataType::Type GetFieldType() const { return GetType(); }
7570 uint32_t GetFieldIndex() const { return field_index_; }
7571
7572 DECLARE_INSTRUCTION(UnresolvedStaticFieldGet);
7573
7574 protected:
7575 DEFAULT_COPY_CONSTRUCTOR(UnresolvedStaticFieldGet);
7576
7577 private:
7578 const uint32_t field_index_;
7579 };
7580
7581 class HUnresolvedStaticFieldSet final : public HExpression<1> {
7582 public:
7583 HUnresolvedStaticFieldSet(HInstruction* value,
7584 DataType::Type field_type,
7585 uint32_t field_index,
7586 uint32_t dex_pc)
7587 : HExpression(kUnresolvedStaticFieldSet, SideEffects::AllExceptGCDependency(), dex_pc),
7588 field_index_(field_index) {
7589 SetPackedField<FieldTypeField>(field_type);
7590 DCHECK_EQ(DataType::Kind(field_type), DataType::Kind(value->GetType()));
7591 SetRawInputAt(0, value);
7592 }
7593
7594 bool IsClonable() const override { return true; }
7595 bool NeedsEnvironment() const override { return true; }
7596 bool CanThrow() const override { return true; }
7597
7598 DataType::Type GetFieldType() const { return GetPackedField<FieldTypeField>(); }
7599 uint32_t GetFieldIndex() const { return field_index_; }
7600
7601 DECLARE_INSTRUCTION(UnresolvedStaticFieldSet);
7602
7603 protected:
7604 DEFAULT_COPY_CONSTRUCTOR(UnresolvedStaticFieldSet);
7605
7606 private:
7607 static constexpr size_t kFieldFieldType = HInstruction::kNumberOfGenericPackedBits;
7608 static constexpr size_t kFieldFieldTypeSize =
7609 MinimumBitsToStore(static_cast<size_t>(DataType::Type::kLast));
7610 static constexpr size_t kNumberOfUnresolvedStaticFieldSetPackedBits =
7611 kFieldFieldType + kFieldFieldTypeSize;
7612 static_assert(kNumberOfUnresolvedStaticFieldSetPackedBits <= HInstruction::kMaxNumberOfPackedBits,
7613 "Too many packed fields.");
7614 using FieldTypeField = BitField<DataType::Type, kFieldFieldType, kFieldFieldTypeSize>;
7615
7616 const uint32_t field_index_;
7617 };
7618
7619 // Implement the move-exception DEX instruction.
7620 class HLoadException final : public HExpression<0> {
7621 public:
7622 explicit HLoadException(uint32_t dex_pc = kNoDexPc)
7623 : HExpression(kLoadException, DataType::Type::kReference, SideEffects::None(), dex_pc) {
7624 }
7625
7626 bool CanBeNull() const override { return false; }
7627
7628 DECLARE_INSTRUCTION(LoadException);
7629
7630 protected:
7631 DEFAULT_COPY_CONSTRUCTOR(LoadException);
7632 };
7633
7634 // Implicit part of move-exception which clears thread-local exception storage.
7635 // Must not be removed because the runtime expects the TLS to get cleared.
7636 class HClearException final : public HExpression<0> {
7637 public:
7638 explicit HClearException(uint32_t dex_pc = kNoDexPc)
7639 : HExpression(kClearException, SideEffects::AllWrites(), dex_pc) {
7640 }
7641
7642 DECLARE_INSTRUCTION(ClearException);
7643
7644 protected:
7645 DEFAULT_COPY_CONSTRUCTOR(ClearException);
7646 };
7647
7648 class HThrow final : public HExpression<1> {
7649 public:
7650 HThrow(HInstruction* exception, uint32_t dex_pc)
7651 : HExpression(kThrow, SideEffects::CanTriggerGC(), dex_pc) {
7652 SetRawInputAt(0, exception);
7653 }
7654
7655 bool IsControlFlow() const override { return true; }
7656
7657 bool NeedsEnvironment() const override { return true; }
7658
7659 bool CanThrow() const override { return true; }
7660
7661 bool AlwaysThrows() const override { return true; }
7662
7663 DECLARE_INSTRUCTION(Throw);
7664
7665 protected:
7666 DEFAULT_COPY_CONSTRUCTOR(Throw);
7667 };
7668
7669 /**
7670 * Implementation strategies for the code generator of a HInstanceOf
7671 * or `HCheckCast`.
7672 */
7673 enum class TypeCheckKind { // private marker to avoid generate-operator-out.py from processing.
7674 kUnresolvedCheck, // Check against an unresolved type.
7675 kExactCheck, // Can do a single class compare.
7676 kClassHierarchyCheck, // Can just walk the super class chain.
7677 kAbstractClassCheck, // Can just walk the super class chain, starting one up.
7678 kInterfaceCheck, // No optimization yet when checking against an interface.
7679 kArrayObjectCheck, // Can just check if the array is not primitive.
7680 kArrayCheck, // No optimization yet when checking against a generic array.
7681 kBitstringCheck, // Compare the type check bitstring.
7682 kLast = kArrayCheck
7683 };
7684
7685 std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs);
7686
7687 // Note: HTypeCheckInstruction is just a helper class, not an abstract instruction with an
7688 // `IsTypeCheckInstruction()`. (New virtual methods in the HInstruction class have a high cost.)
7689 class HTypeCheckInstruction : public HVariableInputSizeInstruction {
7690 public:
7691 HTypeCheckInstruction(InstructionKind kind,
7692 DataType::Type type,
7693 HInstruction* object,
7694 HInstruction* target_class_or_null,
7695 TypeCheckKind check_kind,
7696 Handle<mirror::Class> klass,
7697 uint32_t dex_pc,
7698 ArenaAllocator* allocator,
7699 HIntConstant* bitstring_path_to_root,
7700 HIntConstant* bitstring_mask,
7701 SideEffects side_effects)
7702 : HVariableInputSizeInstruction(
7703 kind,
7704 type,
7705 side_effects,
7706 dex_pc,
7707 allocator,
7708 /* number_of_inputs= */ check_kind == TypeCheckKind::kBitstringCheck ? 4u : 2u,
7709 kArenaAllocTypeCheckInputs),
7710 klass_(klass) {
7711 SetPackedField<TypeCheckKindField>(check_kind);
7712 SetPackedFlag<kFlagMustDoNullCheck>(true);
7713 SetPackedFlag<kFlagValidTargetClassRTI>(false);
7714 SetRawInputAt(0, object);
7715 SetRawInputAt(1, target_class_or_null);
7716 DCHECK_EQ(check_kind == TypeCheckKind::kBitstringCheck, bitstring_path_to_root != nullptr);
7717 DCHECK_EQ(check_kind == TypeCheckKind::kBitstringCheck, bitstring_mask != nullptr);
7718 if (check_kind == TypeCheckKind::kBitstringCheck) {
7719 DCHECK(target_class_or_null->IsNullConstant());
7720 SetRawInputAt(2, bitstring_path_to_root);
7721 SetRawInputAt(3, bitstring_mask);
7722 } else {
7723 DCHECK(target_class_or_null->IsLoadClass());
7724 }
7725 }
7726
7727 HLoadClass* GetTargetClass() const {
7728 DCHECK_NE(GetTypeCheckKind(), TypeCheckKind::kBitstringCheck);
7729 HInstruction* load_class = InputAt(1);
7730 DCHECK(load_class->IsLoadClass());
7731 return load_class->AsLoadClass();
7732 }
7733
7734 uint32_t GetBitstringPathToRoot() const {
7735 DCHECK_EQ(GetTypeCheckKind(), TypeCheckKind::kBitstringCheck);
7736 HInstruction* path_to_root = InputAt(2);
7737 DCHECK(path_to_root->IsIntConstant());
7738 return static_cast<uint32_t>(path_to_root->AsIntConstant()->GetValue());
7739 }
7740
7741 uint32_t GetBitstringMask() const {
7742 DCHECK_EQ(GetTypeCheckKind(), TypeCheckKind::kBitstringCheck);
7743 HInstruction* mask = InputAt(3);
7744 DCHECK(mask->IsIntConstant());
7745 return static_cast<uint32_t>(mask->AsIntConstant()->GetValue());
7746 }
7747
7748 bool IsClonable() const override { return true; }
7749 bool CanBeMoved() const override { return true; }
7750
7751 bool InstructionDataEquals(const HInstruction* other) const override {
7752 DCHECK(other->IsInstanceOf() || other->IsCheckCast()) << other->DebugName();
7753 return GetPackedFields() == down_cast<const HTypeCheckInstruction*>(other)->GetPackedFields();
7754 }
7755
7756 bool MustDoNullCheck() const { return GetPackedFlag<kFlagMustDoNullCheck>(); }
7757 void ClearMustDoNullCheck() { SetPackedFlag<kFlagMustDoNullCheck>(false); }
7758 TypeCheckKind GetTypeCheckKind() const { return GetPackedField<TypeCheckKindField>(); }
7759 bool IsExactCheck() const { return GetTypeCheckKind() == TypeCheckKind::kExactCheck; }
7760
7761 ReferenceTypeInfo GetTargetClassRTI() {
7762 if (GetPackedFlag<kFlagValidTargetClassRTI>()) {
7763 // Note: The is_exact flag from the return value should not be used.
7764 return ReferenceTypeInfo::CreateUnchecked(klass_, /* is_exact= */ true);
7765 } else {
7766 return ReferenceTypeInfo::CreateInvalid();
7767 }
7768 }
7769
7770 // Target class RTI is marked as valid by RTP if the klass_ is admissible.
7771 void SetValidTargetClassRTI() {
7772 DCHECK(klass_ != nullptr);
7773 SetPackedFlag<kFlagValidTargetClassRTI>(true);
7774 }
7775
7776 Handle<mirror::Class> GetClass() const {
7777 return klass_;
7778 }
7779
7780 protected:
7781 DEFAULT_COPY_CONSTRUCTOR(TypeCheckInstruction);
7782
7783 private:
7784 static constexpr size_t kFieldTypeCheckKind = kNumberOfGenericPackedBits;
7785 static constexpr size_t kFieldTypeCheckKindSize =
7786 MinimumBitsToStore(static_cast<size_t>(TypeCheckKind::kLast));
7787 static constexpr size_t kFlagMustDoNullCheck = kFieldTypeCheckKind + kFieldTypeCheckKindSize;
7788 static constexpr size_t kFlagValidTargetClassRTI = kFlagMustDoNullCheck + 1;
7789 static constexpr size_t kNumberOfInstanceOfPackedBits = kFlagValidTargetClassRTI + 1;
7790 static_assert(kNumberOfInstanceOfPackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
7791 using TypeCheckKindField = BitField<TypeCheckKind, kFieldTypeCheckKind, kFieldTypeCheckKindSize>;
7792
7793 Handle<mirror::Class> klass_;
7794 };
7795
7796 class HInstanceOf final : public HTypeCheckInstruction {
7797 public:
7798 HInstanceOf(HInstruction* object,
7799 HInstruction* target_class_or_null,
7800 TypeCheckKind check_kind,
7801 Handle<mirror::Class> klass,
7802 uint32_t dex_pc,
7803 ArenaAllocator* allocator,
7804 HIntConstant* bitstring_path_to_root,
7805 HIntConstant* bitstring_mask)
7806 : HTypeCheckInstruction(kInstanceOf,
7807 DataType::Type::kBool,
7808 object,
7809 target_class_or_null,
7810 check_kind,
7811 klass,
7812 dex_pc,
7813 allocator,
7814 bitstring_path_to_root,
7815 bitstring_mask,
7816 SideEffectsForArchRuntimeCalls(check_kind)) {}
7817
7818 bool IsClonable() const override { return true; }
7819
7820 bool NeedsEnvironment() const override {
7821 return CanCallRuntime(GetTypeCheckKind());
7822 }
7823
7824 static bool CanCallRuntime(TypeCheckKind check_kind) {
7825 // TODO: Re-evaluate now that mips codegen has been removed.
7826 return check_kind != TypeCheckKind::kExactCheck;
7827 }
7828
7829 static SideEffects SideEffectsForArchRuntimeCalls(TypeCheckKind check_kind) {
7830 return CanCallRuntime(check_kind) ? SideEffects::CanTriggerGC() : SideEffects::None();
7831 }
7832
7833 DECLARE_INSTRUCTION(InstanceOf);
7834
7835 protected:
7836 DEFAULT_COPY_CONSTRUCTOR(InstanceOf);
7837 };
7838
7839 class HBoundType final : public HExpression<1> {
7840 public:
7841 explicit HBoundType(HInstruction* input, uint32_t dex_pc = kNoDexPc)
7842 : HExpression(kBoundType, DataType::Type::kReference, SideEffects::None(), dex_pc),
7843 upper_bound_(ReferenceTypeInfo::CreateInvalid()) {
7844 SetPackedFlag<kFlagUpperCanBeNull>(true);
7845 SetPackedFlag<kFlagCanBeNull>(true);
7846 DCHECK_EQ(input->GetType(), DataType::Type::kReference);
7847 SetRawInputAt(0, input);
7848 }
7849
7850 bool InstructionDataEquals(const HInstruction* other) const override;
7851 bool IsClonable() const override { return true; }
7852
7853 // {Get,Set}Upper* should only be used in reference type propagation.
7854 const ReferenceTypeInfo& GetUpperBound() const { return upper_bound_; }
7855 bool GetUpperCanBeNull() const { return GetPackedFlag<kFlagUpperCanBeNull>(); }
7856 void SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null);
7857
7858 void SetCanBeNull(bool can_be_null) {
7859 DCHECK(GetUpperCanBeNull() || !can_be_null);
7860 SetPackedFlag<kFlagCanBeNull>(can_be_null);
7861 }
7862
7863 bool CanBeNull() const override { return GetPackedFlag<kFlagCanBeNull>(); }
7864
7865 DECLARE_INSTRUCTION(BoundType);
7866
7867 protected:
7868 DEFAULT_COPY_CONSTRUCTOR(BoundType);
7869
7870 private:
7871 // Represents the top constraint that can_be_null_ cannot exceed (i.e. if this
7872 // is false then CanBeNull() cannot be true).
7873 static constexpr size_t kFlagUpperCanBeNull = kNumberOfGenericPackedBits;
7874 static constexpr size_t kFlagCanBeNull = kFlagUpperCanBeNull + 1;
7875 static constexpr size_t kNumberOfBoundTypePackedBits = kFlagCanBeNull + 1;
7876 static_assert(kNumberOfBoundTypePackedBits <= kMaxNumberOfPackedBits, "Too many packed fields.");
7877
7878 // Encodes the most upper class that this instruction can have. In other words
7879 // it is always the case that GetUpperBound().IsSupertypeOf(GetReferenceType()).
7880 // It is used to bound the type in cases like:
7881 // if (x instanceof ClassX) {
7882 // // uper_bound_ will be ClassX
7883 // }
7884 ReferenceTypeInfo upper_bound_;
7885 };
7886
7887 class HCheckCast final : public HTypeCheckInstruction {
7888 public:
7889 HCheckCast(HInstruction* object,
7890 HInstruction* target_class_or_null,
7891 TypeCheckKind check_kind,
7892 Handle<mirror::Class> klass,
7893 uint32_t dex_pc,
7894 ArenaAllocator* allocator,
7895 HIntConstant* bitstring_path_to_root,
7896 HIntConstant* bitstring_mask)
7897 : HTypeCheckInstruction(kCheckCast,
7898 DataType::Type::kVoid,
7899 object,
7900 target_class_or_null,
7901 check_kind,
7902 klass,
7903 dex_pc,
7904 allocator,
7905 bitstring_path_to_root,
7906 bitstring_mask,
7907 SideEffects::CanTriggerGC()) {}
7908
7909 bool IsClonable() const override { return true; }
7910 bool NeedsEnvironment() const override {
7911 // Instruction may throw a CheckCastError.
7912 return true;
7913 }
7914
7915 bool CanThrow() const override { return true; }
7916
7917 DECLARE_INSTRUCTION(CheckCast);
7918
7919 protected:
7920 DEFAULT_COPY_CONSTRUCTOR(CheckCast);
7921 };
7922
7923 /**
7924 * @brief Memory barrier types (see "The JSR-133 Cookbook for Compiler Writers").
7925 * @details We define the combined barrier types that are actually required
7926 * by the Java Memory Model, rather than using exactly the terminology from
7927 * the JSR-133 cookbook. These should, in many cases, be replaced by acquire/release
7928 * primitives. Note that the JSR-133 cookbook generally does not deal with
7929 * store atomicity issues, and the recipes there are not always entirely sufficient.
7930 * The current recipe is as follows:
7931 * -# Use AnyStore ~= (LoadStore | StoreStore) ~= release barrier before volatile store.
7932 * -# Use AnyAny barrier after volatile store. (StoreLoad is as expensive.)
7933 * -# Use LoadAny barrier ~= (LoadLoad | LoadStore) ~= acquire barrier after each volatile load.
7934 * -# Use StoreStore barrier after all stores but before return from any constructor whose
7935 * class has final fields.
7936 * -# Use NTStoreStore to order non-temporal stores with respect to all later
7937 * store-to-memory instructions. Only generated together with non-temporal stores.
7938 */
7939 enum MemBarrierKind {
7940 kAnyStore,
7941 kLoadAny,
7942 kStoreStore,
7943 kAnyAny,
7944 kNTStoreStore,
7945 kLastBarrierKind = kNTStoreStore
7946 };
7947 std::ostream& operator<<(std::ostream& os, MemBarrierKind kind);
7948
7949 class HMemoryBarrier final : public HExpression<0> {
7950 public:
7951 explicit HMemoryBarrier(MemBarrierKind barrier_kind, uint32_t dex_pc = kNoDexPc)
7952 : HExpression(kMemoryBarrier,
7953 SideEffects::AllWritesAndReads(), // Assume write/read on all fields/arrays.
7954 dex_pc) {
7955 SetPackedField<BarrierKindField>(barrier_kind);
7956 }
7957
7958 bool IsClonable() const override { return true; }
7959
7960 MemBarrierKind GetBarrierKind() { return GetPackedField<BarrierKindField>(); }
7961
7962 DECLARE_INSTRUCTION(MemoryBarrier);
7963
7964 protected:
7965 DEFAULT_COPY_CONSTRUCTOR(MemoryBarrier);
7966
7967 private:
7968 static constexpr size_t kFieldBarrierKind = HInstruction::kNumberOfGenericPackedBits;
7969 static constexpr size_t kFieldBarrierKindSize =
7970 MinimumBitsToStore(static_cast<size_t>(kLastBarrierKind));
7971 static constexpr size_t kNumberOfMemoryBarrierPackedBits =
7972 kFieldBarrierKind + kFieldBarrierKindSize;
7973 static_assert(kNumberOfMemoryBarrierPackedBits <= kMaxNumberOfPackedBits,
7974 "Too many packed fields.");
7975 using BarrierKindField = BitField<MemBarrierKind, kFieldBarrierKind, kFieldBarrierKindSize>;
7976 };
7977
7978 // A constructor fence orders all prior stores to fields that could be accessed via a final field of
7979 // the specified object(s), with respect to any subsequent store that might "publish"
7980 // (i.e. make visible) the specified object to another thread.
7981 //
7982 // JLS 17.5.1 "Semantics of final fields" states that a freeze action happens
7983 // for all final fields (that were set) at the end of the invoked constructor.
7984 //
7985 // The constructor fence models the freeze actions for the final fields of an object
7986 // being constructed (semantically at the end of the constructor). Constructor fences
7987 // have a per-object affinity; two separate objects being constructed get two separate
7988 // constructor fences.
7989 //
7990 // (Note: that if calling a super-constructor or forwarding to another constructor,
7991 // the freezes would happen at the end of *that* constructor being invoked).
7992 //
7993 // The memory model guarantees that when the object being constructed is "published" after
7994 // constructor completion (i.e. escapes the current thread via a store), then any final field
7995 // writes must be observable on other threads (once they observe that publication).
7996 //
7997 // Further, anything written before the freeze, and read by dereferencing through the final field,
7998 // must also be visible (so final object field could itself have an object with non-final fields;
7999 // yet the freeze must also extend to them).
8000 //
8001 // Constructor example:
8002 //
8003 // class HasFinal {
8004 // final int field; Optimizing IR for <init>()V:
8005 // HasFinal() {
8006 // field = 123; HInstanceFieldSet(this, HasFinal.field, 123)
8007 // // freeze(this.field); HConstructorFence(this)
8008 // } HReturn
8009 // }
8010 //
8011 // HConstructorFence can serve double duty as a fence for new-instance/new-array allocations of
8012 // already-initialized classes; in that case the allocation must act as a "default-initializer"
8013 // of the object which effectively writes the class pointer "final field".
8014 //
8015 // For example, we can model default-initialiation as roughly the equivalent of the following:
8016 //
8017 // class Object {
8018 // private final Class header;
8019 // }
8020 //
8021 // Java code: Optimizing IR:
8022 //
8023 // T new_instance<T>() {
8024 // Object obj = allocate_memory(T.class.size); obj = HInvoke(art_quick_alloc_object, T)
8025 // obj.header = T.class; // header write is done by above call.
8026 // // freeze(obj.header) HConstructorFence(obj)
8027 // return (T)obj;
8028 // }
8029 //
8030 // See also:
8031 // * DexCompilationUnit::RequiresConstructorBarrier
8032 // * QuasiAtomic::ThreadFenceForConstructor
8033 //
8034 class HConstructorFence final : public HVariableInputSizeInstruction {
8035 // A fence has variable inputs because the inputs can be removed
8036 // after prepare_for_register_allocation phase.
8037 // (TODO: In the future a fence could freeze multiple objects
8038 // after merging two fences together.)
8039 public:
8040 // `fence_object` is the reference that needs to be protected for correct publication.
8041 //
8042 // It makes sense in the following situations:
8043 // * <init> constructors, it's the "this" parameter (i.e. HParameterValue, s.t. IsThis() == true).
8044 // * new-instance-like instructions, it's the return value (i.e. HNewInstance).
8045 //
8046 // After construction the `fence_object` becomes the 0th input.
8047 // This is not an input in a real sense, but just a convenient place to stash the information
8048 // about the associated object.
8049 HConstructorFence(HInstruction* fence_object,
8050 uint32_t dex_pc,
8051 ArenaAllocator* allocator)
8052 // We strongly suspect there is not a more accurate way to describe the fine-grained reordering
8053 // constraints described in the class header. We claim that these SideEffects constraints
8054 // enforce a superset of the real constraints.
8055 //
8056 // The ordering described above is conservatively modeled with SideEffects as follows:
8057 //
8058 // * To prevent reordering of the publication stores:
8059 // ----> "Reads of objects" is the initial SideEffect.
8060 // * For every primitive final field store in the constructor:
8061 // ----> Union that field's type as a read (e.g. "Read of T") into the SideEffect.
8062 // * If there are any stores to reference final fields in the constructor:
8063 // ----> Use a more conservative "AllReads" SideEffect because any stores to any references
8064 // that are reachable from `fence_object` also need to be prevented for reordering
8065 // (and we do not want to do alias analysis to figure out what those stores are).
8066 //
8067 // In the implementation, this initially starts out as an "all reads" side effect; this is an
8068 // even more conservative approach than the one described above, and prevents all of the
8069 // above reordering without analyzing any of the instructions in the constructor.
8070 //
8071 // If in a later phase we discover that there are no writes to reference final fields,
8072 // we can refine the side effect to a smaller set of type reads (see above constraints).
8073 : HVariableInputSizeInstruction(kConstructorFence,
8074 SideEffects::AllReads(),
8075 dex_pc,
8076 allocator,
8077 /* number_of_inputs= */ 1,
8078 kArenaAllocConstructorFenceInputs) {
8079 DCHECK(fence_object != nullptr);
8080 SetRawInputAt(0, fence_object);
8081 }
8082
8083 // The object associated with this constructor fence.
8084 //
8085 // (Note: This will be null after the prepare_for_register_allocation phase,
8086 // as all constructor fence inputs are removed there).
8087 HInstruction* GetFenceObject() const {
8088 return InputAt(0);
8089 }
8090
8091 // Find all the HConstructorFence uses (`fence_use`) for `this` and:
8092 // - Delete `fence_use` from `this`'s use list.
8093 // - Delete `this` from `fence_use`'s inputs list.
8094 // - If the `fence_use` is dead, remove it from the graph.
8095 //
8096 // A fence is considered dead once it no longer has any uses
8097 // and all of the inputs are dead.
8098 //
8099 // This must *not* be called during/after prepare_for_register_allocation,
8100 // because that removes all the inputs to the fences but the fence is actually
8101 // still considered live.
8102 //
8103 // Returns how many HConstructorFence instructions were removed from graph.
8104 static size_t RemoveConstructorFences(HInstruction* instruction);
8105
8106 // Combine all inputs of `this` and `other` instruction and remove
8107 // `other` from the graph.
8108 //
8109 // Inputs are unique after the merge.
8110 //
8111 // Requirement: `this` must not be the same as `other.
8112 void Merge(HConstructorFence* other);
8113
8114 // Check if this constructor fence is protecting
8115 // an HNewInstance or HNewArray that is also the immediate
8116 // predecessor of `this`.
8117 //
8118 // If `ignore_inputs` is true, then the immediate predecessor doesn't need
8119 // to be one of the inputs of `this`.
8120 //
8121 // Returns the associated HNewArray or HNewInstance,
8122 // or null otherwise.
8123 HInstruction* GetAssociatedAllocation(bool ignore_inputs = false);
8124
8125 DECLARE_INSTRUCTION(ConstructorFence);
8126
8127 protected:
8128 DEFAULT_COPY_CONSTRUCTOR(ConstructorFence);
8129 };
8130
8131 class HMonitorOperation final : public HExpression<1> {
8132 public:
8133 enum class OperationKind {
8134 kEnter,
8135 kExit,
8136 kLast = kExit
8137 };
8138
8139 HMonitorOperation(HInstruction* object, OperationKind kind, uint32_t dex_pc)
8140 : HExpression(kMonitorOperation,
8141 SideEffects::AllExceptGCDependency(), // Assume write/read on all fields/arrays.
8142 dex_pc) {
8143 SetPackedField<OperationKindField>(kind);
8144 SetRawInputAt(0, object);
8145 }
8146
8147 // Instruction may go into runtime, so we need an environment.
8148 bool NeedsEnvironment() const override { return true; }
8149
8150 bool CanThrow() const override {
8151 // Verifier guarantees that monitor-exit cannot throw.
8152 // This is important because it allows the HGraphBuilder to remove
8153 // a dead throw-catch loop generated for `synchronized` blocks/methods.
8154 return IsEnter();
8155 }
8156
8157 OperationKind GetOperationKind() const { return GetPackedField<OperationKindField>(); }
8158 bool IsEnter() const { return GetOperationKind() == OperationKind::kEnter; }
8159
8160 DECLARE_INSTRUCTION(MonitorOperation);
8161
8162 protected:
8163 DEFAULT_COPY_CONSTRUCTOR(MonitorOperation);
8164
8165 private:
8166 static constexpr size_t kFieldOperationKind = HInstruction::kNumberOfGenericPackedBits;
8167 static constexpr size_t kFieldOperationKindSize =
8168 MinimumBitsToStore(static_cast<size_t>(OperationKind::kLast));
8169 static constexpr size_t kNumberOfMonitorOperationPackedBits =
8170 kFieldOperationKind + kFieldOperationKindSize;
8171 static_assert(kNumberOfMonitorOperationPackedBits <= HInstruction::kMaxNumberOfPackedBits,
8172 "Too many packed fields.");
8173 using OperationKindField = BitField<OperationKind, kFieldOperationKind, kFieldOperationKindSize>;
8174 };
8175
8176 class HSelect final : public HExpression<3> {
8177 public:
8178 HSelect(HInstruction* condition,
8179 HInstruction* true_value,
8180 HInstruction* false_value,
8181 uint32_t dex_pc)
8182 : HExpression(kSelect, HPhi::ToPhiType(true_value->GetType()), SideEffects::None(), dex_pc) {
8183 DCHECK_EQ(HPhi::ToPhiType(true_value->GetType()), HPhi::ToPhiType(false_value->GetType()));
8184
8185 // First input must be `true_value` or `false_value` to allow codegens to
8186 // use the SameAsFirstInput allocation policy. We make it `false_value`, so
8187 // that architectures which implement HSelect as a conditional move also
8188 // will not need to invert the condition.
8189 SetRawInputAt(0, false_value);
8190 SetRawInputAt(1, true_value);
8191 SetRawInputAt(2, condition);
8192 }
8193
8194 bool IsClonable() const override { return true; }
8195 HInstruction* GetFalseValue() const { return InputAt(0); }
8196 HInstruction* GetTrueValue() const { return InputAt(1); }
8197 HInstruction* GetCondition() const { return InputAt(2); }
8198
8199 bool CanBeMoved() const override { return true; }
8200 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
8201 return true;
8202 }
8203
8204 bool CanBeNull() const override {
8205 return GetTrueValue()->CanBeNull() || GetFalseValue()->CanBeNull();
8206 }
8207
8208 DECLARE_INSTRUCTION(Select);
8209
8210 protected:
8211 DEFAULT_COPY_CONSTRUCTOR(Select);
8212 };
8213
8214 class MoveOperands : public ArenaObject<kArenaAllocMoveOperands> {
8215 public:
8216 MoveOperands(Location source,
8217 Location destination,
8218 DataType::Type type,
8219 HInstruction* instruction)
8220 : source_(source), destination_(destination), type_(type), instruction_(instruction) {}
8221
8222 Location GetSource() const { return source_; }
8223 Location GetDestination() const { return destination_; }
8224
8225 void SetSource(Location value) { source_ = value; }
8226 void SetDestination(Location value) { destination_ = value; }
8227
8228 // The parallel move resolver marks moves as "in-progress" by clearing the
8229 // destination (but not the source).
8230 Location MarkPending() {
8231 DCHECK(!IsPending());
8232 Location dest = destination_;
8233 destination_ = Location::NoLocation();
8234 return dest;
8235 }
8236
8237 void ClearPending(Location dest) {
8238 DCHECK(IsPending());
8239 destination_ = dest;
8240 }
8241
8242 bool IsPending() const {
8243 DCHECK(source_.IsValid() || destination_.IsInvalid());
8244 return destination_.IsInvalid() && source_.IsValid();
8245 }
8246
8247 // True if this blocks a move from the given location.
8248 bool Blocks(Location loc) const {
8249 return !IsEliminated() && source_.OverlapsWith(loc);
8250 }
8251
8252 // A move is redundant if it's been eliminated, if its source and
8253 // destination are the same, or if its destination is unneeded.
8254 bool IsRedundant() const {
8255 return IsEliminated() || destination_.IsInvalid() || source_.Equals(destination_);
8256 }
8257
8258 // We clear both operands to indicate move that's been eliminated.
8259 void Eliminate() {
8260 source_ = destination_ = Location::NoLocation();
8261 }
8262
8263 bool IsEliminated() const {
8264 DCHECK_IMPLIES(source_.IsInvalid(), destination_.IsInvalid());
8265 return source_.IsInvalid();
8266 }
8267
8268 DataType::Type GetType() const { return type_; }
8269
8270 bool Is64BitMove() const {
8271 return DataType::Is64BitType(type_);
8272 }
8273
8274 HInstruction* GetInstruction() const { return instruction_; }
8275
8276 private:
8277 Location source_;
8278 Location destination_;
8279 // The type this move is for.
8280 DataType::Type type_;
8281 // The instruction this move is assocatied with. Null when this move is
8282 // for moving an input in the expected locations of user (including a phi user).
8283 // This is only used in debug mode, to ensure we do not connect interval siblings
8284 // in the same parallel move.
8285 HInstruction* instruction_;
8286 };
8287
8288 std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs);
8289
8290 static constexpr size_t kDefaultNumberOfMoves = 4;
8291
8292 class HParallelMove final : public HExpression<0> {
8293 public:
8294 explicit HParallelMove(ArenaAllocator* allocator, uint32_t dex_pc = kNoDexPc)
8295 : HExpression(kParallelMove, SideEffects::None(), dex_pc),
8296 moves_(allocator->Adapter(kArenaAllocMoveOperands)) {
8297 moves_.reserve(kDefaultNumberOfMoves);
8298 }
8299
8300 void AddMove(Location source,
8301 Location destination,
8302 DataType::Type type,
8303 HInstruction* instruction) {
8304 DCHECK(source.IsValid());
8305 DCHECK(destination.IsValid());
8306 if (kIsDebugBuild) {
8307 if (instruction != nullptr) {
8308 for (const MoveOperands& move : moves_) {
8309 if (move.GetInstruction() == instruction) {
8310 // Special case the situation where the move is for the spill slot
8311 // of the instruction.
8312 if ((GetPrevious() == instruction)
8313 || ((GetPrevious() == nullptr)
8314 && instruction->IsPhi()
8315 && instruction->GetBlock() == GetBlock())) {
8316 DCHECK_NE(destination.GetKind(), move.GetDestination().GetKind())
8317 << "Doing parallel moves for the same instruction.";
8318 } else {
8319 DCHECK(false) << "Doing parallel moves for the same instruction.";
8320 }
8321 }
8322 }
8323 }
8324 for (const MoveOperands& move : moves_) {
8325 DCHECK(!destination.OverlapsWith(move.GetDestination()))
8326 << "Overlapped destination for two moves in a parallel move: "
8327 << move.GetSource() << " ==> " << move.GetDestination() << " and "
8328 << source << " ==> " << destination << " for " << SafePrint(instruction);
8329 }
8330 }
8331 moves_.emplace_back(source, destination, type, instruction);
8332 }
8333
8334 MoveOperands* MoveOperandsAt(size_t index) {
8335 return &moves_[index];
8336 }
8337
8338 size_t NumMoves() const { return moves_.size(); }
8339
8340 DECLARE_INSTRUCTION(ParallelMove);
8341
8342 protected:
8343 DEFAULT_COPY_CONSTRUCTOR(ParallelMove);
8344
8345 private:
8346 ArenaVector<MoveOperands> moves_;
8347 };
8348
8349 // This instruction computes an intermediate address pointing in the 'middle' of an object. The
8350 // result pointer cannot be handled by GC, so extra care is taken to make sure that this value is
8351 // never used across anything that can trigger GC.
8352 // The result of this instruction is not a pointer in the sense of `DataType::Type::kreference`.
8353 // So we represent it by the type `DataType::Type::kInt`.
8354 class HIntermediateAddress final : public HExpression<2> {
8355 public:
8356 HIntermediateAddress(HInstruction* base_address, HInstruction* offset, uint32_t dex_pc)
8357 : HExpression(kIntermediateAddress,
8358 DataType::Type::kInt32,
8359 SideEffects::DependsOnGC(),
8360 dex_pc) {
8361 DCHECK_EQ(DataType::Size(DataType::Type::kInt32),
8362 DataType::Size(DataType::Type::kReference))
8363 << "kPrimInt and kPrimNot have different sizes.";
8364 SetRawInputAt(0, base_address);
8365 SetRawInputAt(1, offset);
8366 }
8367
8368 bool IsClonable() const override { return true; }
8369 bool CanBeMoved() const override { return true; }
8370 bool InstructionDataEquals(const HInstruction* other ATTRIBUTE_UNUSED) const override {
8371 return true;
8372 }
8373 bool IsActualObject() const override { return false; }
8374
8375 HInstruction* GetBaseAddress() const { return InputAt(0); }
8376 HInstruction* GetOffset() const { return InputAt(1); }
8377
8378 DECLARE_INSTRUCTION(IntermediateAddress);
8379
8380 protected:
8381 DEFAULT_COPY_CONSTRUCTOR(IntermediateAddress);
8382 };
8383
8384
8385 } // namespace art
8386
8387 #include "nodes_vector.h"
8388
8389 #if defined(ART_ENABLE_CODEGEN_arm) || defined(ART_ENABLE_CODEGEN_arm64)
8390 #include "nodes_shared.h"
8391 #endif
8392 #if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
8393 #include "nodes_x86.h"
8394 #endif
8395
8396 namespace art {
8397
8398 class OptimizingCompilerStats;
8399
8400 class HGraphVisitor : public ValueObject {
8401 public:
8402 explicit HGraphVisitor(HGraph* graph, OptimizingCompilerStats* stats = nullptr)
8403 : stats_(stats),
8404 graph_(graph) {}
8405 virtual ~HGraphVisitor() {}
8406
8407 virtual void VisitInstruction(HInstruction* instruction ATTRIBUTE_UNUSED) {}
8408 virtual void VisitBasicBlock(HBasicBlock* block);
8409
8410 // Visit the graph following basic block insertion order.
8411 void VisitInsertionOrder();
8412
8413 // Visit the graph following dominator tree reverse post-order.
8414 void VisitReversePostOrder();
8415
8416 HGraph* GetGraph() const { return graph_; }
8417
8418 // Visit functions for instruction classes.
8419 #define DECLARE_VISIT_INSTRUCTION(name, super) \
8420 virtual void Visit##name(H##name* instr) { VisitInstruction(instr); }
8421
8422 FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION)
8423
8424 #undef DECLARE_VISIT_INSTRUCTION
8425
8426 protected:
8427 OptimizingCompilerStats* stats_;
8428
8429 private:
8430 HGraph* const graph_;
8431
8432 DISALLOW_COPY_AND_ASSIGN(HGraphVisitor);
8433 };
8434
8435 class HGraphDelegateVisitor : public HGraphVisitor {
8436 public:
8437 explicit HGraphDelegateVisitor(HGraph* graph, OptimizingCompilerStats* stats = nullptr)
8438 : HGraphVisitor(graph, stats) {}
8439 virtual ~HGraphDelegateVisitor() {}
8440
8441 // Visit functions that delegate to to super class.
8442 #define DECLARE_VISIT_INSTRUCTION(name, super) \
8443 void Visit##name(H##name* instr) override { Visit##super(instr); }
8444
8445 FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION)
8446
8447 #undef DECLARE_VISIT_INSTRUCTION
8448
8449 private:
8450 DISALLOW_COPY_AND_ASSIGN(HGraphDelegateVisitor);
8451 };
8452
8453 // Create a clone of the instruction, insert it into the graph; replace the old one with a new
8454 // and remove the old instruction.
8455 HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr);
8456
8457 // Create a clone for each clonable instructions/phis and replace the original with the clone.
8458 //
8459 // Used for testing individual instruction cloner.
8460 class CloneAndReplaceInstructionVisitor : public HGraphDelegateVisitor {
8461 public:
8462 explicit CloneAndReplaceInstructionVisitor(HGraph* graph)
8463 : HGraphDelegateVisitor(graph), instr_replaced_by_clones_count_(0) {}
8464
8465 void VisitInstruction(HInstruction* instruction) override {
8466 if (instruction->IsClonable()) {
8467 ReplaceInstrOrPhiByClone(instruction);
8468 instr_replaced_by_clones_count_++;
8469 }
8470 }
8471
8472 size_t GetInstrReplacedByClonesCount() const { return instr_replaced_by_clones_count_; }
8473
8474 private:
8475 size_t instr_replaced_by_clones_count_;
8476
8477 DISALLOW_COPY_AND_ASSIGN(CloneAndReplaceInstructionVisitor);
8478 };
8479
8480 // Iterator over the blocks that art part of the loop. Includes blocks part
8481 // of an inner loop. The order in which the blocks are iterated is on their
8482 // block id.
8483 class HBlocksInLoopIterator : public ValueObject {
8484 public:
8485 explicit HBlocksInLoopIterator(const HLoopInformation& info)
8486 : blocks_in_loop_(info.GetBlocks()),
8487 blocks_(info.GetHeader()->GetGraph()->GetBlocks()),
8488 index_(0) {
8489 if (!blocks_in_loop_.IsBitSet(index_)) {
8490 Advance();
8491 }
8492 }
8493
8494 bool Done() const { return index_ == blocks_.size(); }
8495 HBasicBlock* Current() const { return blocks_[index_]; }
8496 void Advance() {
8497 ++index_;
8498 for (size_t e = blocks_.size(); index_ < e; ++index_) {
8499 if (blocks_in_loop_.IsBitSet(index_)) {
8500 break;
8501 }
8502 }
8503 }
8504
8505 private:
8506 const BitVector& blocks_in_loop_;
8507 const ArenaVector<HBasicBlock*>& blocks_;
8508 size_t index_;
8509
8510 DISALLOW_COPY_AND_ASSIGN(HBlocksInLoopIterator);
8511 };
8512
8513 // Iterator over the blocks that art part of the loop. Includes blocks part
8514 // of an inner loop. The order in which the blocks are iterated is reverse
8515 // post order.
8516 class HBlocksInLoopReversePostOrderIterator : public ValueObject {
8517 public:
8518 explicit HBlocksInLoopReversePostOrderIterator(const HLoopInformation& info)
8519 : blocks_in_loop_(info.GetBlocks()),
8520 blocks_(info.GetHeader()->GetGraph()->GetReversePostOrder()),
8521 index_(0) {
8522 if (!blocks_in_loop_.IsBitSet(blocks_[index_]->GetBlockId())) {
8523 Advance();
8524 }
8525 }
8526
8527 bool Done() const { return index_ == blocks_.size(); }
8528 HBasicBlock* Current() const { return blocks_[index_]; }
8529 void Advance() {
8530 ++index_;
8531 for (size_t e = blocks_.size(); index_ < e; ++index_) {
8532 if (blocks_in_loop_.IsBitSet(blocks_[index_]->GetBlockId())) {
8533 break;
8534 }
8535 }
8536 }
8537
8538 private:
8539 const BitVector& blocks_in_loop_;
8540 const ArenaVector<HBasicBlock*>& blocks_;
8541 size_t index_;
8542
8543 DISALLOW_COPY_AND_ASSIGN(HBlocksInLoopReversePostOrderIterator);
8544 };
8545
8546 // Returns int64_t value of a properly typed constant.
8547 inline int64_t Int64FromConstant(HConstant* constant) {
8548 if (constant->IsIntConstant()) {
8549 return constant->AsIntConstant()->GetValue();
8550 } else if (constant->IsLongConstant()) {
8551 return constant->AsLongConstant()->GetValue();
8552 } else {
8553 DCHECK(constant->IsNullConstant()) << constant->DebugName();
8554 return 0;
8555 }
8556 }
8557
8558 // Returns true iff instruction is an integral constant (and sets value on success).
8559 inline bool IsInt64AndGet(HInstruction* instruction, /*out*/ int64_t* value) {
8560 if (instruction->IsIntConstant()) {
8561 *value = instruction->AsIntConstant()->GetValue();
8562 return true;
8563 } else if (instruction->IsLongConstant()) {
8564 *value = instruction->AsLongConstant()->GetValue();
8565 return true;
8566 } else if (instruction->IsNullConstant()) {
8567 *value = 0;
8568 return true;
8569 }
8570 return false;
8571 }
8572
8573 // Returns true iff instruction is the given integral constant.
8574 inline bool IsInt64Value(HInstruction* instruction, int64_t value) {
8575 int64_t val = 0;
8576 return IsInt64AndGet(instruction, &val) && val == value;
8577 }
8578
8579 // Returns true iff instruction is a zero bit pattern.
8580 inline bool IsZeroBitPattern(HInstruction* instruction) {
8581 return instruction->IsConstant() && instruction->AsConstant()->IsZeroBitPattern();
8582 }
8583
8584 // Implement HInstruction::Is##type() for concrete instructions.
8585 #define INSTRUCTION_TYPE_CHECK(type, super) \
8586 inline bool HInstruction::Is##type() const { return GetKind() == k##type; }
8587 FOR_EACH_CONCRETE_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
8588 #undef INSTRUCTION_TYPE_CHECK
8589
8590 // Implement HInstruction::Is##type() for abstract instructions.
8591 #define INSTRUCTION_TYPE_CHECK_RESULT(type, super) \
8592 std::is_base_of<BaseType, H##type>::value,
8593 #define INSTRUCTION_TYPE_CHECK(type, super) \
8594 inline bool HInstruction::Is##type() const { \
8595 DCHECK_LT(GetKind(), kLastInstructionKind); \
8596 using BaseType = H##type; \
8597 static constexpr bool results[] = { \
8598 FOR_EACH_CONCRETE_INSTRUCTION(INSTRUCTION_TYPE_CHECK_RESULT) \
8599 }; \
8600 return results[static_cast<size_t>(GetKind())]; \
8601 }
8602
8603 FOR_EACH_ABSTRACT_INSTRUCTION(INSTRUCTION_TYPE_CHECK)
8604 #undef INSTRUCTION_TYPE_CHECK
8605 #undef INSTRUCTION_TYPE_CHECK_RESULT
8606
8607 #define INSTRUCTION_TYPE_CAST(type, super) \
8608 inline const H##type* HInstruction::As##type() const { \
8609 return Is##type() ? down_cast<const H##type*>(this) : nullptr; \
8610 } \
8611 inline H##type* HInstruction::As##type() { \
8612 return Is##type() ? static_cast<H##type*>(this) : nullptr; \
8613 }
8614
8615 FOR_EACH_INSTRUCTION(INSTRUCTION_TYPE_CAST)
8616 #undef INSTRUCTION_TYPE_CAST
8617
8618
8619 // Create space in `blocks` for adding `number_of_new_blocks` entries
8620 // starting at location `at`. Blocks after `at` are moved accordingly.
8621 inline void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
8622 size_t number_of_new_blocks,
8623 size_t after) {
8624 DCHECK_LT(after, blocks->size());
8625 size_t old_size = blocks->size();
8626 size_t new_size = old_size + number_of_new_blocks;
8627 blocks->resize(new_size);
8628 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
8629 }
8630
8631 /*
8632 * Hunt "under the hood" of array lengths (leading to array references),
8633 * null checks (also leading to array references), and new arrays
8634 * (leading to the actual length). This makes it more likely related
8635 * instructions become actually comparable.
8636 */
8637 inline HInstruction* HuntForDeclaration(HInstruction* instruction) {
8638 while (instruction->IsArrayLength() ||
8639 instruction->IsNullCheck() ||
8640 instruction->IsNewArray()) {
8641 instruction = instruction->IsNewArray()
8642 ? instruction->AsNewArray()->GetLength()
8643 : instruction->InputAt(0);
8644 }
8645 return instruction;
8646 }
8647
8648 inline bool IsAddOrSub(const HInstruction* instruction) {
8649 return instruction->IsAdd() || instruction->IsSub();
8650 }
8651
8652 void RemoveEnvironmentUses(HInstruction* instruction);
8653 bool HasEnvironmentUsedByOthers(HInstruction* instruction);
8654 void ResetEnvironmentInputRecords(HInstruction* instruction);
8655
8656 // Detects an instruction that is >= 0. As long as the value is carried by
8657 // a single instruction, arithmetic wrap-around cannot occur.
8658 bool IsGEZero(HInstruction* instruction);
8659
8660 } // namespace art
8661
8662 #endif // ART_COMPILER_OPTIMIZING_NODES_H_
8663