nodes.h revision 0cf4493166ff28518c8eafa2d0463f6e817cce75
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 "base/arena_bit_vector.h" 25#include "base/arena_containers.h" 26#include "base/arena_object.h" 27#include "base/stl_util.h" 28#include "dex/compiler_enums.h" 29#include "entrypoints/quick/quick_entrypoints_enum.h" 30#include "handle.h" 31#include "handle_scope.h" 32#include "invoke_type.h" 33#include "locations.h" 34#include "method_reference.h" 35#include "mirror/class.h" 36#include "offsets.h" 37#include "primitive.h" 38#include "utils/array_ref.h" 39 40namespace art { 41 42class GraphChecker; 43class HBasicBlock; 44class HCurrentMethod; 45class HDoubleConstant; 46class HEnvironment; 47class HFakeString; 48class HFloatConstant; 49class HGraphBuilder; 50class HGraphVisitor; 51class HInstruction; 52class HIntConstant; 53class HInvoke; 54class HLongConstant; 55class HNullConstant; 56class HPhi; 57class HSuspendCheck; 58class HTryBoundary; 59class LiveInterval; 60class LocationSummary; 61class SlowPathCode; 62class SsaBuilder; 63 64namespace mirror { 65class DexCache; 66} // namespace mirror 67 68static const int kDefaultNumberOfBlocks = 8; 69static const int kDefaultNumberOfSuccessors = 2; 70static const int kDefaultNumberOfPredecessors = 2; 71static const int kDefaultNumberOfExceptionalPredecessors = 0; 72static const int kDefaultNumberOfDominatedBlocks = 1; 73static const int kDefaultNumberOfBackEdges = 1; 74 75static constexpr uint32_t kMaxIntShiftValue = 0x1f; 76static constexpr uint64_t kMaxLongShiftValue = 0x3f; 77 78static constexpr uint32_t kUnknownFieldIndex = static_cast<uint32_t>(-1); 79static constexpr uint16_t kUnknownClassDefIndex = static_cast<uint16_t>(-1); 80 81static constexpr InvokeType kInvalidInvokeType = static_cast<InvokeType>(-1); 82 83static constexpr uint32_t kNoDexPc = -1; 84 85enum IfCondition { 86 // All types. 87 kCondEQ, // == 88 kCondNE, // != 89 // Signed integers and floating-point numbers. 90 kCondLT, // < 91 kCondLE, // <= 92 kCondGT, // > 93 kCondGE, // >= 94 // Unsigned integers. 95 kCondB, // < 96 kCondBE, // <= 97 kCondA, // > 98 kCondAE, // >= 99}; 100 101class HInstructionList : public ValueObject { 102 public: 103 HInstructionList() : first_instruction_(nullptr), last_instruction_(nullptr) {} 104 105 void AddInstruction(HInstruction* instruction); 106 void RemoveInstruction(HInstruction* instruction); 107 108 // Insert `instruction` before/after an existing instruction `cursor`. 109 void InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor); 110 void InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor); 111 112 // Return true if this list contains `instruction`. 113 bool Contains(HInstruction* instruction) const; 114 115 // Return true if `instruction1` is found before `instruction2` in 116 // this instruction list and false otherwise. Abort if none 117 // of these instructions is found. 118 bool FoundBefore(const HInstruction* instruction1, 119 const HInstruction* instruction2) const; 120 121 bool IsEmpty() const { return first_instruction_ == nullptr; } 122 void Clear() { first_instruction_ = last_instruction_ = nullptr; } 123 124 // Update the block of all instructions to be `block`. 125 void SetBlockOfInstructions(HBasicBlock* block) const; 126 127 void AddAfter(HInstruction* cursor, const HInstructionList& instruction_list); 128 void Add(const HInstructionList& instruction_list); 129 130 // Return the number of instructions in the list. This is an expensive operation. 131 size_t CountSize() const; 132 133 private: 134 HInstruction* first_instruction_; 135 HInstruction* last_instruction_; 136 137 friend class HBasicBlock; 138 friend class HGraph; 139 friend class HInstruction; 140 friend class HInstructionIterator; 141 friend class HBackwardInstructionIterator; 142 143 DISALLOW_COPY_AND_ASSIGN(HInstructionList); 144}; 145 146// Control-flow graph of a method. Contains a list of basic blocks. 147class HGraph : public ArenaObject<kArenaAllocGraph> { 148 public: 149 HGraph(ArenaAllocator* arena, 150 const DexFile& dex_file, 151 uint32_t method_idx, 152 bool should_generate_constructor_barrier, 153 InstructionSet instruction_set, 154 InvokeType invoke_type = kInvalidInvokeType, 155 bool debuggable = false, 156 int start_instruction_id = 0) 157 : arena_(arena), 158 blocks_(arena->Adapter(kArenaAllocBlockList)), 159 reverse_post_order_(arena->Adapter(kArenaAllocReversePostOrder)), 160 linear_order_(arena->Adapter(kArenaAllocLinearOrder)), 161 entry_block_(nullptr), 162 exit_block_(nullptr), 163 maximum_number_of_out_vregs_(0), 164 number_of_vregs_(0), 165 number_of_in_vregs_(0), 166 temporaries_vreg_slots_(0), 167 has_bounds_checks_(false), 168 has_try_catch_(false), 169 debuggable_(debuggable), 170 current_instruction_id_(start_instruction_id), 171 dex_file_(dex_file), 172 method_idx_(method_idx), 173 invoke_type_(invoke_type), 174 in_ssa_form_(false), 175 should_generate_constructor_barrier_(should_generate_constructor_barrier), 176 instruction_set_(instruction_set), 177 cached_null_constant_(nullptr), 178 cached_int_constants_(std::less<int32_t>(), arena->Adapter(kArenaAllocConstantsMap)), 179 cached_float_constants_(std::less<int32_t>(), arena->Adapter(kArenaAllocConstantsMap)), 180 cached_long_constants_(std::less<int64_t>(), arena->Adapter(kArenaAllocConstantsMap)), 181 cached_double_constants_(std::less<int64_t>(), arena->Adapter(kArenaAllocConstantsMap)), 182 cached_current_method_(nullptr) { 183 blocks_.reserve(kDefaultNumberOfBlocks); 184 } 185 186 ArenaAllocator* GetArena() const { return arena_; } 187 const ArenaVector<HBasicBlock*>& GetBlocks() const { return blocks_; } 188 189 bool IsInSsaForm() const { return in_ssa_form_; } 190 191 HBasicBlock* GetEntryBlock() const { return entry_block_; } 192 HBasicBlock* GetExitBlock() const { return exit_block_; } 193 bool HasExitBlock() const { return exit_block_ != nullptr; } 194 195 void SetEntryBlock(HBasicBlock* block) { entry_block_ = block; } 196 void SetExitBlock(HBasicBlock* block) { exit_block_ = block; } 197 198 void AddBlock(HBasicBlock* block); 199 200 // Try building the SSA form of this graph, with dominance computation and loop 201 // recognition. Returns whether it was successful in doing all these steps. 202 bool TryBuildingSsa() { 203 BuildDominatorTree(); 204 // The SSA builder requires loops to all be natural. Specifically, the dead phi 205 // elimination phase checks the consistency of the graph when doing a post-order 206 // visit for eliminating dead phis: a dead phi can only have loop header phi 207 // users remaining when being visited. 208 if (!AnalyzeNaturalLoops()) return false; 209 // Precompute per-block try membership before entering the SSA builder, 210 // which needs the information to build catch block phis from values of 211 // locals at throwing instructions inside try blocks. 212 ComputeTryBlockInformation(); 213 TransformToSsa(); 214 in_ssa_form_ = true; 215 return true; 216 } 217 218 void ComputeDominanceInformation(); 219 void ClearDominanceInformation(); 220 221 void BuildDominatorTree(); 222 void TransformToSsa(); 223 void SimplifyCFG(); 224 void SimplifyCatchBlocks(); 225 226 // Analyze all natural loops in this graph. Returns false if one 227 // loop is not natural, that is the header does not dominate the 228 // back edge. 229 bool AnalyzeNaturalLoops() const; 230 231 // Iterate over blocks to compute try block membership. Needs reverse post 232 // order and loop information. 233 void ComputeTryBlockInformation(); 234 235 // Inline this graph in `outer_graph`, replacing the given `invoke` instruction. 236 // Returns the instruction used to replace the invoke expression or null if the 237 // invoke is for a void method. 238 HInstruction* InlineInto(HGraph* outer_graph, HInvoke* invoke); 239 240 // Need to add a couple of blocks to test if the loop body is entered and 241 // put deoptimization instructions, etc. 242 void TransformLoopHeaderForBCE(HBasicBlock* header); 243 244 // Removes `block` from the graph. Assumes `block` has been disconnected from 245 // other blocks and has no instructions or phis. 246 void DeleteDeadEmptyBlock(HBasicBlock* block); 247 248 // Splits the edge between `block` and `successor` while preserving the 249 // indices in the predecessor/successor lists. If there are multiple edges 250 // between the blocks, the lowest indices are used. 251 // Returns the new block which is empty and has the same dex pc as `successor`. 252 HBasicBlock* SplitEdge(HBasicBlock* block, HBasicBlock* successor); 253 254 void SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor); 255 void SimplifyLoop(HBasicBlock* header); 256 257 int32_t GetNextInstructionId() { 258 DCHECK_NE(current_instruction_id_, INT32_MAX); 259 return current_instruction_id_++; 260 } 261 262 int32_t GetCurrentInstructionId() const { 263 return current_instruction_id_; 264 } 265 266 void SetCurrentInstructionId(int32_t id) { 267 current_instruction_id_ = id; 268 } 269 270 uint16_t GetMaximumNumberOfOutVRegs() const { 271 return maximum_number_of_out_vregs_; 272 } 273 274 void SetMaximumNumberOfOutVRegs(uint16_t new_value) { 275 maximum_number_of_out_vregs_ = new_value; 276 } 277 278 void UpdateMaximumNumberOfOutVRegs(uint16_t other_value) { 279 maximum_number_of_out_vregs_ = std::max(maximum_number_of_out_vregs_, other_value); 280 } 281 282 void UpdateTemporariesVRegSlots(size_t slots) { 283 temporaries_vreg_slots_ = std::max(slots, temporaries_vreg_slots_); 284 } 285 286 size_t GetTemporariesVRegSlots() const { 287 DCHECK(!in_ssa_form_); 288 return temporaries_vreg_slots_; 289 } 290 291 void SetNumberOfVRegs(uint16_t number_of_vregs) { 292 number_of_vregs_ = number_of_vregs; 293 } 294 295 uint16_t GetNumberOfVRegs() const { 296 return number_of_vregs_; 297 } 298 299 void SetNumberOfInVRegs(uint16_t value) { 300 number_of_in_vregs_ = value; 301 } 302 303 uint16_t GetNumberOfLocalVRegs() const { 304 DCHECK(!in_ssa_form_); 305 return number_of_vregs_ - number_of_in_vregs_; 306 } 307 308 const ArenaVector<HBasicBlock*>& GetReversePostOrder() const { 309 return reverse_post_order_; 310 } 311 312 const ArenaVector<HBasicBlock*>& GetLinearOrder() const { 313 return linear_order_; 314 } 315 316 bool HasBoundsChecks() const { 317 return has_bounds_checks_; 318 } 319 320 void SetHasBoundsChecks(bool value) { 321 has_bounds_checks_ = value; 322 } 323 324 bool ShouldGenerateConstructorBarrier() const { 325 return should_generate_constructor_barrier_; 326 } 327 328 bool IsDebuggable() const { return debuggable_; } 329 330 // Returns a constant of the given type and value. If it does not exist 331 // already, it is created and inserted into the graph. This method is only for 332 // integral types. 333 HConstant* GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc = kNoDexPc); 334 335 // TODO: This is problematic for the consistency of reference type propagation 336 // because it can be created anytime after the pass and thus it will be left 337 // with an invalid type. 338 HNullConstant* GetNullConstant(uint32_t dex_pc = kNoDexPc); 339 340 HIntConstant* GetIntConstant(int32_t value, uint32_t dex_pc = kNoDexPc) { 341 return CreateConstant(value, &cached_int_constants_, dex_pc); 342 } 343 HLongConstant* GetLongConstant(int64_t value, uint32_t dex_pc = kNoDexPc) { 344 return CreateConstant(value, &cached_long_constants_, dex_pc); 345 } 346 HFloatConstant* GetFloatConstant(float value, uint32_t dex_pc = kNoDexPc) { 347 return CreateConstant(bit_cast<int32_t, float>(value), &cached_float_constants_, dex_pc); 348 } 349 HDoubleConstant* GetDoubleConstant(double value, uint32_t dex_pc = kNoDexPc) { 350 return CreateConstant(bit_cast<int64_t, double>(value), &cached_double_constants_, dex_pc); 351 } 352 353 HCurrentMethod* GetCurrentMethod(); 354 355 const DexFile& GetDexFile() const { 356 return dex_file_; 357 } 358 359 uint32_t GetMethodIdx() const { 360 return method_idx_; 361 } 362 363 InvokeType GetInvokeType() const { 364 return invoke_type_; 365 } 366 367 InstructionSet GetInstructionSet() const { 368 return instruction_set_; 369 } 370 371 bool HasTryCatch() const { return has_try_catch_; } 372 void SetHasTryCatch(bool value) { has_try_catch_ = value; } 373 374 ArtMethod* GetArtMethod() const { return art_method_; } 375 void SetArtMethod(ArtMethod* method) { art_method_ = method; } 376 377 // Returns an instruction with the opposite boolean value from 'cond'. 378 // The instruction has been inserted into the graph, either as a constant, or 379 // before cursor. 380 HInstruction* InsertOppositeCondition(HInstruction* cond, HInstruction* cursor); 381 382 private: 383 void FindBackEdges(ArenaBitVector* visited); 384 void RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const; 385 void RemoveDeadBlocks(const ArenaBitVector& visited); 386 387 template <class InstructionType, typename ValueType> 388 InstructionType* CreateConstant(ValueType value, 389 ArenaSafeMap<ValueType, InstructionType*>* cache, 390 uint32_t dex_pc = kNoDexPc) { 391 // Try to find an existing constant of the given value. 392 InstructionType* constant = nullptr; 393 auto cached_constant = cache->find(value); 394 if (cached_constant != cache->end()) { 395 constant = cached_constant->second; 396 } 397 398 // If not found or previously deleted, create and cache a new instruction. 399 // Don't bother reviving a previously deleted instruction, for simplicity. 400 if (constant == nullptr || constant->GetBlock() == nullptr) { 401 constant = new (arena_) InstructionType(value, dex_pc); 402 cache->Overwrite(value, constant); 403 InsertConstant(constant); 404 } 405 return constant; 406 } 407 408 void InsertConstant(HConstant* instruction); 409 410 // Cache a float constant into the graph. This method should only be 411 // called by the SsaBuilder when creating "equivalent" instructions. 412 void CacheFloatConstant(HFloatConstant* constant); 413 414 // See CacheFloatConstant comment. 415 void CacheDoubleConstant(HDoubleConstant* constant); 416 417 ArenaAllocator* const arena_; 418 419 // List of blocks in insertion order. 420 ArenaVector<HBasicBlock*> blocks_; 421 422 // List of blocks to perform a reverse post order tree traversal. 423 ArenaVector<HBasicBlock*> reverse_post_order_; 424 425 // List of blocks to perform a linear order tree traversal. 426 ArenaVector<HBasicBlock*> linear_order_; 427 428 HBasicBlock* entry_block_; 429 HBasicBlock* exit_block_; 430 431 // The maximum number of virtual registers arguments passed to a HInvoke in this graph. 432 uint16_t maximum_number_of_out_vregs_; 433 434 // The number of virtual registers in this method. Contains the parameters. 435 uint16_t number_of_vregs_; 436 437 // The number of virtual registers used by parameters of this method. 438 uint16_t number_of_in_vregs_; 439 440 // Number of vreg size slots that the temporaries use (used in baseline compiler). 441 size_t temporaries_vreg_slots_; 442 443 // Has bounds checks. We can totally skip BCE if it's false. 444 bool has_bounds_checks_; 445 446 // Flag whether there are any try/catch blocks in the graph. We will skip 447 // try/catch-related passes if false. 448 bool has_try_catch_; 449 450 // Indicates whether the graph should be compiled in a way that 451 // ensures full debuggability. If false, we can apply more 452 // aggressive optimizations that may limit the level of debugging. 453 const bool debuggable_; 454 455 // The current id to assign to a newly added instruction. See HInstruction.id_. 456 int32_t current_instruction_id_; 457 458 // The dex file from which the method is from. 459 const DexFile& dex_file_; 460 461 // The method index in the dex file. 462 const uint32_t method_idx_; 463 464 // If inlined, this encodes how the callee is being invoked. 465 const InvokeType invoke_type_; 466 467 // Whether the graph has been transformed to SSA form. Only used 468 // in debug mode to ensure we are not using properties only valid 469 // for non-SSA form (like the number of temporaries). 470 bool in_ssa_form_; 471 472 const bool should_generate_constructor_barrier_; 473 474 const InstructionSet instruction_set_; 475 476 // Cached constants. 477 HNullConstant* cached_null_constant_; 478 ArenaSafeMap<int32_t, HIntConstant*> cached_int_constants_; 479 ArenaSafeMap<int32_t, HFloatConstant*> cached_float_constants_; 480 ArenaSafeMap<int64_t, HLongConstant*> cached_long_constants_; 481 ArenaSafeMap<int64_t, HDoubleConstant*> cached_double_constants_; 482 483 HCurrentMethod* cached_current_method_; 484 485 // The ArtMethod this graph is for. Note that for AOT, it may be null, 486 // for example for methods whose declaring class could not be resolved 487 // (such as when the superclass could not be found). 488 ArtMethod* art_method_; 489 490 friend class SsaBuilder; // For caching constants. 491 friend class SsaLivenessAnalysis; // For the linear order. 492 ART_FRIEND_TEST(GraphTest, IfSuccessorSimpleJoinBlock1); 493 DISALLOW_COPY_AND_ASSIGN(HGraph); 494}; 495 496class HLoopInformation : public ArenaObject<kArenaAllocLoopInfo> { 497 public: 498 HLoopInformation(HBasicBlock* header, HGraph* graph) 499 : header_(header), 500 suspend_check_(nullptr), 501 back_edges_(graph->GetArena()->Adapter(kArenaAllocLoopInfoBackEdges)), 502 // Make bit vector growable, as the number of blocks may change. 503 blocks_(graph->GetArena(), graph->GetBlocks().size(), true) { 504 back_edges_.reserve(kDefaultNumberOfBackEdges); 505 } 506 507 HBasicBlock* GetHeader() const { 508 return header_; 509 } 510 511 void SetHeader(HBasicBlock* block) { 512 header_ = block; 513 } 514 515 HSuspendCheck* GetSuspendCheck() const { return suspend_check_; } 516 void SetSuspendCheck(HSuspendCheck* check) { suspend_check_ = check; } 517 bool HasSuspendCheck() const { return suspend_check_ != nullptr; } 518 519 void AddBackEdge(HBasicBlock* back_edge) { 520 back_edges_.push_back(back_edge); 521 } 522 523 void RemoveBackEdge(HBasicBlock* back_edge) { 524 RemoveElement(back_edges_, back_edge); 525 } 526 527 bool IsBackEdge(const HBasicBlock& block) const { 528 return ContainsElement(back_edges_, &block); 529 } 530 531 size_t NumberOfBackEdges() const { 532 return back_edges_.size(); 533 } 534 535 HBasicBlock* GetPreHeader() const; 536 537 const ArenaVector<HBasicBlock*>& GetBackEdges() const { 538 return back_edges_; 539 } 540 541 // Returns the lifetime position of the back edge that has the 542 // greatest lifetime position. 543 size_t GetLifetimeEnd() const; 544 545 void ReplaceBackEdge(HBasicBlock* existing, HBasicBlock* new_back_edge) { 546 ReplaceElement(back_edges_, existing, new_back_edge); 547 } 548 549 // Finds blocks that are part of this loop. Returns whether the loop is a natural loop, 550 // that is the header dominates the back edge. 551 bool Populate(); 552 553 // Reanalyzes the loop by removing loop info from its blocks and re-running 554 // Populate(). If there are no back edges left, the loop info is completely 555 // removed as well as its SuspendCheck instruction. It must be run on nested 556 // inner loops first. 557 void Update(); 558 559 // Returns whether this loop information contains `block`. 560 // Note that this loop information *must* be populated before entering this function. 561 bool Contains(const HBasicBlock& block) const; 562 563 // Returns whether this loop information is an inner loop of `other`. 564 // Note that `other` *must* be populated before entering this function. 565 bool IsIn(const HLoopInformation& other) const; 566 567 // Returns true if instruction is not defined within this loop. 568 bool IsDefinedOutOfTheLoop(HInstruction* instruction) const; 569 570 const ArenaBitVector& GetBlocks() const { return blocks_; } 571 572 void Add(HBasicBlock* block); 573 void Remove(HBasicBlock* block); 574 575 private: 576 // Internal recursive implementation of `Populate`. 577 void PopulateRecursive(HBasicBlock* block); 578 579 HBasicBlock* header_; 580 HSuspendCheck* suspend_check_; 581 ArenaVector<HBasicBlock*> back_edges_; 582 ArenaBitVector blocks_; 583 584 DISALLOW_COPY_AND_ASSIGN(HLoopInformation); 585}; 586 587// Stores try/catch information for basic blocks. 588// Note that HGraph is constructed so that catch blocks cannot simultaneously 589// be try blocks. 590class TryCatchInformation : public ArenaObject<kArenaAllocTryCatchInfo> { 591 public: 592 // Try block information constructor. 593 explicit TryCatchInformation(const HTryBoundary& try_entry) 594 : try_entry_(&try_entry), 595 catch_dex_file_(nullptr), 596 catch_type_index_(DexFile::kDexNoIndex16) { 597 DCHECK(try_entry_ != nullptr); 598 } 599 600 // Catch block information constructor. 601 TryCatchInformation(uint16_t catch_type_index, const DexFile& dex_file) 602 : try_entry_(nullptr), 603 catch_dex_file_(&dex_file), 604 catch_type_index_(catch_type_index) {} 605 606 bool IsTryBlock() const { return try_entry_ != nullptr; } 607 608 const HTryBoundary& GetTryEntry() const { 609 DCHECK(IsTryBlock()); 610 return *try_entry_; 611 } 612 613 bool IsCatchBlock() const { return catch_dex_file_ != nullptr; } 614 615 bool IsCatchAllTypeIndex() const { 616 DCHECK(IsCatchBlock()); 617 return catch_type_index_ == DexFile::kDexNoIndex16; 618 } 619 620 uint16_t GetCatchTypeIndex() const { 621 DCHECK(IsCatchBlock()); 622 return catch_type_index_; 623 } 624 625 const DexFile& GetCatchDexFile() const { 626 DCHECK(IsCatchBlock()); 627 return *catch_dex_file_; 628 } 629 630 private: 631 // One of possibly several TryBoundary instructions entering the block's try. 632 // Only set for try blocks. 633 const HTryBoundary* try_entry_; 634 635 // Exception type information. Only set for catch blocks. 636 const DexFile* catch_dex_file_; 637 const uint16_t catch_type_index_; 638}; 639 640static constexpr size_t kNoLifetime = -1; 641static constexpr uint32_t kInvalidBlockId = static_cast<uint32_t>(-1); 642 643// A block in a method. Contains the list of instructions represented 644// as a double linked list. Each block knows its predecessors and 645// successors. 646 647class HBasicBlock : public ArenaObject<kArenaAllocBasicBlock> { 648 public: 649 HBasicBlock(HGraph* graph, uint32_t dex_pc = kNoDexPc) 650 : graph_(graph), 651 predecessors_(graph->GetArena()->Adapter(kArenaAllocPredecessors)), 652 successors_(graph->GetArena()->Adapter(kArenaAllocSuccessors)), 653 loop_information_(nullptr), 654 dominator_(nullptr), 655 dominated_blocks_(graph->GetArena()->Adapter(kArenaAllocDominated)), 656 block_id_(kInvalidBlockId), 657 dex_pc_(dex_pc), 658 lifetime_start_(kNoLifetime), 659 lifetime_end_(kNoLifetime), 660 try_catch_information_(nullptr) { 661 predecessors_.reserve(kDefaultNumberOfPredecessors); 662 successors_.reserve(kDefaultNumberOfSuccessors); 663 dominated_blocks_.reserve(kDefaultNumberOfDominatedBlocks); 664 } 665 666 const ArenaVector<HBasicBlock*>& GetPredecessors() const { 667 return predecessors_; 668 } 669 670 const ArenaVector<HBasicBlock*>& GetSuccessors() const { 671 return successors_; 672 } 673 674 ArrayRef<HBasicBlock* const> GetNormalSuccessors() const; 675 ArrayRef<HBasicBlock* const> GetExceptionalSuccessors() const; 676 677 bool HasSuccessor(const HBasicBlock* block, size_t start_from = 0u) { 678 return ContainsElement(successors_, block, start_from); 679 } 680 681 const ArenaVector<HBasicBlock*>& GetDominatedBlocks() const { 682 return dominated_blocks_; 683 } 684 685 bool IsEntryBlock() const { 686 return graph_->GetEntryBlock() == this; 687 } 688 689 bool IsExitBlock() const { 690 return graph_->GetExitBlock() == this; 691 } 692 693 bool IsSingleGoto() const; 694 bool IsSingleTryBoundary() const; 695 696 // Returns true if this block emits nothing but a jump. 697 bool IsSingleJump() const { 698 HLoopInformation* loop_info = GetLoopInformation(); 699 return (IsSingleGoto() || IsSingleTryBoundary()) 700 // Back edges generate a suspend check. 701 && (loop_info == nullptr || !loop_info->IsBackEdge(*this)); 702 } 703 704 void AddBackEdge(HBasicBlock* back_edge) { 705 if (loop_information_ == nullptr) { 706 loop_information_ = new (graph_->GetArena()) HLoopInformation(this, graph_); 707 } 708 DCHECK_EQ(loop_information_->GetHeader(), this); 709 loop_information_->AddBackEdge(back_edge); 710 } 711 712 HGraph* GetGraph() const { return graph_; } 713 void SetGraph(HGraph* graph) { graph_ = graph; } 714 715 uint32_t GetBlockId() const { return block_id_; } 716 void SetBlockId(int id) { block_id_ = id; } 717 uint32_t GetDexPc() const { return dex_pc_; } 718 719 HBasicBlock* GetDominator() const { return dominator_; } 720 void SetDominator(HBasicBlock* dominator) { dominator_ = dominator; } 721 void AddDominatedBlock(HBasicBlock* block) { dominated_blocks_.push_back(block); } 722 723 void RemoveDominatedBlock(HBasicBlock* block) { 724 RemoveElement(dominated_blocks_, block); 725 } 726 727 void ReplaceDominatedBlock(HBasicBlock* existing, HBasicBlock* new_block) { 728 ReplaceElement(dominated_blocks_, existing, new_block); 729 } 730 731 void ClearDominanceInformation(); 732 733 int NumberOfBackEdges() const { 734 return IsLoopHeader() ? loop_information_->NumberOfBackEdges() : 0; 735 } 736 737 HInstruction* GetFirstInstruction() const { return instructions_.first_instruction_; } 738 HInstruction* GetLastInstruction() const { return instructions_.last_instruction_; } 739 const HInstructionList& GetInstructions() const { return instructions_; } 740 HInstruction* GetFirstPhi() const { return phis_.first_instruction_; } 741 HInstruction* GetLastPhi() const { return phis_.last_instruction_; } 742 const HInstructionList& GetPhis() const { return phis_; } 743 744 void AddSuccessor(HBasicBlock* block) { 745 successors_.push_back(block); 746 block->predecessors_.push_back(this); 747 } 748 749 void ReplaceSuccessor(HBasicBlock* existing, HBasicBlock* new_block) { 750 size_t successor_index = GetSuccessorIndexOf(existing); 751 existing->RemovePredecessor(this); 752 new_block->predecessors_.push_back(this); 753 successors_[successor_index] = new_block; 754 } 755 756 void ReplacePredecessor(HBasicBlock* existing, HBasicBlock* new_block) { 757 size_t predecessor_index = GetPredecessorIndexOf(existing); 758 existing->RemoveSuccessor(this); 759 new_block->successors_.push_back(this); 760 predecessors_[predecessor_index] = new_block; 761 } 762 763 // Insert `this` between `predecessor` and `successor. This method 764 // preserves the indicies, and will update the first edge found between 765 // `predecessor` and `successor`. 766 void InsertBetween(HBasicBlock* predecessor, HBasicBlock* successor) { 767 size_t predecessor_index = successor->GetPredecessorIndexOf(predecessor); 768 size_t successor_index = predecessor->GetSuccessorIndexOf(successor); 769 successor->predecessors_[predecessor_index] = this; 770 predecessor->successors_[successor_index] = this; 771 successors_.push_back(successor); 772 predecessors_.push_back(predecessor); 773 } 774 775 void RemovePredecessor(HBasicBlock* block) { 776 predecessors_.erase(predecessors_.begin() + GetPredecessorIndexOf(block)); 777 } 778 779 void RemoveSuccessor(HBasicBlock* block) { 780 successors_.erase(successors_.begin() + GetSuccessorIndexOf(block)); 781 } 782 783 void ClearAllPredecessors() { 784 predecessors_.clear(); 785 } 786 787 void AddPredecessor(HBasicBlock* block) { 788 predecessors_.push_back(block); 789 block->successors_.push_back(this); 790 } 791 792 void SwapPredecessors() { 793 DCHECK_EQ(predecessors_.size(), 2u); 794 std::swap(predecessors_[0], predecessors_[1]); 795 } 796 797 void SwapSuccessors() { 798 DCHECK_EQ(successors_.size(), 2u); 799 std::swap(successors_[0], successors_[1]); 800 } 801 802 size_t GetPredecessorIndexOf(HBasicBlock* predecessor) const { 803 return IndexOfElement(predecessors_, predecessor); 804 } 805 806 size_t GetSuccessorIndexOf(HBasicBlock* successor) const { 807 return IndexOfElement(successors_, successor); 808 } 809 810 HBasicBlock* GetSinglePredecessor() const { 811 DCHECK_EQ(GetPredecessors().size(), 1u); 812 return GetPredecessors()[0]; 813 } 814 815 HBasicBlock* GetSingleSuccessor() const { 816 DCHECK_EQ(GetSuccessors().size(), 1u); 817 return GetSuccessors()[0]; 818 } 819 820 // Returns whether the first occurrence of `predecessor` in the list of 821 // predecessors is at index `idx`. 822 bool IsFirstIndexOfPredecessor(HBasicBlock* predecessor, size_t idx) const { 823 DCHECK_EQ(GetPredecessors()[idx], predecessor); 824 return GetPredecessorIndexOf(predecessor) == idx; 825 } 826 827 // Create a new block between this block and its predecessors. The new block 828 // is added to the graph, all predecessor edges are relinked to it and an edge 829 // is created to `this`. Returns the new empty block. Reverse post order or 830 // loop and try/catch information are not updated. 831 HBasicBlock* CreateImmediateDominator(); 832 833 // Split the block into two blocks just before `cursor`. Returns the newly 834 // created, latter block. Note that this method will add the block to the 835 // graph, create a Goto at the end of the former block and will create an edge 836 // between the blocks. It will not, however, update the reverse post order or 837 // loop and try/catch information. 838 HBasicBlock* SplitBefore(HInstruction* cursor); 839 840 // Split the block into two blocks just after `cursor`. Returns the newly 841 // created block. Note that this method just updates raw block information, 842 // like predecessors, successors, dominators, and instruction list. It does not 843 // update the graph, reverse post order, loop information, nor make sure the 844 // blocks are consistent (for example ending with a control flow instruction). 845 HBasicBlock* SplitAfter(HInstruction* cursor); 846 847 // Split catch block into two blocks after the original move-exception bytecode 848 // instruction, or at the beginning if not present. Returns the newly created, 849 // latter block, or nullptr if such block could not be created (must be dead 850 // in that case). Note that this method just updates raw block information, 851 // like predecessors, successors, dominators, and instruction list. It does not 852 // update the graph, reverse post order, loop information, nor make sure the 853 // blocks are consistent (for example ending with a control flow instruction). 854 HBasicBlock* SplitCatchBlockAfterMoveException(); 855 856 // Merge `other` at the end of `this`. Successors and dominated blocks of 857 // `other` are changed to be successors and dominated blocks of `this`. Note 858 // that this method does not update the graph, reverse post order, loop 859 // information, nor make sure the blocks are consistent (for example ending 860 // with a control flow instruction). 861 void MergeWithInlined(HBasicBlock* other); 862 863 // Replace `this` with `other`. Predecessors, successors, and dominated blocks 864 // of `this` are moved to `other`. 865 // Note that this method does not update the graph, reverse post order, loop 866 // information, nor make sure the blocks are consistent (for example ending 867 // with a control flow instruction). 868 void ReplaceWith(HBasicBlock* other); 869 870 // Merge `other` at the end of `this`. This method updates loops, reverse post 871 // order, links to predecessors, successors, dominators and deletes the block 872 // from the graph. The two blocks must be successive, i.e. `this` the only 873 // predecessor of `other` and vice versa. 874 void MergeWith(HBasicBlock* other); 875 876 // Disconnects `this` from all its predecessors, successors and dominator, 877 // removes it from all loops it is included in and eventually from the graph. 878 // The block must not dominate any other block. Predecessors and successors 879 // are safely updated. 880 void DisconnectAndDelete(); 881 882 void AddInstruction(HInstruction* instruction); 883 // Insert `instruction` before/after an existing instruction `cursor`. 884 void InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor); 885 void InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor); 886 // Replace instruction `initial` with `replacement` within this block. 887 void ReplaceAndRemoveInstructionWith(HInstruction* initial, 888 HInstruction* replacement); 889 void AddPhi(HPhi* phi); 890 void InsertPhiAfter(HPhi* instruction, HPhi* cursor); 891 // RemoveInstruction and RemovePhi delete a given instruction from the respective 892 // instruction list. With 'ensure_safety' set to true, it verifies that the 893 // instruction is not in use and removes it from the use lists of its inputs. 894 void RemoveInstruction(HInstruction* instruction, bool ensure_safety = true); 895 void RemovePhi(HPhi* phi, bool ensure_safety = true); 896 void RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety = true); 897 898 bool IsLoopHeader() const { 899 return IsInLoop() && (loop_information_->GetHeader() == this); 900 } 901 902 bool IsLoopPreHeaderFirstPredecessor() const { 903 DCHECK(IsLoopHeader()); 904 return GetPredecessors()[0] == GetLoopInformation()->GetPreHeader(); 905 } 906 907 HLoopInformation* GetLoopInformation() const { 908 return loop_information_; 909 } 910 911 // Set the loop_information_ on this block. Overrides the current 912 // loop_information if it is an outer loop of the passed loop information. 913 // Note that this method is called while creating the loop information. 914 void SetInLoop(HLoopInformation* info) { 915 if (IsLoopHeader()) { 916 // Nothing to do. This just means `info` is an outer loop. 917 } else if (!IsInLoop()) { 918 loop_information_ = info; 919 } else if (loop_information_->Contains(*info->GetHeader())) { 920 // Block is currently part of an outer loop. Make it part of this inner loop. 921 // Note that a non loop header having a loop information means this loop information 922 // has already been populated 923 loop_information_ = info; 924 } else { 925 // Block is part of an inner loop. Do not update the loop information. 926 // Note that we cannot do the check `info->Contains(loop_information_)->GetHeader()` 927 // at this point, because this method is being called while populating `info`. 928 } 929 } 930 931 // Raw update of the loop information. 932 void SetLoopInformation(HLoopInformation* info) { 933 loop_information_ = info; 934 } 935 936 bool IsInLoop() const { return loop_information_ != nullptr; } 937 938 TryCatchInformation* GetTryCatchInformation() const { return try_catch_information_; } 939 940 void SetTryCatchInformation(TryCatchInformation* try_catch_information) { 941 try_catch_information_ = try_catch_information; 942 } 943 944 bool IsTryBlock() const { 945 return try_catch_information_ != nullptr && try_catch_information_->IsTryBlock(); 946 } 947 948 bool IsCatchBlock() const { 949 return try_catch_information_ != nullptr && try_catch_information_->IsCatchBlock(); 950 } 951 952 // Returns the try entry that this block's successors should have. They will 953 // be in the same try, unless the block ends in a try boundary. In that case, 954 // the appropriate try entry will be returned. 955 const HTryBoundary* ComputeTryEntryOfSuccessors() const; 956 957 bool HasThrowingInstructions() const; 958 959 // Returns whether this block dominates the blocked passed as parameter. 960 bool Dominates(HBasicBlock* block) const; 961 962 size_t GetLifetimeStart() const { return lifetime_start_; } 963 size_t GetLifetimeEnd() const { return lifetime_end_; } 964 965 void SetLifetimeStart(size_t start) { lifetime_start_ = start; } 966 void SetLifetimeEnd(size_t end) { lifetime_end_ = end; } 967 968 bool EndsWithControlFlowInstruction() const; 969 bool EndsWithIf() const; 970 bool EndsWithTryBoundary() const; 971 bool HasSinglePhi() const; 972 973 private: 974 HGraph* graph_; 975 ArenaVector<HBasicBlock*> predecessors_; 976 ArenaVector<HBasicBlock*> successors_; 977 HInstructionList instructions_; 978 HInstructionList phis_; 979 HLoopInformation* loop_information_; 980 HBasicBlock* dominator_; 981 ArenaVector<HBasicBlock*> dominated_blocks_; 982 uint32_t block_id_; 983 // The dex program counter of the first instruction of this block. 984 const uint32_t dex_pc_; 985 size_t lifetime_start_; 986 size_t lifetime_end_; 987 TryCatchInformation* try_catch_information_; 988 989 friend class HGraph; 990 friend class HInstruction; 991 992 DISALLOW_COPY_AND_ASSIGN(HBasicBlock); 993}; 994 995// Iterates over the LoopInformation of all loops which contain 'block' 996// from the innermost to the outermost. 997class HLoopInformationOutwardIterator : public ValueObject { 998 public: 999 explicit HLoopInformationOutwardIterator(const HBasicBlock& block) 1000 : current_(block.GetLoopInformation()) {} 1001 1002 bool Done() const { return current_ == nullptr; } 1003 1004 void Advance() { 1005 DCHECK(!Done()); 1006 current_ = current_->GetPreHeader()->GetLoopInformation(); 1007 } 1008 1009 HLoopInformation* Current() const { 1010 DCHECK(!Done()); 1011 return current_; 1012 } 1013 1014 private: 1015 HLoopInformation* current_; 1016 1017 DISALLOW_COPY_AND_ASSIGN(HLoopInformationOutwardIterator); 1018}; 1019 1020#define FOR_EACH_CONCRETE_INSTRUCTION_COMMON(M) \ 1021 M(Above, Condition) \ 1022 M(AboveOrEqual, Condition) \ 1023 M(Add, BinaryOperation) \ 1024 M(And, BinaryOperation) \ 1025 M(ArrayGet, Instruction) \ 1026 M(ArrayLength, Instruction) \ 1027 M(ArraySet, Instruction) \ 1028 M(Below, Condition) \ 1029 M(BelowOrEqual, Condition) \ 1030 M(BooleanNot, UnaryOperation) \ 1031 M(BoundsCheck, Instruction) \ 1032 M(BoundType, Instruction) \ 1033 M(CheckCast, Instruction) \ 1034 M(ClearException, Instruction) \ 1035 M(ClinitCheck, Instruction) \ 1036 M(Compare, BinaryOperation) \ 1037 M(CurrentMethod, Instruction) \ 1038 M(Deoptimize, Instruction) \ 1039 M(Div, BinaryOperation) \ 1040 M(DivZeroCheck, Instruction) \ 1041 M(DoubleConstant, Constant) \ 1042 M(Equal, Condition) \ 1043 M(Exit, Instruction) \ 1044 M(FakeString, Instruction) \ 1045 M(FloatConstant, Constant) \ 1046 M(Goto, Instruction) \ 1047 M(GreaterThan, Condition) \ 1048 M(GreaterThanOrEqual, Condition) \ 1049 M(If, Instruction) \ 1050 M(InstanceFieldGet, Instruction) \ 1051 M(InstanceFieldSet, Instruction) \ 1052 M(InstanceOf, Instruction) \ 1053 M(IntConstant, Constant) \ 1054 M(InvokeUnresolved, Invoke) \ 1055 M(InvokeInterface, Invoke) \ 1056 M(InvokeStaticOrDirect, Invoke) \ 1057 M(InvokeVirtual, Invoke) \ 1058 M(LessThan, Condition) \ 1059 M(LessThanOrEqual, Condition) \ 1060 M(LoadClass, Instruction) \ 1061 M(LoadException, Instruction) \ 1062 M(LoadLocal, Instruction) \ 1063 M(LoadString, Instruction) \ 1064 M(Local, Instruction) \ 1065 M(LongConstant, Constant) \ 1066 M(MemoryBarrier, Instruction) \ 1067 M(MonitorOperation, Instruction) \ 1068 M(Mul, BinaryOperation) \ 1069 M(NativeDebugInfo, Instruction) \ 1070 M(Neg, UnaryOperation) \ 1071 M(NewArray, Instruction) \ 1072 M(NewInstance, Instruction) \ 1073 M(Not, UnaryOperation) \ 1074 M(NotEqual, Condition) \ 1075 M(NullConstant, Instruction) \ 1076 M(NullCheck, Instruction) \ 1077 M(Or, BinaryOperation) \ 1078 M(PackedSwitch, Instruction) \ 1079 M(ParallelMove, Instruction) \ 1080 M(ParameterValue, Instruction) \ 1081 M(Phi, Instruction) \ 1082 M(Rem, BinaryOperation) \ 1083 M(Return, Instruction) \ 1084 M(ReturnVoid, Instruction) \ 1085 M(Ror, BinaryOperation) \ 1086 M(Shl, BinaryOperation) \ 1087 M(Shr, BinaryOperation) \ 1088 M(StaticFieldGet, Instruction) \ 1089 M(StaticFieldSet, Instruction) \ 1090 M(UnresolvedInstanceFieldGet, Instruction) \ 1091 M(UnresolvedInstanceFieldSet, Instruction) \ 1092 M(UnresolvedStaticFieldGet, Instruction) \ 1093 M(UnresolvedStaticFieldSet, Instruction) \ 1094 M(StoreLocal, Instruction) \ 1095 M(Sub, BinaryOperation) \ 1096 M(SuspendCheck, Instruction) \ 1097 M(Temporary, Instruction) \ 1098 M(Throw, Instruction) \ 1099 M(TryBoundary, Instruction) \ 1100 M(TypeConversion, Instruction) \ 1101 M(UShr, BinaryOperation) \ 1102 M(Xor, BinaryOperation) \ 1103 1104#ifndef ART_ENABLE_CODEGEN_arm 1105#define FOR_EACH_CONCRETE_INSTRUCTION_ARM(M) 1106#else 1107#define FOR_EACH_CONCRETE_INSTRUCTION_ARM(M) \ 1108 M(ArmDexCacheArraysBase, Instruction) 1109#endif 1110 1111#ifndef ART_ENABLE_CODEGEN_arm64 1112#define FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M) 1113#else 1114#define FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M) \ 1115 M(Arm64DataProcWithShifterOp, Instruction) \ 1116 M(Arm64IntermediateAddress, Instruction) \ 1117 M(Arm64MultiplyAccumulate, Instruction) 1118#endif 1119 1120#define FOR_EACH_CONCRETE_INSTRUCTION_MIPS(M) 1121 1122#define FOR_EACH_CONCRETE_INSTRUCTION_MIPS64(M) 1123 1124#ifndef ART_ENABLE_CODEGEN_x86 1125#define FOR_EACH_CONCRETE_INSTRUCTION_X86(M) 1126#else 1127#define FOR_EACH_CONCRETE_INSTRUCTION_X86(M) \ 1128 M(X86ComputeBaseMethodAddress, Instruction) \ 1129 M(X86LoadFromConstantTable, Instruction) \ 1130 M(X86PackedSwitch, Instruction) 1131#endif 1132 1133#define FOR_EACH_CONCRETE_INSTRUCTION_X86_64(M) 1134 1135#define FOR_EACH_CONCRETE_INSTRUCTION(M) \ 1136 FOR_EACH_CONCRETE_INSTRUCTION_COMMON(M) \ 1137 FOR_EACH_CONCRETE_INSTRUCTION_ARM(M) \ 1138 FOR_EACH_CONCRETE_INSTRUCTION_ARM64(M) \ 1139 FOR_EACH_CONCRETE_INSTRUCTION_MIPS(M) \ 1140 FOR_EACH_CONCRETE_INSTRUCTION_MIPS64(M) \ 1141 FOR_EACH_CONCRETE_INSTRUCTION_X86(M) \ 1142 FOR_EACH_CONCRETE_INSTRUCTION_X86_64(M) 1143 1144#define FOR_EACH_ABSTRACT_INSTRUCTION(M) \ 1145 M(Condition, BinaryOperation) \ 1146 M(Constant, Instruction) \ 1147 M(UnaryOperation, Instruction) \ 1148 M(BinaryOperation, Instruction) \ 1149 M(Invoke, Instruction) 1150 1151#define FOR_EACH_INSTRUCTION(M) \ 1152 FOR_EACH_CONCRETE_INSTRUCTION(M) \ 1153 FOR_EACH_ABSTRACT_INSTRUCTION(M) 1154 1155#define FORWARD_DECLARATION(type, super) class H##type; 1156FOR_EACH_INSTRUCTION(FORWARD_DECLARATION) 1157#undef FORWARD_DECLARATION 1158 1159#define DECLARE_INSTRUCTION(type) \ 1160 InstructionKind GetKindInternal() const OVERRIDE { return k##type; } \ 1161 const char* DebugName() const OVERRIDE { return #type; } \ 1162 bool InstructionTypeEquals(HInstruction* other) const OVERRIDE { \ 1163 return other->Is##type(); \ 1164 } \ 1165 void Accept(HGraphVisitor* visitor) OVERRIDE 1166 1167#define DECLARE_ABSTRACT_INSTRUCTION(type) \ 1168 bool Is##type() const { return As##type() != nullptr; } \ 1169 const H##type* As##type() const { return this; } \ 1170 H##type* As##type() { return this; } 1171 1172template <typename T> class HUseList; 1173 1174template <typename T> 1175class HUseListNode : public ArenaObject<kArenaAllocUseListNode> { 1176 public: 1177 HUseListNode* GetPrevious() const { return prev_; } 1178 HUseListNode* GetNext() const { return next_; } 1179 T GetUser() const { return user_; } 1180 size_t GetIndex() const { return index_; } 1181 void SetIndex(size_t index) { index_ = index; } 1182 1183 private: 1184 HUseListNode(T user, size_t index) 1185 : user_(user), index_(index), prev_(nullptr), next_(nullptr) {} 1186 1187 T const user_; 1188 size_t index_; 1189 HUseListNode<T>* prev_; 1190 HUseListNode<T>* next_; 1191 1192 friend class HUseList<T>; 1193 1194 DISALLOW_COPY_AND_ASSIGN(HUseListNode); 1195}; 1196 1197template <typename T> 1198class HUseList : public ValueObject { 1199 public: 1200 HUseList() : first_(nullptr) {} 1201 1202 void Clear() { 1203 first_ = nullptr; 1204 } 1205 1206 // Adds a new entry at the beginning of the use list and returns 1207 // the newly created node. 1208 HUseListNode<T>* AddUse(T user, size_t index, ArenaAllocator* arena) { 1209 HUseListNode<T>* new_node = new (arena) HUseListNode<T>(user, index); 1210 if (IsEmpty()) { 1211 first_ = new_node; 1212 } else { 1213 first_->prev_ = new_node; 1214 new_node->next_ = first_; 1215 first_ = new_node; 1216 } 1217 return new_node; 1218 } 1219 1220 HUseListNode<T>* GetFirst() const { 1221 return first_; 1222 } 1223 1224 void Remove(HUseListNode<T>* node) { 1225 DCHECK(node != nullptr); 1226 DCHECK(Contains(node)); 1227 1228 if (node->prev_ != nullptr) { 1229 node->prev_->next_ = node->next_; 1230 } 1231 if (node->next_ != nullptr) { 1232 node->next_->prev_ = node->prev_; 1233 } 1234 if (node == first_) { 1235 first_ = node->next_; 1236 } 1237 } 1238 1239 bool Contains(const HUseListNode<T>* node) const { 1240 if (node == nullptr) { 1241 return false; 1242 } 1243 for (HUseListNode<T>* current = first_; current != nullptr; current = current->GetNext()) { 1244 if (current == node) { 1245 return true; 1246 } 1247 } 1248 return false; 1249 } 1250 1251 bool IsEmpty() const { 1252 return first_ == nullptr; 1253 } 1254 1255 bool HasOnlyOneUse() const { 1256 return first_ != nullptr && first_->next_ == nullptr; 1257 } 1258 1259 size_t SizeSlow() const { 1260 size_t count = 0; 1261 for (HUseListNode<T>* current = first_; current != nullptr; current = current->GetNext()) { 1262 ++count; 1263 } 1264 return count; 1265 } 1266 1267 private: 1268 HUseListNode<T>* first_; 1269}; 1270 1271template<typename T> 1272class HUseIterator : public ValueObject { 1273 public: 1274 explicit HUseIterator(const HUseList<T>& uses) : current_(uses.GetFirst()) {} 1275 1276 bool Done() const { return current_ == nullptr; } 1277 1278 void Advance() { 1279 DCHECK(!Done()); 1280 current_ = current_->GetNext(); 1281 } 1282 1283 HUseListNode<T>* Current() const { 1284 DCHECK(!Done()); 1285 return current_; 1286 } 1287 1288 private: 1289 HUseListNode<T>* current_; 1290 1291 friend class HValue; 1292}; 1293 1294// This class is used by HEnvironment and HInstruction classes to record the 1295// instructions they use and pointers to the corresponding HUseListNodes kept 1296// by the used instructions. 1297template <typename T> 1298class HUserRecord : public ValueObject { 1299 public: 1300 HUserRecord() : instruction_(nullptr), use_node_(nullptr) {} 1301 explicit HUserRecord(HInstruction* instruction) : instruction_(instruction), use_node_(nullptr) {} 1302 1303 HUserRecord(const HUserRecord<T>& old_record, HUseListNode<T>* use_node) 1304 : instruction_(old_record.instruction_), use_node_(use_node) { 1305 DCHECK(instruction_ != nullptr); 1306 DCHECK(use_node_ != nullptr); 1307 DCHECK(old_record.use_node_ == nullptr); 1308 } 1309 1310 HInstruction* GetInstruction() const { return instruction_; } 1311 HUseListNode<T>* GetUseNode() const { return use_node_; } 1312 1313 private: 1314 // Instruction used by the user. 1315 HInstruction* instruction_; 1316 1317 // Corresponding entry in the use list kept by 'instruction_'. 1318 HUseListNode<T>* use_node_; 1319}; 1320 1321/** 1322 * Side-effects representation. 1323 * 1324 * For write/read dependences on fields/arrays, the dependence analysis uses 1325 * type disambiguation (e.g. a float field write cannot modify the value of an 1326 * integer field read) and the access type (e.g. a reference array write cannot 1327 * modify the value of a reference field read [although it may modify the 1328 * reference fetch prior to reading the field, which is represented by its own 1329 * write/read dependence]). The analysis makes conservative points-to 1330 * assumptions on reference types (e.g. two same typed arrays are assumed to be 1331 * the same, and any reference read depends on any reference read without 1332 * further regard of its type). 1333 * 1334 * The internal representation uses 38-bit and is described in the table below. 1335 * The first line indicates the side effect, and for field/array accesses the 1336 * second line indicates the type of the access (in the order of the 1337 * Primitive::Type enum). 1338 * The two numbered lines below indicate the bit position in the bitfield (read 1339 * vertically). 1340 * 1341 * |Depends on GC|ARRAY-R |FIELD-R |Can trigger GC|ARRAY-W |FIELD-W | 1342 * +-------------+---------+---------+--------------+---------+---------+ 1343 * | |DFJISCBZL|DFJISCBZL| |DFJISCBZL|DFJISCBZL| 1344 * | 3 |333333322|222222221| 1 |111111110|000000000| 1345 * | 7 |654321098|765432109| 8 |765432109|876543210| 1346 * 1347 * Note that, to ease the implementation, 'changes' bits are least significant 1348 * bits, while 'dependency' bits are most significant bits. 1349 */ 1350class SideEffects : public ValueObject { 1351 public: 1352 SideEffects() : flags_(0) {} 1353 1354 static SideEffects None() { 1355 return SideEffects(0); 1356 } 1357 1358 static SideEffects All() { 1359 return SideEffects(kAllChangeBits | kAllDependOnBits); 1360 } 1361 1362 static SideEffects AllChanges() { 1363 return SideEffects(kAllChangeBits); 1364 } 1365 1366 static SideEffects AllDependencies() { 1367 return SideEffects(kAllDependOnBits); 1368 } 1369 1370 static SideEffects AllExceptGCDependency() { 1371 return AllWritesAndReads().Union(SideEffects::CanTriggerGC()); 1372 } 1373 1374 static SideEffects AllWritesAndReads() { 1375 return SideEffects(kAllWrites | kAllReads); 1376 } 1377 1378 static SideEffects AllWrites() { 1379 return SideEffects(kAllWrites); 1380 } 1381 1382 static SideEffects AllReads() { 1383 return SideEffects(kAllReads); 1384 } 1385 1386 static SideEffects FieldWriteOfType(Primitive::Type type, bool is_volatile) { 1387 return is_volatile 1388 ? AllWritesAndReads() 1389 : SideEffects(TypeFlagWithAlias(type, kFieldWriteOffset)); 1390 } 1391 1392 static SideEffects ArrayWriteOfType(Primitive::Type type) { 1393 return SideEffects(TypeFlagWithAlias(type, kArrayWriteOffset)); 1394 } 1395 1396 static SideEffects FieldReadOfType(Primitive::Type type, bool is_volatile) { 1397 return is_volatile 1398 ? AllWritesAndReads() 1399 : SideEffects(TypeFlagWithAlias(type, kFieldReadOffset)); 1400 } 1401 1402 static SideEffects ArrayReadOfType(Primitive::Type type) { 1403 return SideEffects(TypeFlagWithAlias(type, kArrayReadOffset)); 1404 } 1405 1406 static SideEffects CanTriggerGC() { 1407 return SideEffects(1ULL << kCanTriggerGCBit); 1408 } 1409 1410 static SideEffects DependsOnGC() { 1411 return SideEffects(1ULL << kDependsOnGCBit); 1412 } 1413 1414 // Combines the side-effects of this and the other. 1415 SideEffects Union(SideEffects other) const { 1416 return SideEffects(flags_ | other.flags_); 1417 } 1418 1419 SideEffects Exclusion(SideEffects other) const { 1420 return SideEffects(flags_ & ~other.flags_); 1421 } 1422 1423 void Add(SideEffects other) { 1424 flags_ |= other.flags_; 1425 } 1426 1427 bool Includes(SideEffects other) const { 1428 return (other.flags_ & flags_) == other.flags_; 1429 } 1430 1431 bool HasSideEffects() const { 1432 return (flags_ & kAllChangeBits); 1433 } 1434 1435 bool HasDependencies() const { 1436 return (flags_ & kAllDependOnBits); 1437 } 1438 1439 // Returns true if there are no side effects or dependencies. 1440 bool DoesNothing() const { 1441 return flags_ == 0; 1442 } 1443 1444 // Returns true if something is written. 1445 bool DoesAnyWrite() const { 1446 return (flags_ & kAllWrites); 1447 } 1448 1449 // Returns true if something is read. 1450 bool DoesAnyRead() const { 1451 return (flags_ & kAllReads); 1452 } 1453 1454 // Returns true if potentially everything is written and read 1455 // (every type and every kind of access). 1456 bool DoesAllReadWrite() const { 1457 return (flags_ & (kAllWrites | kAllReads)) == (kAllWrites | kAllReads); 1458 } 1459 1460 bool DoesAll() const { 1461 return flags_ == (kAllChangeBits | kAllDependOnBits); 1462 } 1463 1464 // Returns true if `this` may read something written by `other`. 1465 bool MayDependOn(SideEffects other) const { 1466 const uint64_t depends_on_flags = (flags_ & kAllDependOnBits) >> kChangeBits; 1467 return (other.flags_ & depends_on_flags); 1468 } 1469 1470 // Returns string representation of flags (for debugging only). 1471 // Format: |x|DFJISCBZL|DFJISCBZL|y|DFJISCBZL|DFJISCBZL| 1472 std::string ToString() const { 1473 std::string flags = "|"; 1474 for (int s = kLastBit; s >= 0; s--) { 1475 bool current_bit_is_set = ((flags_ >> s) & 1) != 0; 1476 if ((s == kDependsOnGCBit) || (s == kCanTriggerGCBit)) { 1477 // This is a bit for the GC side effect. 1478 if (current_bit_is_set) { 1479 flags += "GC"; 1480 } 1481 flags += "|"; 1482 } else { 1483 // This is a bit for the array/field analysis. 1484 // The underscore character stands for the 'can trigger GC' bit. 1485 static const char *kDebug = "LZBCSIJFDLZBCSIJFD_LZBCSIJFDLZBCSIJFD"; 1486 if (current_bit_is_set) { 1487 flags += kDebug[s]; 1488 } 1489 if ((s == kFieldWriteOffset) || (s == kArrayWriteOffset) || 1490 (s == kFieldReadOffset) || (s == kArrayReadOffset)) { 1491 flags += "|"; 1492 } 1493 } 1494 } 1495 return flags; 1496 } 1497 1498 bool Equals(const SideEffects& other) const { return flags_ == other.flags_; } 1499 1500 private: 1501 static constexpr int kFieldArrayAnalysisBits = 9; 1502 1503 static constexpr int kFieldWriteOffset = 0; 1504 static constexpr int kArrayWriteOffset = kFieldWriteOffset + kFieldArrayAnalysisBits; 1505 static constexpr int kLastBitForWrites = kArrayWriteOffset + kFieldArrayAnalysisBits - 1; 1506 static constexpr int kCanTriggerGCBit = kLastBitForWrites + 1; 1507 1508 static constexpr int kChangeBits = kCanTriggerGCBit + 1; 1509 1510 static constexpr int kFieldReadOffset = kCanTriggerGCBit + 1; 1511 static constexpr int kArrayReadOffset = kFieldReadOffset + kFieldArrayAnalysisBits; 1512 static constexpr int kLastBitForReads = kArrayReadOffset + kFieldArrayAnalysisBits - 1; 1513 static constexpr int kDependsOnGCBit = kLastBitForReads + 1; 1514 1515 static constexpr int kLastBit = kDependsOnGCBit; 1516 static constexpr int kDependOnBits = kLastBit + 1 - kChangeBits; 1517 1518 // Aliases. 1519 1520 static_assert(kChangeBits == kDependOnBits, 1521 "the 'change' bits should match the 'depend on' bits."); 1522 1523 static constexpr uint64_t kAllChangeBits = ((1ULL << kChangeBits) - 1); 1524 static constexpr uint64_t kAllDependOnBits = ((1ULL << kDependOnBits) - 1) << kChangeBits; 1525 static constexpr uint64_t kAllWrites = 1526 ((1ULL << (kLastBitForWrites + 1 - kFieldWriteOffset)) - 1) << kFieldWriteOffset; 1527 static constexpr uint64_t kAllReads = 1528 ((1ULL << (kLastBitForReads + 1 - kFieldReadOffset)) - 1) << kFieldReadOffset; 1529 1530 // Work around the fact that HIR aliases I/F and J/D. 1531 // TODO: remove this interceptor once HIR types are clean 1532 static uint64_t TypeFlagWithAlias(Primitive::Type type, int offset) { 1533 switch (type) { 1534 case Primitive::kPrimInt: 1535 case Primitive::kPrimFloat: 1536 return TypeFlag(Primitive::kPrimInt, offset) | 1537 TypeFlag(Primitive::kPrimFloat, offset); 1538 case Primitive::kPrimLong: 1539 case Primitive::kPrimDouble: 1540 return TypeFlag(Primitive::kPrimLong, offset) | 1541 TypeFlag(Primitive::kPrimDouble, offset); 1542 default: 1543 return TypeFlag(type, offset); 1544 } 1545 } 1546 1547 // Translates type to bit flag. 1548 static uint64_t TypeFlag(Primitive::Type type, int offset) { 1549 CHECK_NE(type, Primitive::kPrimVoid); 1550 const uint64_t one = 1; 1551 const int shift = type; // 0-based consecutive enum 1552 DCHECK_LE(kFieldWriteOffset, shift); 1553 DCHECK_LT(shift, kArrayWriteOffset); 1554 return one << (type + offset); 1555 } 1556 1557 // Private constructor on direct flags value. 1558 explicit SideEffects(uint64_t flags) : flags_(flags) {} 1559 1560 uint64_t flags_; 1561}; 1562 1563// A HEnvironment object contains the values of virtual registers at a given location. 1564class HEnvironment : public ArenaObject<kArenaAllocEnvironment> { 1565 public: 1566 HEnvironment(ArenaAllocator* arena, 1567 size_t number_of_vregs, 1568 const DexFile& dex_file, 1569 uint32_t method_idx, 1570 uint32_t dex_pc, 1571 InvokeType invoke_type, 1572 HInstruction* holder) 1573 : vregs_(number_of_vregs, arena->Adapter(kArenaAllocEnvironmentVRegs)), 1574 locations_(number_of_vregs, arena->Adapter(kArenaAllocEnvironmentLocations)), 1575 parent_(nullptr), 1576 dex_file_(dex_file), 1577 method_idx_(method_idx), 1578 dex_pc_(dex_pc), 1579 invoke_type_(invoke_type), 1580 holder_(holder) { 1581 } 1582 1583 HEnvironment(ArenaAllocator* arena, const HEnvironment& to_copy, HInstruction* holder) 1584 : HEnvironment(arena, 1585 to_copy.Size(), 1586 to_copy.GetDexFile(), 1587 to_copy.GetMethodIdx(), 1588 to_copy.GetDexPc(), 1589 to_copy.GetInvokeType(), 1590 holder) {} 1591 1592 void SetAndCopyParentChain(ArenaAllocator* allocator, HEnvironment* parent) { 1593 if (parent_ != nullptr) { 1594 parent_->SetAndCopyParentChain(allocator, parent); 1595 } else { 1596 parent_ = new (allocator) HEnvironment(allocator, *parent, holder_); 1597 parent_->CopyFrom(parent); 1598 if (parent->GetParent() != nullptr) { 1599 parent_->SetAndCopyParentChain(allocator, parent->GetParent()); 1600 } 1601 } 1602 } 1603 1604 void CopyFrom(const ArenaVector<HInstruction*>& locals); 1605 void CopyFrom(HEnvironment* environment); 1606 1607 // Copy from `env`. If it's a loop phi for `loop_header`, copy the first 1608 // input to the loop phi instead. This is for inserting instructions that 1609 // require an environment (like HDeoptimization) in the loop pre-header. 1610 void CopyFromWithLoopPhiAdjustment(HEnvironment* env, HBasicBlock* loop_header); 1611 1612 void SetRawEnvAt(size_t index, HInstruction* instruction) { 1613 vregs_[index] = HUserRecord<HEnvironment*>(instruction); 1614 } 1615 1616 HInstruction* GetInstructionAt(size_t index) const { 1617 return vregs_[index].GetInstruction(); 1618 } 1619 1620 void RemoveAsUserOfInput(size_t index) const; 1621 1622 size_t Size() const { return vregs_.size(); } 1623 1624 HEnvironment* GetParent() const { return parent_; } 1625 1626 void SetLocationAt(size_t index, Location location) { 1627 locations_[index] = location; 1628 } 1629 1630 Location GetLocationAt(size_t index) const { 1631 return locations_[index]; 1632 } 1633 1634 uint32_t GetDexPc() const { 1635 return dex_pc_; 1636 } 1637 1638 uint32_t GetMethodIdx() const { 1639 return method_idx_; 1640 } 1641 1642 InvokeType GetInvokeType() const { 1643 return invoke_type_; 1644 } 1645 1646 const DexFile& GetDexFile() const { 1647 return dex_file_; 1648 } 1649 1650 HInstruction* GetHolder() const { 1651 return holder_; 1652 } 1653 1654 1655 bool IsFromInlinedInvoke() const { 1656 return GetParent() != nullptr; 1657 } 1658 1659 private: 1660 // Record instructions' use entries of this environment for constant-time removal. 1661 // It should only be called by HInstruction when a new environment use is added. 1662 void RecordEnvUse(HUseListNode<HEnvironment*>* env_use) { 1663 DCHECK(env_use->GetUser() == this); 1664 size_t index = env_use->GetIndex(); 1665 vregs_[index] = HUserRecord<HEnvironment*>(vregs_[index], env_use); 1666 } 1667 1668 ArenaVector<HUserRecord<HEnvironment*>> vregs_; 1669 ArenaVector<Location> locations_; 1670 HEnvironment* parent_; 1671 const DexFile& dex_file_; 1672 const uint32_t method_idx_; 1673 const uint32_t dex_pc_; 1674 const InvokeType invoke_type_; 1675 1676 // The instruction that holds this environment. 1677 HInstruction* const holder_; 1678 1679 friend class HInstruction; 1680 1681 DISALLOW_COPY_AND_ASSIGN(HEnvironment); 1682}; 1683 1684class ReferenceTypeInfo : ValueObject { 1685 public: 1686 typedef Handle<mirror::Class> TypeHandle; 1687 1688 static ReferenceTypeInfo Create(TypeHandle type_handle, bool is_exact) { 1689 // The constructor will check that the type_handle is valid. 1690 return ReferenceTypeInfo(type_handle, is_exact); 1691 } 1692 1693 static ReferenceTypeInfo CreateInvalid() { return ReferenceTypeInfo(); } 1694 1695 static bool IsValidHandle(TypeHandle handle) SHARED_REQUIRES(Locks::mutator_lock_) { 1696 return handle.GetReference() != nullptr; 1697 } 1698 1699 bool IsValid() const SHARED_REQUIRES(Locks::mutator_lock_) { 1700 return IsValidHandle(type_handle_); 1701 } 1702 1703 bool IsExact() const { return is_exact_; } 1704 1705 bool IsObjectClass() const SHARED_REQUIRES(Locks::mutator_lock_) { 1706 DCHECK(IsValid()); 1707 return GetTypeHandle()->IsObjectClass(); 1708 } 1709 1710 bool IsStringClass() const SHARED_REQUIRES(Locks::mutator_lock_) { 1711 DCHECK(IsValid()); 1712 return GetTypeHandle()->IsStringClass(); 1713 } 1714 1715 bool IsObjectArray() const SHARED_REQUIRES(Locks::mutator_lock_) { 1716 DCHECK(IsValid()); 1717 return IsArrayClass() && GetTypeHandle()->GetComponentType()->IsObjectClass(); 1718 } 1719 1720 bool IsInterface() const SHARED_REQUIRES(Locks::mutator_lock_) { 1721 DCHECK(IsValid()); 1722 return GetTypeHandle()->IsInterface(); 1723 } 1724 1725 bool IsArrayClass() const SHARED_REQUIRES(Locks::mutator_lock_) { 1726 DCHECK(IsValid()); 1727 return GetTypeHandle()->IsArrayClass(); 1728 } 1729 1730 bool IsPrimitiveArrayClass() const SHARED_REQUIRES(Locks::mutator_lock_) { 1731 DCHECK(IsValid()); 1732 return GetTypeHandle()->IsPrimitiveArray(); 1733 } 1734 1735 bool IsNonPrimitiveArrayClass() const SHARED_REQUIRES(Locks::mutator_lock_) { 1736 DCHECK(IsValid()); 1737 return GetTypeHandle()->IsArrayClass() && !GetTypeHandle()->IsPrimitiveArray(); 1738 } 1739 1740 bool CanArrayHold(ReferenceTypeInfo rti) const SHARED_REQUIRES(Locks::mutator_lock_) { 1741 DCHECK(IsValid()); 1742 if (!IsExact()) return false; 1743 if (!IsArrayClass()) return false; 1744 return GetTypeHandle()->GetComponentType()->IsAssignableFrom(rti.GetTypeHandle().Get()); 1745 } 1746 1747 bool CanArrayHoldValuesOf(ReferenceTypeInfo rti) const SHARED_REQUIRES(Locks::mutator_lock_) { 1748 DCHECK(IsValid()); 1749 if (!IsExact()) return false; 1750 if (!IsArrayClass()) return false; 1751 if (!rti.IsArrayClass()) return false; 1752 return GetTypeHandle()->GetComponentType()->IsAssignableFrom( 1753 rti.GetTypeHandle()->GetComponentType()); 1754 } 1755 1756 Handle<mirror::Class> GetTypeHandle() const { return type_handle_; } 1757 1758 bool IsSupertypeOf(ReferenceTypeInfo rti) const SHARED_REQUIRES(Locks::mutator_lock_) { 1759 DCHECK(IsValid()); 1760 DCHECK(rti.IsValid()); 1761 return GetTypeHandle()->IsAssignableFrom(rti.GetTypeHandle().Get()); 1762 } 1763 1764 bool IsStrictSupertypeOf(ReferenceTypeInfo rti) const SHARED_REQUIRES(Locks::mutator_lock_) { 1765 DCHECK(IsValid()); 1766 DCHECK(rti.IsValid()); 1767 return GetTypeHandle().Get() != rti.GetTypeHandle().Get() && 1768 GetTypeHandle()->IsAssignableFrom(rti.GetTypeHandle().Get()); 1769 } 1770 1771 // Returns true if the type information provide the same amount of details. 1772 // Note that it does not mean that the instructions have the same actual type 1773 // (because the type can be the result of a merge). 1774 bool IsEqual(ReferenceTypeInfo rti) SHARED_REQUIRES(Locks::mutator_lock_) { 1775 if (!IsValid() && !rti.IsValid()) { 1776 // Invalid types are equal. 1777 return true; 1778 } 1779 if (!IsValid() || !rti.IsValid()) { 1780 // One is valid, the other not. 1781 return false; 1782 } 1783 return IsExact() == rti.IsExact() 1784 && GetTypeHandle().Get() == rti.GetTypeHandle().Get(); 1785 } 1786 1787 private: 1788 ReferenceTypeInfo(); 1789 ReferenceTypeInfo(TypeHandle type_handle, bool is_exact); 1790 1791 // The class of the object. 1792 TypeHandle type_handle_; 1793 // Whether or not the type is exact or a superclass of the actual type. 1794 // Whether or not we have any information about this type. 1795 bool is_exact_; 1796}; 1797 1798std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs); 1799 1800class HInstruction : public ArenaObject<kArenaAllocInstruction> { 1801 public: 1802 HInstruction(SideEffects side_effects, uint32_t dex_pc) 1803 : previous_(nullptr), 1804 next_(nullptr), 1805 block_(nullptr), 1806 dex_pc_(dex_pc), 1807 id_(-1), 1808 ssa_index_(-1), 1809 environment_(nullptr), 1810 locations_(nullptr), 1811 live_interval_(nullptr), 1812 lifetime_position_(kNoLifetime), 1813 side_effects_(side_effects), 1814 reference_type_info_(ReferenceTypeInfo::CreateInvalid()) {} 1815 1816 virtual ~HInstruction() {} 1817 1818#define DECLARE_KIND(type, super) k##type, 1819 enum InstructionKind { 1820 FOR_EACH_INSTRUCTION(DECLARE_KIND) 1821 }; 1822#undef DECLARE_KIND 1823 1824 HInstruction* GetNext() const { return next_; } 1825 HInstruction* GetPrevious() const { return previous_; } 1826 1827 HInstruction* GetNextDisregardingMoves() const; 1828 HInstruction* GetPreviousDisregardingMoves() const; 1829 1830 HBasicBlock* GetBlock() const { return block_; } 1831 ArenaAllocator* GetArena() const { return block_->GetGraph()->GetArena(); } 1832 void SetBlock(HBasicBlock* block) { block_ = block; } 1833 bool IsInBlock() const { return block_ != nullptr; } 1834 bool IsInLoop() const { return block_->IsInLoop(); } 1835 bool IsLoopHeaderPhi() { return IsPhi() && block_->IsLoopHeader(); } 1836 1837 virtual size_t InputCount() const = 0; 1838 HInstruction* InputAt(size_t i) const { return InputRecordAt(i).GetInstruction(); } 1839 1840 virtual void Accept(HGraphVisitor* visitor) = 0; 1841 virtual const char* DebugName() const = 0; 1842 1843 virtual Primitive::Type GetType() const { return Primitive::kPrimVoid; } 1844 void SetRawInputAt(size_t index, HInstruction* input) { 1845 SetRawInputRecordAt(index, HUserRecord<HInstruction*>(input)); 1846 } 1847 1848 virtual bool NeedsEnvironment() const { return false; } 1849 1850 uint32_t GetDexPc() const { return dex_pc_; } 1851 1852 virtual bool IsControlFlow() const { return false; } 1853 1854 virtual bool CanThrow() const { return false; } 1855 bool CanThrowIntoCatchBlock() const { return CanThrow() && block_->IsTryBlock(); } 1856 1857 bool HasSideEffects() const { return side_effects_.HasSideEffects(); } 1858 bool DoesAnyWrite() const { return side_effects_.DoesAnyWrite(); } 1859 1860 // Does not apply for all instructions, but having this at top level greatly 1861 // simplifies the null check elimination. 1862 // TODO: Consider merging can_be_null into ReferenceTypeInfo. 1863 virtual bool CanBeNull() const { 1864 DCHECK_EQ(GetType(), Primitive::kPrimNot) << "CanBeNull only applies to reference types"; 1865 return true; 1866 } 1867 1868 virtual bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const { 1869 return false; 1870 } 1871 1872 void SetReferenceTypeInfo(ReferenceTypeInfo rti); 1873 1874 ReferenceTypeInfo GetReferenceTypeInfo() const { 1875 DCHECK_EQ(GetType(), Primitive::kPrimNot); 1876 return reference_type_info_; 1877 } 1878 1879 void AddUseAt(HInstruction* user, size_t index) { 1880 DCHECK(user != nullptr); 1881 HUseListNode<HInstruction*>* use = 1882 uses_.AddUse(user, index, GetBlock()->GetGraph()->GetArena()); 1883 user->SetRawInputRecordAt(index, HUserRecord<HInstruction*>(user->InputRecordAt(index), use)); 1884 } 1885 1886 void AddEnvUseAt(HEnvironment* user, size_t index) { 1887 DCHECK(user != nullptr); 1888 HUseListNode<HEnvironment*>* env_use = 1889 env_uses_.AddUse(user, index, GetBlock()->GetGraph()->GetArena()); 1890 user->RecordEnvUse(env_use); 1891 } 1892 1893 void RemoveAsUserOfInput(size_t input) { 1894 HUserRecord<HInstruction*> input_use = InputRecordAt(input); 1895 input_use.GetInstruction()->uses_.Remove(input_use.GetUseNode()); 1896 } 1897 1898 const HUseList<HInstruction*>& GetUses() const { return uses_; } 1899 const HUseList<HEnvironment*>& GetEnvUses() const { return env_uses_; } 1900 1901 bool HasUses() const { return !uses_.IsEmpty() || !env_uses_.IsEmpty(); } 1902 bool HasEnvironmentUses() const { return !env_uses_.IsEmpty(); } 1903 bool HasNonEnvironmentUses() const { return !uses_.IsEmpty(); } 1904 bool HasOnlyOneNonEnvironmentUse() const { 1905 return !HasEnvironmentUses() && GetUses().HasOnlyOneUse(); 1906 } 1907 1908 // Does this instruction strictly dominate `other_instruction`? 1909 // Returns false if this instruction and `other_instruction` are the same. 1910 // Aborts if this instruction and `other_instruction` are both phis. 1911 bool StrictlyDominates(HInstruction* other_instruction) const; 1912 1913 int GetId() const { return id_; } 1914 void SetId(int id) { id_ = id; } 1915 1916 int GetSsaIndex() const { return ssa_index_; } 1917 void SetSsaIndex(int ssa_index) { ssa_index_ = ssa_index; } 1918 bool HasSsaIndex() const { return ssa_index_ != -1; } 1919 1920 bool HasEnvironment() const { return environment_ != nullptr; } 1921 HEnvironment* GetEnvironment() const { return environment_; } 1922 // Set the `environment_` field. Raw because this method does not 1923 // update the uses lists. 1924 void SetRawEnvironment(HEnvironment* environment) { 1925 DCHECK(environment_ == nullptr); 1926 DCHECK_EQ(environment->GetHolder(), this); 1927 environment_ = environment; 1928 } 1929 1930 // Set the environment of this instruction, copying it from `environment`. While 1931 // copying, the uses lists are being updated. 1932 void CopyEnvironmentFrom(HEnvironment* environment) { 1933 DCHECK(environment_ == nullptr); 1934 ArenaAllocator* allocator = GetBlock()->GetGraph()->GetArena(); 1935 environment_ = new (allocator) HEnvironment(allocator, *environment, this); 1936 environment_->CopyFrom(environment); 1937 if (environment->GetParent() != nullptr) { 1938 environment_->SetAndCopyParentChain(allocator, environment->GetParent()); 1939 } 1940 } 1941 1942 void CopyEnvironmentFromWithLoopPhiAdjustment(HEnvironment* environment, 1943 HBasicBlock* block) { 1944 DCHECK(environment_ == nullptr); 1945 ArenaAllocator* allocator = GetBlock()->GetGraph()->GetArena(); 1946 environment_ = new (allocator) HEnvironment(allocator, *environment, this); 1947 environment_->CopyFromWithLoopPhiAdjustment(environment, block); 1948 if (environment->GetParent() != nullptr) { 1949 environment_->SetAndCopyParentChain(allocator, environment->GetParent()); 1950 } 1951 } 1952 1953 // Returns the number of entries in the environment. Typically, that is the 1954 // number of dex registers in a method. It could be more in case of inlining. 1955 size_t EnvironmentSize() const; 1956 1957 LocationSummary* GetLocations() const { return locations_; } 1958 void SetLocations(LocationSummary* locations) { locations_ = locations; } 1959 1960 void ReplaceWith(HInstruction* instruction); 1961 void ReplaceInput(HInstruction* replacement, size_t index); 1962 1963 // This is almost the same as doing `ReplaceWith()`. But in this helper, the 1964 // uses of this instruction by `other` are *not* updated. 1965 void ReplaceWithExceptInReplacementAtIndex(HInstruction* other, size_t use_index) { 1966 ReplaceWith(other); 1967 other->ReplaceInput(this, use_index); 1968 } 1969 1970 // Move `this` instruction before `cursor`. 1971 void MoveBefore(HInstruction* cursor); 1972 1973 // Move `this` before its first user and out of any loops. If there is no 1974 // out-of-loop user that dominates all other users, move the instruction 1975 // to the end of the out-of-loop common dominator of the user's blocks. 1976 // 1977 // This can be used only on non-throwing instructions with no side effects that 1978 // have at least one use but no environment uses. 1979 void MoveBeforeFirstUserAndOutOfLoops(); 1980 1981#define INSTRUCTION_TYPE_CHECK(type, super) \ 1982 bool Is##type() const; \ 1983 const H##type* As##type() const; \ 1984 H##type* As##type(); 1985 1986 FOR_EACH_CONCRETE_INSTRUCTION(INSTRUCTION_TYPE_CHECK) 1987#undef INSTRUCTION_TYPE_CHECK 1988 1989#define INSTRUCTION_TYPE_CHECK(type, super) \ 1990 bool Is##type() const { return (As##type() != nullptr); } \ 1991 virtual const H##type* As##type() const { return nullptr; } \ 1992 virtual H##type* As##type() { return nullptr; } 1993 FOR_EACH_ABSTRACT_INSTRUCTION(INSTRUCTION_TYPE_CHECK) 1994#undef INSTRUCTION_TYPE_CHECK 1995 1996 // Returns whether the instruction can be moved within the graph. 1997 virtual bool CanBeMoved() const { return false; } 1998 1999 // Returns whether the two instructions are of the same kind. 2000 virtual bool InstructionTypeEquals(HInstruction* other ATTRIBUTE_UNUSED) const { 2001 return false; 2002 } 2003 2004 // Returns whether any data encoded in the two instructions is equal. 2005 // This method does not look at the inputs. Both instructions must be 2006 // of the same type, otherwise the method has undefined behavior. 2007 virtual bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const { 2008 return false; 2009 } 2010 2011 // Returns whether two instructions are equal, that is: 2012 // 1) They have the same type and contain the same data (InstructionDataEquals). 2013 // 2) Their inputs are identical. 2014 bool Equals(HInstruction* other) const; 2015 2016 // TODO: Remove this indirection when the [[pure]] attribute proposal (n3744) 2017 // is adopted and implemented by our C++ compiler(s). Fow now, we need to hide 2018 // the virtual function because the __attribute__((__pure__)) doesn't really 2019 // apply the strong requirement for virtual functions, preventing optimizations. 2020 InstructionKind GetKind() const PURE; 2021 virtual InstructionKind GetKindInternal() const = 0; 2022 2023 virtual size_t ComputeHashCode() const { 2024 size_t result = GetKind(); 2025 for (size_t i = 0, e = InputCount(); i < e; ++i) { 2026 result = (result * 31) + InputAt(i)->GetId(); 2027 } 2028 return result; 2029 } 2030 2031 SideEffects GetSideEffects() const { return side_effects_; } 2032 void AddSideEffects(SideEffects other) { side_effects_.Add(other); } 2033 2034 size_t GetLifetimePosition() const { return lifetime_position_; } 2035 void SetLifetimePosition(size_t position) { lifetime_position_ = position; } 2036 LiveInterval* GetLiveInterval() const { return live_interval_; } 2037 void SetLiveInterval(LiveInterval* interval) { live_interval_ = interval; } 2038 bool HasLiveInterval() const { return live_interval_ != nullptr; } 2039 2040 bool IsSuspendCheckEntry() const { return IsSuspendCheck() && GetBlock()->IsEntryBlock(); } 2041 2042 // Returns whether the code generation of the instruction will require to have access 2043 // to the current method. Such instructions are: 2044 // (1): Instructions that require an environment, as calling the runtime requires 2045 // to walk the stack and have the current method stored at a specific stack address. 2046 // (2): Object literals like classes and strings, that are loaded from the dex cache 2047 // fields of the current method. 2048 bool NeedsCurrentMethod() const { 2049 return NeedsEnvironment() || IsLoadClass() || IsLoadString(); 2050 } 2051 2052 // Returns whether the code generation of the instruction will require to have access 2053 // to the dex cache of the current method's declaring class via the current method. 2054 virtual bool NeedsDexCacheOfDeclaringClass() const { return false; } 2055 2056 // Does this instruction have any use in an environment before 2057 // control flow hits 'other'? 2058 bool HasAnyEnvironmentUseBefore(HInstruction* other); 2059 2060 // Remove all references to environment uses of this instruction. 2061 // The caller must ensure that this is safe to do. 2062 void RemoveEnvironmentUsers(); 2063 2064 protected: 2065 virtual const HUserRecord<HInstruction*> InputRecordAt(size_t i) const = 0; 2066 virtual void SetRawInputRecordAt(size_t index, const HUserRecord<HInstruction*>& input) = 0; 2067 2068 private: 2069 void RemoveEnvironmentUser(HUseListNode<HEnvironment*>* use_node) { env_uses_.Remove(use_node); } 2070 2071 HInstruction* previous_; 2072 HInstruction* next_; 2073 HBasicBlock* block_; 2074 const uint32_t dex_pc_; 2075 2076 // An instruction gets an id when it is added to the graph. 2077 // It reflects creation order. A negative id means the instruction 2078 // has not been added to the graph. 2079 int id_; 2080 2081 // When doing liveness analysis, instructions that have uses get an SSA index. 2082 int ssa_index_; 2083 2084 // List of instructions that have this instruction as input. 2085 HUseList<HInstruction*> uses_; 2086 2087 // List of environments that contain this instruction. 2088 HUseList<HEnvironment*> env_uses_; 2089 2090 // The environment associated with this instruction. Not null if the instruction 2091 // might jump out of the method. 2092 HEnvironment* environment_; 2093 2094 // Set by the code generator. 2095 LocationSummary* locations_; 2096 2097 // Set by the liveness analysis. 2098 LiveInterval* live_interval_; 2099 2100 // Set by the liveness analysis, this is the position in a linear 2101 // order of blocks where this instruction's live interval start. 2102 size_t lifetime_position_; 2103 2104 SideEffects side_effects_; 2105 2106 // TODO: for primitive types this should be marked as invalid. 2107 ReferenceTypeInfo reference_type_info_; 2108 2109 friend class GraphChecker; 2110 friend class HBasicBlock; 2111 friend class HEnvironment; 2112 friend class HGraph; 2113 friend class HInstructionList; 2114 2115 DISALLOW_COPY_AND_ASSIGN(HInstruction); 2116}; 2117std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs); 2118 2119class HInputIterator : public ValueObject { 2120 public: 2121 explicit HInputIterator(HInstruction* instruction) : instruction_(instruction), index_(0) {} 2122 2123 bool Done() const { return index_ == instruction_->InputCount(); } 2124 HInstruction* Current() const { return instruction_->InputAt(index_); } 2125 void Advance() { index_++; } 2126 2127 private: 2128 HInstruction* instruction_; 2129 size_t index_; 2130 2131 DISALLOW_COPY_AND_ASSIGN(HInputIterator); 2132}; 2133 2134class HInstructionIterator : public ValueObject { 2135 public: 2136 explicit HInstructionIterator(const HInstructionList& instructions) 2137 : instruction_(instructions.first_instruction_) { 2138 next_ = Done() ? nullptr : instruction_->GetNext(); 2139 } 2140 2141 bool Done() const { return instruction_ == nullptr; } 2142 HInstruction* Current() const { return instruction_; } 2143 void Advance() { 2144 instruction_ = next_; 2145 next_ = Done() ? nullptr : instruction_->GetNext(); 2146 } 2147 2148 private: 2149 HInstruction* instruction_; 2150 HInstruction* next_; 2151 2152 DISALLOW_COPY_AND_ASSIGN(HInstructionIterator); 2153}; 2154 2155class HBackwardInstructionIterator : public ValueObject { 2156 public: 2157 explicit HBackwardInstructionIterator(const HInstructionList& instructions) 2158 : instruction_(instructions.last_instruction_) { 2159 next_ = Done() ? nullptr : instruction_->GetPrevious(); 2160 } 2161 2162 bool Done() const { return instruction_ == nullptr; } 2163 HInstruction* Current() const { return instruction_; } 2164 void Advance() { 2165 instruction_ = next_; 2166 next_ = Done() ? nullptr : instruction_->GetPrevious(); 2167 } 2168 2169 private: 2170 HInstruction* instruction_; 2171 HInstruction* next_; 2172 2173 DISALLOW_COPY_AND_ASSIGN(HBackwardInstructionIterator); 2174}; 2175 2176template<size_t N> 2177class HTemplateInstruction: public HInstruction { 2178 public: 2179 HTemplateInstruction<N>(SideEffects side_effects, uint32_t dex_pc) 2180 : HInstruction(side_effects, dex_pc), inputs_() {} 2181 virtual ~HTemplateInstruction() {} 2182 2183 size_t InputCount() const OVERRIDE { return N; } 2184 2185 protected: 2186 const HUserRecord<HInstruction*> InputRecordAt(size_t i) const OVERRIDE { 2187 DCHECK_LT(i, N); 2188 return inputs_[i]; 2189 } 2190 2191 void SetRawInputRecordAt(size_t i, const HUserRecord<HInstruction*>& input) OVERRIDE { 2192 DCHECK_LT(i, N); 2193 inputs_[i] = input; 2194 } 2195 2196 private: 2197 std::array<HUserRecord<HInstruction*>, N> inputs_; 2198 2199 friend class SsaBuilder; 2200}; 2201 2202// HTemplateInstruction specialization for N=0. 2203template<> 2204class HTemplateInstruction<0>: public HInstruction { 2205 public: 2206 explicit HTemplateInstruction<0>(SideEffects side_effects, uint32_t dex_pc) 2207 : HInstruction(side_effects, dex_pc) {} 2208 2209 virtual ~HTemplateInstruction() {} 2210 2211 size_t InputCount() const OVERRIDE { return 0; } 2212 2213 protected: 2214 const HUserRecord<HInstruction*> InputRecordAt(size_t i ATTRIBUTE_UNUSED) const OVERRIDE { 2215 LOG(FATAL) << "Unreachable"; 2216 UNREACHABLE(); 2217 } 2218 2219 void SetRawInputRecordAt(size_t i ATTRIBUTE_UNUSED, 2220 const HUserRecord<HInstruction*>& input ATTRIBUTE_UNUSED) OVERRIDE { 2221 LOG(FATAL) << "Unreachable"; 2222 UNREACHABLE(); 2223 } 2224 2225 private: 2226 friend class SsaBuilder; 2227}; 2228 2229template<intptr_t N> 2230class HExpression : public HTemplateInstruction<N> { 2231 public: 2232 HExpression<N>(Primitive::Type type, SideEffects side_effects, uint32_t dex_pc) 2233 : HTemplateInstruction<N>(side_effects, dex_pc), type_(type) {} 2234 virtual ~HExpression() {} 2235 2236 Primitive::Type GetType() const OVERRIDE { return type_; } 2237 2238 protected: 2239 Primitive::Type type_; 2240}; 2241 2242// Represents dex's RETURN_VOID opcode. A HReturnVoid is a control flow 2243// instruction that branches to the exit block. 2244class HReturnVoid : public HTemplateInstruction<0> { 2245 public: 2246 explicit HReturnVoid(uint32_t dex_pc = kNoDexPc) 2247 : HTemplateInstruction(SideEffects::None(), dex_pc) {} 2248 2249 bool IsControlFlow() const OVERRIDE { return true; } 2250 2251 DECLARE_INSTRUCTION(ReturnVoid); 2252 2253 private: 2254 DISALLOW_COPY_AND_ASSIGN(HReturnVoid); 2255}; 2256 2257// Represents dex's RETURN opcodes. A HReturn is a control flow 2258// instruction that branches to the exit block. 2259class HReturn : public HTemplateInstruction<1> { 2260 public: 2261 explicit HReturn(HInstruction* value, uint32_t dex_pc = kNoDexPc) 2262 : HTemplateInstruction(SideEffects::None(), dex_pc) { 2263 SetRawInputAt(0, value); 2264 } 2265 2266 bool IsControlFlow() const OVERRIDE { return true; } 2267 2268 DECLARE_INSTRUCTION(Return); 2269 2270 private: 2271 DISALLOW_COPY_AND_ASSIGN(HReturn); 2272}; 2273 2274// The exit instruction is the only instruction of the exit block. 2275// Instructions aborting the method (HThrow and HReturn) must branch to the 2276// exit block. 2277class HExit : public HTemplateInstruction<0> { 2278 public: 2279 explicit HExit(uint32_t dex_pc = kNoDexPc) : HTemplateInstruction(SideEffects::None(), dex_pc) {} 2280 2281 bool IsControlFlow() const OVERRIDE { return true; } 2282 2283 DECLARE_INSTRUCTION(Exit); 2284 2285 private: 2286 DISALLOW_COPY_AND_ASSIGN(HExit); 2287}; 2288 2289// Jumps from one block to another. 2290class HGoto : public HTemplateInstruction<0> { 2291 public: 2292 explicit HGoto(uint32_t dex_pc = kNoDexPc) : HTemplateInstruction(SideEffects::None(), dex_pc) {} 2293 2294 bool IsControlFlow() const OVERRIDE { return true; } 2295 2296 HBasicBlock* GetSuccessor() const { 2297 return GetBlock()->GetSingleSuccessor(); 2298 } 2299 2300 DECLARE_INSTRUCTION(Goto); 2301 2302 private: 2303 DISALLOW_COPY_AND_ASSIGN(HGoto); 2304}; 2305 2306class HConstant : public HExpression<0> { 2307 public: 2308 explicit HConstant(Primitive::Type type, uint32_t dex_pc = kNoDexPc) 2309 : HExpression(type, SideEffects::None(), dex_pc) {} 2310 2311 bool CanBeMoved() const OVERRIDE { return true; } 2312 2313 virtual bool IsMinusOne() const { return false; } 2314 virtual bool IsZero() const { return false; } 2315 virtual bool IsOne() const { return false; } 2316 2317 virtual uint64_t GetValueAsUint64() const = 0; 2318 2319 DECLARE_ABSTRACT_INSTRUCTION(Constant); 2320 2321 private: 2322 DISALLOW_COPY_AND_ASSIGN(HConstant); 2323}; 2324 2325class HNullConstant : public HConstant { 2326 public: 2327 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 2328 return true; 2329 } 2330 2331 uint64_t GetValueAsUint64() const OVERRIDE { return 0; } 2332 2333 size_t ComputeHashCode() const OVERRIDE { return 0; } 2334 2335 DECLARE_INSTRUCTION(NullConstant); 2336 2337 private: 2338 explicit HNullConstant(uint32_t dex_pc = kNoDexPc) : HConstant(Primitive::kPrimNot, dex_pc) {} 2339 2340 friend class HGraph; 2341 DISALLOW_COPY_AND_ASSIGN(HNullConstant); 2342}; 2343 2344// Constants of the type int. Those can be from Dex instructions, or 2345// synthesized (for example with the if-eqz instruction). 2346class HIntConstant : public HConstant { 2347 public: 2348 int32_t GetValue() const { return value_; } 2349 2350 uint64_t GetValueAsUint64() const OVERRIDE { 2351 return static_cast<uint64_t>(static_cast<uint32_t>(value_)); 2352 } 2353 2354 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 2355 DCHECK(other->IsIntConstant()); 2356 return other->AsIntConstant()->value_ == value_; 2357 } 2358 2359 size_t ComputeHashCode() const OVERRIDE { return GetValue(); } 2360 2361 bool IsMinusOne() const OVERRIDE { return GetValue() == -1; } 2362 bool IsZero() const OVERRIDE { return GetValue() == 0; } 2363 bool IsOne() const OVERRIDE { return GetValue() == 1; } 2364 2365 DECLARE_INSTRUCTION(IntConstant); 2366 2367 private: 2368 explicit HIntConstant(int32_t value, uint32_t dex_pc = kNoDexPc) 2369 : HConstant(Primitive::kPrimInt, dex_pc), value_(value) {} 2370 explicit HIntConstant(bool value, uint32_t dex_pc = kNoDexPc) 2371 : HConstant(Primitive::kPrimInt, dex_pc), value_(value ? 1 : 0) {} 2372 2373 const int32_t value_; 2374 2375 friend class HGraph; 2376 ART_FRIEND_TEST(GraphTest, InsertInstructionBefore); 2377 ART_FRIEND_TYPED_TEST(ParallelMoveTest, ConstantLast); 2378 DISALLOW_COPY_AND_ASSIGN(HIntConstant); 2379}; 2380 2381class HLongConstant : public HConstant { 2382 public: 2383 int64_t GetValue() const { return value_; } 2384 2385 uint64_t GetValueAsUint64() const OVERRIDE { return value_; } 2386 2387 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 2388 DCHECK(other->IsLongConstant()); 2389 return other->AsLongConstant()->value_ == value_; 2390 } 2391 2392 size_t ComputeHashCode() const OVERRIDE { return static_cast<size_t>(GetValue()); } 2393 2394 bool IsMinusOne() const OVERRIDE { return GetValue() == -1; } 2395 bool IsZero() const OVERRIDE { return GetValue() == 0; } 2396 bool IsOne() const OVERRIDE { return GetValue() == 1; } 2397 2398 DECLARE_INSTRUCTION(LongConstant); 2399 2400 private: 2401 explicit HLongConstant(int64_t value, uint32_t dex_pc = kNoDexPc) 2402 : HConstant(Primitive::kPrimLong, dex_pc), value_(value) {} 2403 2404 const int64_t value_; 2405 2406 friend class HGraph; 2407 DISALLOW_COPY_AND_ASSIGN(HLongConstant); 2408}; 2409 2410// Conditional branch. A block ending with an HIf instruction must have 2411// two successors. 2412class HIf : public HTemplateInstruction<1> { 2413 public: 2414 explicit HIf(HInstruction* input, uint32_t dex_pc = kNoDexPc) 2415 : HTemplateInstruction(SideEffects::None(), dex_pc) { 2416 SetRawInputAt(0, input); 2417 } 2418 2419 bool IsControlFlow() const OVERRIDE { return true; } 2420 2421 HBasicBlock* IfTrueSuccessor() const { 2422 return GetBlock()->GetSuccessors()[0]; 2423 } 2424 2425 HBasicBlock* IfFalseSuccessor() const { 2426 return GetBlock()->GetSuccessors()[1]; 2427 } 2428 2429 DECLARE_INSTRUCTION(If); 2430 2431 private: 2432 DISALLOW_COPY_AND_ASSIGN(HIf); 2433}; 2434 2435 2436// Abstract instruction which marks the beginning and/or end of a try block and 2437// links it to the respective exception handlers. Behaves the same as a Goto in 2438// non-exceptional control flow. 2439// Normal-flow successor is stored at index zero, exception handlers under 2440// higher indices in no particular order. 2441class HTryBoundary : public HTemplateInstruction<0> { 2442 public: 2443 enum BoundaryKind { 2444 kEntry, 2445 kExit, 2446 }; 2447 2448 explicit HTryBoundary(BoundaryKind kind, uint32_t dex_pc = kNoDexPc) 2449 : HTemplateInstruction(SideEffects::None(), dex_pc), kind_(kind) {} 2450 2451 bool IsControlFlow() const OVERRIDE { return true; } 2452 2453 // Returns the block's non-exceptional successor (index zero). 2454 HBasicBlock* GetNormalFlowSuccessor() const { return GetBlock()->GetSuccessors()[0]; } 2455 2456 ArrayRef<HBasicBlock* const> GetExceptionHandlers() const { 2457 return ArrayRef<HBasicBlock* const>(GetBlock()->GetSuccessors()).SubArray(1u); 2458 } 2459 2460 // Returns whether `handler` is among its exception handlers (non-zero index 2461 // successors). 2462 bool HasExceptionHandler(const HBasicBlock& handler) const { 2463 DCHECK(handler.IsCatchBlock()); 2464 return GetBlock()->HasSuccessor(&handler, 1u /* Skip first successor. */); 2465 } 2466 2467 // If not present already, adds `handler` to its block's list of exception 2468 // handlers. 2469 void AddExceptionHandler(HBasicBlock* handler) { 2470 if (!HasExceptionHandler(*handler)) { 2471 GetBlock()->AddSuccessor(handler); 2472 } 2473 } 2474 2475 bool IsEntry() const { return kind_ == BoundaryKind::kEntry; } 2476 2477 bool HasSameExceptionHandlersAs(const HTryBoundary& other) const; 2478 2479 DECLARE_INSTRUCTION(TryBoundary); 2480 2481 private: 2482 const BoundaryKind kind_; 2483 2484 DISALLOW_COPY_AND_ASSIGN(HTryBoundary); 2485}; 2486 2487// Deoptimize to interpreter, upon checking a condition. 2488class HDeoptimize : public HTemplateInstruction<1> { 2489 public: 2490 HDeoptimize(HInstruction* cond, uint32_t dex_pc) 2491 : HTemplateInstruction(SideEffects::None(), dex_pc) { 2492 SetRawInputAt(0, cond); 2493 } 2494 2495 bool CanBeMoved() const OVERRIDE { return true; } 2496 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 2497 return true; 2498 } 2499 bool NeedsEnvironment() const OVERRIDE { return true; } 2500 bool CanThrow() const OVERRIDE { return true; } 2501 2502 DECLARE_INSTRUCTION(Deoptimize); 2503 2504 private: 2505 DISALLOW_COPY_AND_ASSIGN(HDeoptimize); 2506}; 2507 2508// Represents the ArtMethod that was passed as a first argument to 2509// the method. It is used by instructions that depend on it, like 2510// instructions that work with the dex cache. 2511class HCurrentMethod : public HExpression<0> { 2512 public: 2513 explicit HCurrentMethod(Primitive::Type type, uint32_t dex_pc = kNoDexPc) 2514 : HExpression(type, SideEffects::None(), dex_pc) {} 2515 2516 DECLARE_INSTRUCTION(CurrentMethod); 2517 2518 private: 2519 DISALLOW_COPY_AND_ASSIGN(HCurrentMethod); 2520}; 2521 2522// PackedSwitch (jump table). A block ending with a PackedSwitch instruction will 2523// have one successor for each entry in the switch table, and the final successor 2524// will be the block containing the next Dex opcode. 2525class HPackedSwitch : public HTemplateInstruction<1> { 2526 public: 2527 HPackedSwitch(int32_t start_value, 2528 uint32_t num_entries, 2529 HInstruction* input, 2530 uint32_t dex_pc = kNoDexPc) 2531 : HTemplateInstruction(SideEffects::None(), dex_pc), 2532 start_value_(start_value), 2533 num_entries_(num_entries) { 2534 SetRawInputAt(0, input); 2535 } 2536 2537 bool IsControlFlow() const OVERRIDE { return true; } 2538 2539 int32_t GetStartValue() const { return start_value_; } 2540 2541 uint32_t GetNumEntries() const { return num_entries_; } 2542 2543 HBasicBlock* GetDefaultBlock() const { 2544 // Last entry is the default block. 2545 return GetBlock()->GetSuccessors()[num_entries_]; 2546 } 2547 DECLARE_INSTRUCTION(PackedSwitch); 2548 2549 private: 2550 const int32_t start_value_; 2551 const uint32_t num_entries_; 2552 2553 DISALLOW_COPY_AND_ASSIGN(HPackedSwitch); 2554}; 2555 2556class HUnaryOperation : public HExpression<1> { 2557 public: 2558 HUnaryOperation(Primitive::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc) 2559 : HExpression(result_type, SideEffects::None(), dex_pc) { 2560 SetRawInputAt(0, input); 2561 } 2562 2563 HInstruction* GetInput() const { return InputAt(0); } 2564 Primitive::Type GetResultType() const { return GetType(); } 2565 2566 bool CanBeMoved() const OVERRIDE { return true; } 2567 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 2568 return true; 2569 } 2570 2571 // Try to statically evaluate `operation` and return a HConstant 2572 // containing the result of this evaluation. If `operation` cannot 2573 // be evaluated as a constant, return null. 2574 HConstant* TryStaticEvaluation() const; 2575 2576 // Apply this operation to `x`. 2577 virtual HConstant* Evaluate(HIntConstant* x) const = 0; 2578 virtual HConstant* Evaluate(HLongConstant* x) const = 0; 2579 2580 DECLARE_ABSTRACT_INSTRUCTION(UnaryOperation); 2581 2582 private: 2583 DISALLOW_COPY_AND_ASSIGN(HUnaryOperation); 2584}; 2585 2586class HBinaryOperation : public HExpression<2> { 2587 public: 2588 HBinaryOperation(Primitive::Type result_type, 2589 HInstruction* left, 2590 HInstruction* right, 2591 SideEffects side_effects = SideEffects::None(), 2592 uint32_t dex_pc = kNoDexPc) 2593 : HExpression(result_type, side_effects, dex_pc) { 2594 SetRawInputAt(0, left); 2595 SetRawInputAt(1, right); 2596 } 2597 2598 HInstruction* GetLeft() const { return InputAt(0); } 2599 HInstruction* GetRight() const { return InputAt(1); } 2600 Primitive::Type GetResultType() const { return GetType(); } 2601 2602 virtual bool IsCommutative() const { return false; } 2603 2604 // Put constant on the right. 2605 // Returns whether order is changed. 2606 bool OrderInputsWithConstantOnTheRight() { 2607 HInstruction* left = InputAt(0); 2608 HInstruction* right = InputAt(1); 2609 if (left->IsConstant() && !right->IsConstant()) { 2610 ReplaceInput(right, 0); 2611 ReplaceInput(left, 1); 2612 return true; 2613 } 2614 return false; 2615 } 2616 2617 // Order inputs by instruction id, but favor constant on the right side. 2618 // This helps GVN for commutative ops. 2619 void OrderInputs() { 2620 DCHECK(IsCommutative()); 2621 HInstruction* left = InputAt(0); 2622 HInstruction* right = InputAt(1); 2623 if (left == right || (!left->IsConstant() && right->IsConstant())) { 2624 return; 2625 } 2626 if (OrderInputsWithConstantOnTheRight()) { 2627 return; 2628 } 2629 // Order according to instruction id. 2630 if (left->GetId() > right->GetId()) { 2631 ReplaceInput(right, 0); 2632 ReplaceInput(left, 1); 2633 } 2634 } 2635 2636 bool CanBeMoved() const OVERRIDE { return true; } 2637 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 2638 return true; 2639 } 2640 2641 // Try to statically evaluate `operation` and return a HConstant 2642 // containing the result of this evaluation. If `operation` cannot 2643 // be evaluated as a constant, return null. 2644 HConstant* TryStaticEvaluation() const; 2645 2646 // Apply this operation to `x` and `y`. 2647 virtual HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const = 0; 2648 virtual HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const = 0; 2649 virtual HConstant* Evaluate(HIntConstant* x ATTRIBUTE_UNUSED, 2650 HLongConstant* y ATTRIBUTE_UNUSED) const { 2651 VLOG(compiler) << DebugName() << " is not defined for the (int, long) case."; 2652 return nullptr; 2653 } 2654 virtual HConstant* Evaluate(HLongConstant* x ATTRIBUTE_UNUSED, 2655 HIntConstant* y ATTRIBUTE_UNUSED) const { 2656 VLOG(compiler) << DebugName() << " is not defined for the (long, int) case."; 2657 return nullptr; 2658 } 2659 virtual HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED, 2660 HNullConstant* y ATTRIBUTE_UNUSED) const { 2661 VLOG(compiler) << DebugName() << " is not defined for the (null, null) case."; 2662 return nullptr; 2663 } 2664 2665 // Returns an input that can legally be used as the right input and is 2666 // constant, or null. 2667 HConstant* GetConstantRight() const; 2668 2669 // If `GetConstantRight()` returns one of the input, this returns the other 2670 // one. Otherwise it returns null. 2671 HInstruction* GetLeastConstantLeft() const; 2672 2673 DECLARE_ABSTRACT_INSTRUCTION(BinaryOperation); 2674 2675 private: 2676 DISALLOW_COPY_AND_ASSIGN(HBinaryOperation); 2677}; 2678 2679// The comparison bias applies for floating point operations and indicates how NaN 2680// comparisons are treated: 2681enum class ComparisonBias { 2682 kNoBias, // bias is not applicable (i.e. for long operation) 2683 kGtBias, // return 1 for NaN comparisons 2684 kLtBias, // return -1 for NaN comparisons 2685}; 2686 2687class HCondition : public HBinaryOperation { 2688 public: 2689 HCondition(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2690 : HBinaryOperation(Primitive::kPrimBoolean, first, second, SideEffects::None(), dex_pc), 2691 needs_materialization_(true), 2692 bias_(ComparisonBias::kNoBias) {} 2693 2694 bool NeedsMaterialization() const { return needs_materialization_; } 2695 void ClearNeedsMaterialization() { needs_materialization_ = false; } 2696 2697 // For code generation purposes, returns whether this instruction is just before 2698 // `instruction`, and disregard moves in between. 2699 bool IsBeforeWhenDisregardMoves(HInstruction* instruction) const; 2700 2701 DECLARE_ABSTRACT_INSTRUCTION(Condition); 2702 2703 virtual IfCondition GetCondition() const = 0; 2704 2705 virtual IfCondition GetOppositeCondition() const = 0; 2706 2707 bool IsGtBias() const { return bias_ == ComparisonBias::kGtBias; } 2708 2709 void SetBias(ComparisonBias bias) { bias_ = bias; } 2710 2711 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 2712 return bias_ == other->AsCondition()->bias_; 2713 } 2714 2715 bool IsFPConditionTrueIfNaN() const { 2716 DCHECK(Primitive::IsFloatingPointType(InputAt(0)->GetType())); 2717 IfCondition if_cond = GetCondition(); 2718 return IsGtBias() ? ((if_cond == kCondGT) || (if_cond == kCondGE)) : (if_cond == kCondNE); 2719 } 2720 2721 bool IsFPConditionFalseIfNaN() const { 2722 DCHECK(Primitive::IsFloatingPointType(InputAt(0)->GetType())); 2723 IfCondition if_cond = GetCondition(); 2724 return IsGtBias() ? ((if_cond == kCondLT) || (if_cond == kCondLE)) : (if_cond == kCondEQ); 2725 } 2726 2727 private: 2728 // For register allocation purposes, returns whether this instruction needs to be 2729 // materialized (that is, not just be in the processor flags). 2730 bool needs_materialization_; 2731 2732 // Needed if we merge a HCompare into a HCondition. 2733 ComparisonBias bias_; 2734 2735 DISALLOW_COPY_AND_ASSIGN(HCondition); 2736}; 2737 2738// Instruction to check if two inputs are equal to each other. 2739class HEqual : public HCondition { 2740 public: 2741 HEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2742 : HCondition(first, second, dex_pc) {} 2743 2744 bool IsCommutative() const OVERRIDE { return true; } 2745 2746 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2747 return GetBlock()->GetGraph()->GetIntConstant( 2748 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2749 } 2750 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2751 return GetBlock()->GetGraph()->GetIntConstant( 2752 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2753 } 2754 HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED, 2755 HNullConstant* y ATTRIBUTE_UNUSED) const OVERRIDE { 2756 return GetBlock()->GetGraph()->GetIntConstant(1); 2757 } 2758 2759 DECLARE_INSTRUCTION(Equal); 2760 2761 IfCondition GetCondition() const OVERRIDE { 2762 return kCondEQ; 2763 } 2764 2765 IfCondition GetOppositeCondition() const OVERRIDE { 2766 return kCondNE; 2767 } 2768 2769 private: 2770 template <typename T> bool Compute(T x, T y) const { return x == y; } 2771 2772 DISALLOW_COPY_AND_ASSIGN(HEqual); 2773}; 2774 2775class HNotEqual : public HCondition { 2776 public: 2777 HNotEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2778 : HCondition(first, second, dex_pc) {} 2779 2780 bool IsCommutative() const OVERRIDE { return true; } 2781 2782 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2783 return GetBlock()->GetGraph()->GetIntConstant( 2784 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2785 } 2786 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2787 return GetBlock()->GetGraph()->GetIntConstant( 2788 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2789 } 2790 HConstant* Evaluate(HNullConstant* x ATTRIBUTE_UNUSED, 2791 HNullConstant* y ATTRIBUTE_UNUSED) const OVERRIDE { 2792 return GetBlock()->GetGraph()->GetIntConstant(0); 2793 } 2794 2795 DECLARE_INSTRUCTION(NotEqual); 2796 2797 IfCondition GetCondition() const OVERRIDE { 2798 return kCondNE; 2799 } 2800 2801 IfCondition GetOppositeCondition() const OVERRIDE { 2802 return kCondEQ; 2803 } 2804 2805 private: 2806 template <typename T> bool Compute(T x, T y) const { return x != y; } 2807 2808 DISALLOW_COPY_AND_ASSIGN(HNotEqual); 2809}; 2810 2811class HLessThan : public HCondition { 2812 public: 2813 HLessThan(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2814 : HCondition(first, second, dex_pc) {} 2815 2816 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2817 return GetBlock()->GetGraph()->GetIntConstant( 2818 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2819 } 2820 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2821 return GetBlock()->GetGraph()->GetIntConstant( 2822 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2823 } 2824 2825 DECLARE_INSTRUCTION(LessThan); 2826 2827 IfCondition GetCondition() const OVERRIDE { 2828 return kCondLT; 2829 } 2830 2831 IfCondition GetOppositeCondition() const OVERRIDE { 2832 return kCondGE; 2833 } 2834 2835 private: 2836 template <typename T> bool Compute(T x, T y) const { return x < y; } 2837 2838 DISALLOW_COPY_AND_ASSIGN(HLessThan); 2839}; 2840 2841class HLessThanOrEqual : public HCondition { 2842 public: 2843 HLessThanOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2844 : HCondition(first, second, dex_pc) {} 2845 2846 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2847 return GetBlock()->GetGraph()->GetIntConstant( 2848 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2849 } 2850 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2851 return GetBlock()->GetGraph()->GetIntConstant( 2852 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2853 } 2854 2855 DECLARE_INSTRUCTION(LessThanOrEqual); 2856 2857 IfCondition GetCondition() const OVERRIDE { 2858 return kCondLE; 2859 } 2860 2861 IfCondition GetOppositeCondition() const OVERRIDE { 2862 return kCondGT; 2863 } 2864 2865 private: 2866 template <typename T> bool Compute(T x, T y) const { return x <= y; } 2867 2868 DISALLOW_COPY_AND_ASSIGN(HLessThanOrEqual); 2869}; 2870 2871class HGreaterThan : public HCondition { 2872 public: 2873 HGreaterThan(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2874 : HCondition(first, second, dex_pc) {} 2875 2876 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2877 return GetBlock()->GetGraph()->GetIntConstant( 2878 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2879 } 2880 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2881 return GetBlock()->GetGraph()->GetIntConstant( 2882 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2883 } 2884 2885 DECLARE_INSTRUCTION(GreaterThan); 2886 2887 IfCondition GetCondition() const OVERRIDE { 2888 return kCondGT; 2889 } 2890 2891 IfCondition GetOppositeCondition() const OVERRIDE { 2892 return kCondLE; 2893 } 2894 2895 private: 2896 template <typename T> bool Compute(T x, T y) const { return x > y; } 2897 2898 DISALLOW_COPY_AND_ASSIGN(HGreaterThan); 2899}; 2900 2901class HGreaterThanOrEqual : public HCondition { 2902 public: 2903 HGreaterThanOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2904 : HCondition(first, second, dex_pc) {} 2905 2906 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2907 return GetBlock()->GetGraph()->GetIntConstant( 2908 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2909 } 2910 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2911 return GetBlock()->GetGraph()->GetIntConstant( 2912 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 2913 } 2914 2915 DECLARE_INSTRUCTION(GreaterThanOrEqual); 2916 2917 IfCondition GetCondition() const OVERRIDE { 2918 return kCondGE; 2919 } 2920 2921 IfCondition GetOppositeCondition() const OVERRIDE { 2922 return kCondLT; 2923 } 2924 2925 private: 2926 template <typename T> bool Compute(T x, T y) const { return x >= y; } 2927 2928 DISALLOW_COPY_AND_ASSIGN(HGreaterThanOrEqual); 2929}; 2930 2931class HBelow : public HCondition { 2932 public: 2933 HBelow(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2934 : HCondition(first, second, dex_pc) {} 2935 2936 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2937 return GetBlock()->GetGraph()->GetIntConstant( 2938 Compute(static_cast<uint32_t>(x->GetValue()), 2939 static_cast<uint32_t>(y->GetValue())), GetDexPc()); 2940 } 2941 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2942 return GetBlock()->GetGraph()->GetIntConstant( 2943 Compute(static_cast<uint64_t>(x->GetValue()), 2944 static_cast<uint64_t>(y->GetValue())), GetDexPc()); 2945 } 2946 2947 DECLARE_INSTRUCTION(Below); 2948 2949 IfCondition GetCondition() const OVERRIDE { 2950 return kCondB; 2951 } 2952 2953 IfCondition GetOppositeCondition() const OVERRIDE { 2954 return kCondAE; 2955 } 2956 2957 private: 2958 template <typename T> bool Compute(T x, T y) const { return x < y; } 2959 2960 DISALLOW_COPY_AND_ASSIGN(HBelow); 2961}; 2962 2963class HBelowOrEqual : public HCondition { 2964 public: 2965 HBelowOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2966 : HCondition(first, second, dex_pc) {} 2967 2968 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 2969 return GetBlock()->GetGraph()->GetIntConstant( 2970 Compute(static_cast<uint32_t>(x->GetValue()), 2971 static_cast<uint32_t>(y->GetValue())), GetDexPc()); 2972 } 2973 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 2974 return GetBlock()->GetGraph()->GetIntConstant( 2975 Compute(static_cast<uint64_t>(x->GetValue()), 2976 static_cast<uint64_t>(y->GetValue())), GetDexPc()); 2977 } 2978 2979 DECLARE_INSTRUCTION(BelowOrEqual); 2980 2981 IfCondition GetCondition() const OVERRIDE { 2982 return kCondBE; 2983 } 2984 2985 IfCondition GetOppositeCondition() const OVERRIDE { 2986 return kCondA; 2987 } 2988 2989 private: 2990 template <typename T> bool Compute(T x, T y) const { return x <= y; } 2991 2992 DISALLOW_COPY_AND_ASSIGN(HBelowOrEqual); 2993}; 2994 2995class HAbove : public HCondition { 2996 public: 2997 HAbove(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 2998 : HCondition(first, second, dex_pc) {} 2999 3000 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3001 return GetBlock()->GetGraph()->GetIntConstant( 3002 Compute(static_cast<uint32_t>(x->GetValue()), 3003 static_cast<uint32_t>(y->GetValue())), GetDexPc()); 3004 } 3005 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3006 return GetBlock()->GetGraph()->GetIntConstant( 3007 Compute(static_cast<uint64_t>(x->GetValue()), 3008 static_cast<uint64_t>(y->GetValue())), GetDexPc()); 3009 } 3010 3011 DECLARE_INSTRUCTION(Above); 3012 3013 IfCondition GetCondition() const OVERRIDE { 3014 return kCondA; 3015 } 3016 3017 IfCondition GetOppositeCondition() const OVERRIDE { 3018 return kCondBE; 3019 } 3020 3021 private: 3022 template <typename T> bool Compute(T x, T y) const { return x > y; } 3023 3024 DISALLOW_COPY_AND_ASSIGN(HAbove); 3025}; 3026 3027class HAboveOrEqual : public HCondition { 3028 public: 3029 HAboveOrEqual(HInstruction* first, HInstruction* second, uint32_t dex_pc = kNoDexPc) 3030 : HCondition(first, second, dex_pc) {} 3031 3032 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3033 return GetBlock()->GetGraph()->GetIntConstant( 3034 Compute(static_cast<uint32_t>(x->GetValue()), 3035 static_cast<uint32_t>(y->GetValue())), GetDexPc()); 3036 } 3037 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3038 return GetBlock()->GetGraph()->GetIntConstant( 3039 Compute(static_cast<uint64_t>(x->GetValue()), 3040 static_cast<uint64_t>(y->GetValue())), GetDexPc()); 3041 } 3042 3043 DECLARE_INSTRUCTION(AboveOrEqual); 3044 3045 IfCondition GetCondition() const OVERRIDE { 3046 return kCondAE; 3047 } 3048 3049 IfCondition GetOppositeCondition() const OVERRIDE { 3050 return kCondB; 3051 } 3052 3053 private: 3054 template <typename T> bool Compute(T x, T y) const { return x >= y; } 3055 3056 DISALLOW_COPY_AND_ASSIGN(HAboveOrEqual); 3057}; 3058 3059// Instruction to check how two inputs compare to each other. 3060// Result is 0 if input0 == input1, 1 if input0 > input1, or -1 if input0 < input1. 3061class HCompare : public HBinaryOperation { 3062 public: 3063 HCompare(Primitive::Type type, 3064 HInstruction* first, 3065 HInstruction* second, 3066 ComparisonBias bias, 3067 uint32_t dex_pc) 3068 : HBinaryOperation(Primitive::kPrimInt, 3069 first, 3070 second, 3071 SideEffectsForArchRuntimeCalls(type), 3072 dex_pc), 3073 bias_(bias) { 3074 DCHECK_EQ(type, first->GetType()); 3075 DCHECK_EQ(type, second->GetType()); 3076 } 3077 3078 template <typename T> 3079 int32_t Compute(T x, T y) const { return x == y ? 0 : x > y ? 1 : -1; } 3080 3081 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3082 return GetBlock()->GetGraph()->GetIntConstant( 3083 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3084 } 3085 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3086 return GetBlock()->GetGraph()->GetIntConstant( 3087 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3088 } 3089 3090 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 3091 return bias_ == other->AsCompare()->bias_; 3092 } 3093 3094 ComparisonBias GetBias() const { return bias_; } 3095 3096 bool IsGtBias() { return bias_ == ComparisonBias::kGtBias; } 3097 3098 3099 static SideEffects SideEffectsForArchRuntimeCalls(Primitive::Type type) { 3100 // MIPS64 uses a runtime call for FP comparisons. 3101 return Primitive::IsFloatingPointType(type) ? SideEffects::CanTriggerGC() : SideEffects::None(); 3102 } 3103 3104 DECLARE_INSTRUCTION(Compare); 3105 3106 private: 3107 const ComparisonBias bias_; 3108 3109 DISALLOW_COPY_AND_ASSIGN(HCompare); 3110}; 3111 3112// A local in the graph. Corresponds to a Dex register. 3113class HLocal : public HTemplateInstruction<0> { 3114 public: 3115 explicit HLocal(uint16_t reg_number) 3116 : HTemplateInstruction(SideEffects::None(), kNoDexPc), reg_number_(reg_number) {} 3117 3118 DECLARE_INSTRUCTION(Local); 3119 3120 uint16_t GetRegNumber() const { return reg_number_; } 3121 3122 private: 3123 // The Dex register number. 3124 const uint16_t reg_number_; 3125 3126 DISALLOW_COPY_AND_ASSIGN(HLocal); 3127}; 3128 3129// Load a given local. The local is an input of this instruction. 3130class HLoadLocal : public HExpression<1> { 3131 public: 3132 HLoadLocal(HLocal* local, Primitive::Type type, uint32_t dex_pc = kNoDexPc) 3133 : HExpression(type, SideEffects::None(), dex_pc) { 3134 SetRawInputAt(0, local); 3135 } 3136 3137 HLocal* GetLocal() const { return reinterpret_cast<HLocal*>(InputAt(0)); } 3138 3139 DECLARE_INSTRUCTION(LoadLocal); 3140 3141 private: 3142 DISALLOW_COPY_AND_ASSIGN(HLoadLocal); 3143}; 3144 3145// Store a value in a given local. This instruction has two inputs: the value 3146// and the local. 3147class HStoreLocal : public HTemplateInstruction<2> { 3148 public: 3149 HStoreLocal(HLocal* local, HInstruction* value, uint32_t dex_pc = kNoDexPc) 3150 : HTemplateInstruction(SideEffects::None(), dex_pc) { 3151 SetRawInputAt(0, local); 3152 SetRawInputAt(1, value); 3153 } 3154 3155 HLocal* GetLocal() const { return reinterpret_cast<HLocal*>(InputAt(0)); } 3156 3157 DECLARE_INSTRUCTION(StoreLocal); 3158 3159 private: 3160 DISALLOW_COPY_AND_ASSIGN(HStoreLocal); 3161}; 3162 3163class HFloatConstant : public HConstant { 3164 public: 3165 float GetValue() const { return value_; } 3166 3167 uint64_t GetValueAsUint64() const OVERRIDE { 3168 return static_cast<uint64_t>(bit_cast<uint32_t, float>(value_)); 3169 } 3170 3171 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 3172 DCHECK(other->IsFloatConstant()); 3173 return other->AsFloatConstant()->GetValueAsUint64() == GetValueAsUint64(); 3174 } 3175 3176 size_t ComputeHashCode() const OVERRIDE { return static_cast<size_t>(GetValue()); } 3177 3178 bool IsMinusOne() const OVERRIDE { 3179 return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>((-1.0f)); 3180 } 3181 bool IsZero() const OVERRIDE { 3182 return value_ == 0.0f; 3183 } 3184 bool IsOne() const OVERRIDE { 3185 return bit_cast<uint32_t, float>(value_) == bit_cast<uint32_t, float>(1.0f); 3186 } 3187 bool IsNaN() const { 3188 return std::isnan(value_); 3189 } 3190 3191 DECLARE_INSTRUCTION(FloatConstant); 3192 3193 private: 3194 explicit HFloatConstant(float value, uint32_t dex_pc = kNoDexPc) 3195 : HConstant(Primitive::kPrimFloat, dex_pc), value_(value) {} 3196 explicit HFloatConstant(int32_t value, uint32_t dex_pc = kNoDexPc) 3197 : HConstant(Primitive::kPrimFloat, dex_pc), value_(bit_cast<float, int32_t>(value)) {} 3198 3199 const float value_; 3200 3201 // Only the SsaBuilder and HGraph can create floating-point constants. 3202 friend class SsaBuilder; 3203 friend class HGraph; 3204 DISALLOW_COPY_AND_ASSIGN(HFloatConstant); 3205}; 3206 3207class HDoubleConstant : public HConstant { 3208 public: 3209 double GetValue() const { return value_; } 3210 3211 uint64_t GetValueAsUint64() const OVERRIDE { return bit_cast<uint64_t, double>(value_); } 3212 3213 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 3214 DCHECK(other->IsDoubleConstant()); 3215 return other->AsDoubleConstant()->GetValueAsUint64() == GetValueAsUint64(); 3216 } 3217 3218 size_t ComputeHashCode() const OVERRIDE { return static_cast<size_t>(GetValue()); } 3219 3220 bool IsMinusOne() const OVERRIDE { 3221 return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>((-1.0)); 3222 } 3223 bool IsZero() const OVERRIDE { 3224 return value_ == 0.0; 3225 } 3226 bool IsOne() const OVERRIDE { 3227 return bit_cast<uint64_t, double>(value_) == bit_cast<uint64_t, double>(1.0); 3228 } 3229 bool IsNaN() const { 3230 return std::isnan(value_); 3231 } 3232 3233 DECLARE_INSTRUCTION(DoubleConstant); 3234 3235 private: 3236 explicit HDoubleConstant(double value, uint32_t dex_pc = kNoDexPc) 3237 : HConstant(Primitive::kPrimDouble, dex_pc), value_(value) {} 3238 explicit HDoubleConstant(int64_t value, uint32_t dex_pc = kNoDexPc) 3239 : HConstant(Primitive::kPrimDouble, dex_pc), value_(bit_cast<double, int64_t>(value)) {} 3240 3241 const double value_; 3242 3243 // Only the SsaBuilder and HGraph can create floating-point constants. 3244 friend class SsaBuilder; 3245 friend class HGraph; 3246 DISALLOW_COPY_AND_ASSIGN(HDoubleConstant); 3247}; 3248 3249enum class Intrinsics { 3250#define OPTIMIZING_INTRINSICS(Name, IsStatic, NeedsEnvironmentOrCache) k ## Name, 3251#include "intrinsics_list.h" 3252 kNone, 3253 INTRINSICS_LIST(OPTIMIZING_INTRINSICS) 3254#undef INTRINSICS_LIST 3255#undef OPTIMIZING_INTRINSICS 3256}; 3257std::ostream& operator<<(std::ostream& os, const Intrinsics& intrinsic); 3258 3259enum IntrinsicNeedsEnvironmentOrCache { 3260 kNoEnvironmentOrCache, // Intrinsic does not require an environment or dex cache. 3261 kNeedsEnvironmentOrCache // Intrinsic requires an environment or requires a dex cache. 3262}; 3263 3264class HInvoke : public HInstruction { 3265 public: 3266 size_t InputCount() const OVERRIDE { return inputs_.size(); } 3267 3268 bool NeedsEnvironment() const OVERRIDE; 3269 3270 void SetArgumentAt(size_t index, HInstruction* argument) { 3271 SetRawInputAt(index, argument); 3272 } 3273 3274 // Return the number of arguments. This number can be lower than 3275 // the number of inputs returned by InputCount(), as some invoke 3276 // instructions (e.g. HInvokeStaticOrDirect) can have non-argument 3277 // inputs at the end of their list of inputs. 3278 uint32_t GetNumberOfArguments() const { return number_of_arguments_; } 3279 3280 Primitive::Type GetType() const OVERRIDE { return return_type_; } 3281 3282 3283 uint32_t GetDexMethodIndex() const { return dex_method_index_; } 3284 const DexFile& GetDexFile() const { return GetEnvironment()->GetDexFile(); } 3285 3286 InvokeType GetOriginalInvokeType() const { return original_invoke_type_; } 3287 3288 Intrinsics GetIntrinsic() const { 3289 return intrinsic_; 3290 } 3291 3292 void SetIntrinsic(Intrinsics intrinsic, IntrinsicNeedsEnvironmentOrCache needs_env_or_cache); 3293 3294 bool IsFromInlinedInvoke() const { 3295 return GetEnvironment()->IsFromInlinedInvoke(); 3296 } 3297 3298 bool CanThrow() const OVERRIDE { return true; } 3299 3300 uint32_t* GetIntrinsicOptimizations() { 3301 return &intrinsic_optimizations_; 3302 } 3303 3304 const uint32_t* GetIntrinsicOptimizations() const { 3305 return &intrinsic_optimizations_; 3306 } 3307 3308 bool IsIntrinsic() const { return intrinsic_ != Intrinsics::kNone; } 3309 3310 DECLARE_ABSTRACT_INSTRUCTION(Invoke); 3311 3312 protected: 3313 HInvoke(ArenaAllocator* arena, 3314 uint32_t number_of_arguments, 3315 uint32_t number_of_other_inputs, 3316 Primitive::Type return_type, 3317 uint32_t dex_pc, 3318 uint32_t dex_method_index, 3319 InvokeType original_invoke_type) 3320 : HInstruction( 3321 SideEffects::AllExceptGCDependency(), dex_pc), // Assume write/read on all fields/arrays. 3322 number_of_arguments_(number_of_arguments), 3323 inputs_(number_of_arguments + number_of_other_inputs, 3324 arena->Adapter(kArenaAllocInvokeInputs)), 3325 return_type_(return_type), 3326 dex_method_index_(dex_method_index), 3327 original_invoke_type_(original_invoke_type), 3328 intrinsic_(Intrinsics::kNone), 3329 intrinsic_optimizations_(0) { 3330 } 3331 3332 const HUserRecord<HInstruction*> InputRecordAt(size_t index) const OVERRIDE { 3333 return inputs_[index]; 3334 } 3335 3336 void SetRawInputRecordAt(size_t index, const HUserRecord<HInstruction*>& input) OVERRIDE { 3337 inputs_[index] = input; 3338 } 3339 3340 uint32_t number_of_arguments_; 3341 ArenaVector<HUserRecord<HInstruction*>> inputs_; 3342 const Primitive::Type return_type_; 3343 const uint32_t dex_method_index_; 3344 const InvokeType original_invoke_type_; 3345 Intrinsics intrinsic_; 3346 3347 // A magic word holding optimizations for intrinsics. See intrinsics.h. 3348 uint32_t intrinsic_optimizations_; 3349 3350 private: 3351 DISALLOW_COPY_AND_ASSIGN(HInvoke); 3352}; 3353 3354class HInvokeUnresolved : public HInvoke { 3355 public: 3356 HInvokeUnresolved(ArenaAllocator* arena, 3357 uint32_t number_of_arguments, 3358 Primitive::Type return_type, 3359 uint32_t dex_pc, 3360 uint32_t dex_method_index, 3361 InvokeType invoke_type) 3362 : HInvoke(arena, 3363 number_of_arguments, 3364 0u /* number_of_other_inputs */, 3365 return_type, 3366 dex_pc, 3367 dex_method_index, 3368 invoke_type) { 3369 } 3370 3371 DECLARE_INSTRUCTION(InvokeUnresolved); 3372 3373 private: 3374 DISALLOW_COPY_AND_ASSIGN(HInvokeUnresolved); 3375}; 3376 3377class HInvokeStaticOrDirect : public HInvoke { 3378 public: 3379 // Requirements of this method call regarding the class 3380 // initialization (clinit) check of its declaring class. 3381 enum class ClinitCheckRequirement { 3382 kNone, // Class already initialized. 3383 kExplicit, // Static call having explicit clinit check as last input. 3384 kImplicit, // Static call implicitly requiring a clinit check. 3385 }; 3386 3387 // Determines how to load the target ArtMethod*. 3388 enum class MethodLoadKind { 3389 // Use a String init ArtMethod* loaded from Thread entrypoints. 3390 kStringInit, 3391 3392 // Use the method's own ArtMethod* loaded by the register allocator. 3393 kRecursive, 3394 3395 // Use ArtMethod* at a known address, embed the direct address in the code. 3396 // Used for app->boot calls with non-relocatable image and for JIT-compiled calls. 3397 kDirectAddress, 3398 3399 // Use ArtMethod* at an address that will be known at link time, embed the direct 3400 // address in the code. If the image is relocatable, emit .patch_oat entry. 3401 // Used for app->boot calls with relocatable image and boot->boot calls, whether 3402 // the image relocatable or not. 3403 kDirectAddressWithFixup, 3404 3405 // Load from resoved methods array in the dex cache using a PC-relative load. 3406 // Used when we need to use the dex cache, for example for invoke-static that 3407 // may cause class initialization (the entry may point to a resolution method), 3408 // and we know that we can access the dex cache arrays using a PC-relative load. 3409 kDexCachePcRelative, 3410 3411 // Use ArtMethod* from the resolved methods of the compiled method's own ArtMethod*. 3412 // Used for JIT when we need to use the dex cache. This is also the last-resort-kind 3413 // used when other kinds are unavailable (say, dex cache arrays are not PC-relative) 3414 // or unimplemented or impractical (i.e. slow) on a particular architecture. 3415 kDexCacheViaMethod, 3416 }; 3417 3418 // Determines the location of the code pointer. 3419 enum class CodePtrLocation { 3420 // Recursive call, use local PC-relative call instruction. 3421 kCallSelf, 3422 3423 // Use PC-relative call instruction patched at link time. 3424 // Used for calls within an oat file, boot->boot or app->app. 3425 kCallPCRelative, 3426 3427 // Call to a known target address, embed the direct address in code. 3428 // Used for app->boot call with non-relocatable image and for JIT-compiled calls. 3429 kCallDirect, 3430 3431 // Call to a target address that will be known at link time, embed the direct 3432 // address in code. If the image is relocatable, emit .patch_oat entry. 3433 // Used for app->boot calls with relocatable image and boot->boot calls, whether 3434 // the image relocatable or not. 3435 kCallDirectWithFixup, 3436 3437 // Use code pointer from the ArtMethod*. 3438 // Used when we don't know the target code. This is also the last-resort-kind used when 3439 // other kinds are unimplemented or impractical (i.e. slow) on a particular architecture. 3440 kCallArtMethod, 3441 }; 3442 3443 struct DispatchInfo { 3444 MethodLoadKind method_load_kind; 3445 CodePtrLocation code_ptr_location; 3446 // The method load data holds 3447 // - thread entrypoint offset for kStringInit method if this is a string init invoke. 3448 // Note that there are multiple string init methods, each having its own offset. 3449 // - the method address for kDirectAddress 3450 // - the dex cache arrays offset for kDexCachePcRel. 3451 uint64_t method_load_data; 3452 uint64_t direct_code_ptr; 3453 }; 3454 3455 HInvokeStaticOrDirect(ArenaAllocator* arena, 3456 uint32_t number_of_arguments, 3457 Primitive::Type return_type, 3458 uint32_t dex_pc, 3459 uint32_t method_index, 3460 MethodReference target_method, 3461 DispatchInfo dispatch_info, 3462 InvokeType original_invoke_type, 3463 InvokeType optimized_invoke_type, 3464 ClinitCheckRequirement clinit_check_requirement) 3465 : HInvoke(arena, 3466 number_of_arguments, 3467 // There is potentially one extra argument for the HCurrentMethod node, and 3468 // potentially one other if the clinit check is explicit, and potentially 3469 // one other if the method is a string factory. 3470 (NeedsCurrentMethodInput(dispatch_info.method_load_kind) ? 1u : 0u) + 3471 (clinit_check_requirement == ClinitCheckRequirement::kExplicit ? 1u : 0u) + 3472 (dispatch_info.method_load_kind == MethodLoadKind::kStringInit ? 1u : 0u), 3473 return_type, 3474 dex_pc, 3475 method_index, 3476 original_invoke_type), 3477 optimized_invoke_type_(optimized_invoke_type), 3478 clinit_check_requirement_(clinit_check_requirement), 3479 target_method_(target_method), 3480 dispatch_info_(dispatch_info) { } 3481 3482 void SetDispatchInfo(const DispatchInfo& dispatch_info) { 3483 bool had_current_method_input = HasCurrentMethodInput(); 3484 bool needs_current_method_input = NeedsCurrentMethodInput(dispatch_info.method_load_kind); 3485 3486 // Using the current method is the default and once we find a better 3487 // method load kind, we should not go back to using the current method. 3488 DCHECK(had_current_method_input || !needs_current_method_input); 3489 3490 if (had_current_method_input && !needs_current_method_input) { 3491 DCHECK_EQ(InputAt(GetSpecialInputIndex()), GetBlock()->GetGraph()->GetCurrentMethod()); 3492 RemoveInputAt(GetSpecialInputIndex()); 3493 } 3494 dispatch_info_ = dispatch_info; 3495 } 3496 3497 void AddSpecialInput(HInstruction* input) { 3498 // We allow only one special input. 3499 DCHECK(!IsStringInit() && !HasCurrentMethodInput()); 3500 DCHECK(InputCount() == GetSpecialInputIndex() || 3501 (InputCount() == GetSpecialInputIndex() + 1 && IsStaticWithExplicitClinitCheck())); 3502 InsertInputAt(GetSpecialInputIndex(), input); 3503 } 3504 3505 bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const OVERRIDE { 3506 // We access the method via the dex cache so we can't do an implicit null check. 3507 // TODO: for intrinsics we can generate implicit null checks. 3508 return false; 3509 } 3510 3511 bool CanBeNull() const OVERRIDE { 3512 return return_type_ == Primitive::kPrimNot && !IsStringInit(); 3513 } 3514 3515 // Get the index of the special input, if any. 3516 // 3517 // If the invoke IsStringInit(), it initially has a HFakeString special argument 3518 // which is removed by the instruction simplifier; if the invoke HasCurrentMethodInput(), 3519 // the "special input" is the current method pointer; otherwise there may be one 3520 // platform-specific special input, such as PC-relative addressing base. 3521 uint32_t GetSpecialInputIndex() const { return GetNumberOfArguments(); } 3522 3523 InvokeType GetOptimizedInvokeType() const { return optimized_invoke_type_; } 3524 void SetOptimizedInvokeType(InvokeType invoke_type) { 3525 optimized_invoke_type_ = invoke_type; 3526 } 3527 3528 MethodLoadKind GetMethodLoadKind() const { return dispatch_info_.method_load_kind; } 3529 CodePtrLocation GetCodePtrLocation() const { return dispatch_info_.code_ptr_location; } 3530 bool IsRecursive() const { return GetMethodLoadKind() == MethodLoadKind::kRecursive; } 3531 bool NeedsDexCacheOfDeclaringClass() const OVERRIDE; 3532 bool IsStringInit() const { return GetMethodLoadKind() == MethodLoadKind::kStringInit; } 3533 bool HasMethodAddress() const { return GetMethodLoadKind() == MethodLoadKind::kDirectAddress; } 3534 bool HasPcRelativeDexCache() const { 3535 return GetMethodLoadKind() == MethodLoadKind::kDexCachePcRelative; 3536 } 3537 bool HasCurrentMethodInput() const { 3538 // This function can be called only after the invoke has been fully initialized by the builder. 3539 if (NeedsCurrentMethodInput(GetMethodLoadKind())) { 3540 DCHECK(InputAt(GetSpecialInputIndex())->IsCurrentMethod()); 3541 return true; 3542 } else { 3543 DCHECK(InputCount() == GetSpecialInputIndex() || 3544 !InputAt(GetSpecialInputIndex())->IsCurrentMethod()); 3545 return false; 3546 } 3547 } 3548 bool HasDirectCodePtr() const { return GetCodePtrLocation() == CodePtrLocation::kCallDirect; } 3549 MethodReference GetTargetMethod() const { return target_method_; } 3550 void SetTargetMethod(MethodReference method) { target_method_ = method; } 3551 3552 int32_t GetStringInitOffset() const { 3553 DCHECK(IsStringInit()); 3554 return dispatch_info_.method_load_data; 3555 } 3556 3557 uint64_t GetMethodAddress() const { 3558 DCHECK(HasMethodAddress()); 3559 return dispatch_info_.method_load_data; 3560 } 3561 3562 uint32_t GetDexCacheArrayOffset() const { 3563 DCHECK(HasPcRelativeDexCache()); 3564 return dispatch_info_.method_load_data; 3565 } 3566 3567 uint64_t GetDirectCodePtr() const { 3568 DCHECK(HasDirectCodePtr()); 3569 return dispatch_info_.direct_code_ptr; 3570 } 3571 3572 ClinitCheckRequirement GetClinitCheckRequirement() const { return clinit_check_requirement_; } 3573 3574 // Is this instruction a call to a static method? 3575 bool IsStatic() const { 3576 return GetOriginalInvokeType() == kStatic; 3577 } 3578 3579 // Remove the HClinitCheck or the replacement HLoadClass (set as last input by 3580 // PrepareForRegisterAllocation::VisitClinitCheck() in lieu of the initial HClinitCheck) 3581 // instruction; only relevant for static calls with explicit clinit check. 3582 void RemoveExplicitClinitCheck(ClinitCheckRequirement new_requirement) { 3583 DCHECK(IsStaticWithExplicitClinitCheck()); 3584 size_t last_input_index = InputCount() - 1; 3585 HInstruction* last_input = InputAt(last_input_index); 3586 DCHECK(last_input != nullptr); 3587 DCHECK(last_input->IsLoadClass() || last_input->IsClinitCheck()) << last_input->DebugName(); 3588 RemoveAsUserOfInput(last_input_index); 3589 inputs_.pop_back(); 3590 clinit_check_requirement_ = new_requirement; 3591 DCHECK(!IsStaticWithExplicitClinitCheck()); 3592 } 3593 3594 bool IsStringFactoryFor(HFakeString* str) const { 3595 if (!IsStringInit()) return false; 3596 DCHECK(!HasCurrentMethodInput()); 3597 if (InputCount() == (number_of_arguments_)) return false; 3598 return InputAt(InputCount() - 1)->AsFakeString() == str; 3599 } 3600 3601 void RemoveFakeStringArgumentAsLastInput() { 3602 DCHECK(IsStringInit()); 3603 size_t last_input_index = InputCount() - 1; 3604 HInstruction* last_input = InputAt(last_input_index); 3605 DCHECK(last_input != nullptr); 3606 DCHECK(last_input->IsFakeString()) << last_input->DebugName(); 3607 RemoveAsUserOfInput(last_input_index); 3608 inputs_.pop_back(); 3609 } 3610 3611 // Is this a call to a static method whose declaring class has an 3612 // explicit initialization check in the graph? 3613 bool IsStaticWithExplicitClinitCheck() const { 3614 return IsStatic() && (clinit_check_requirement_ == ClinitCheckRequirement::kExplicit); 3615 } 3616 3617 // Is this a call to a static method whose declaring class has an 3618 // implicit intialization check requirement? 3619 bool IsStaticWithImplicitClinitCheck() const { 3620 return IsStatic() && (clinit_check_requirement_ == ClinitCheckRequirement::kImplicit); 3621 } 3622 3623 // Does this method load kind need the current method as an input? 3624 static bool NeedsCurrentMethodInput(MethodLoadKind kind) { 3625 return kind == MethodLoadKind::kRecursive || kind == MethodLoadKind::kDexCacheViaMethod; 3626 } 3627 3628 DECLARE_INSTRUCTION(InvokeStaticOrDirect); 3629 3630 protected: 3631 const HUserRecord<HInstruction*> InputRecordAt(size_t i) const OVERRIDE { 3632 const HUserRecord<HInstruction*> input_record = HInvoke::InputRecordAt(i); 3633 if (kIsDebugBuild && IsStaticWithExplicitClinitCheck() && (i == InputCount() - 1)) { 3634 HInstruction* input = input_record.GetInstruction(); 3635 // `input` is the last input of a static invoke marked as having 3636 // an explicit clinit check. It must either be: 3637 // - an art::HClinitCheck instruction, set by art::HGraphBuilder; or 3638 // - an art::HLoadClass instruction, set by art::PrepareForRegisterAllocation. 3639 DCHECK(input != nullptr); 3640 DCHECK(input->IsClinitCheck() || input->IsLoadClass()) << input->DebugName(); 3641 } 3642 return input_record; 3643 } 3644 3645 void InsertInputAt(size_t index, HInstruction* input); 3646 void RemoveInputAt(size_t index); 3647 3648 private: 3649 InvokeType optimized_invoke_type_; 3650 ClinitCheckRequirement clinit_check_requirement_; 3651 // The target method may refer to different dex file or method index than the original 3652 // invoke. This happens for sharpened calls and for calls where a method was redeclared 3653 // in derived class to increase visibility. 3654 MethodReference target_method_; 3655 DispatchInfo dispatch_info_; 3656 3657 DISALLOW_COPY_AND_ASSIGN(HInvokeStaticOrDirect); 3658}; 3659std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs); 3660std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs); 3661 3662class HInvokeVirtual : public HInvoke { 3663 public: 3664 HInvokeVirtual(ArenaAllocator* arena, 3665 uint32_t number_of_arguments, 3666 Primitive::Type return_type, 3667 uint32_t dex_pc, 3668 uint32_t dex_method_index, 3669 uint32_t vtable_index) 3670 : HInvoke(arena, number_of_arguments, 0u, return_type, dex_pc, dex_method_index, kVirtual), 3671 vtable_index_(vtable_index) {} 3672 3673 bool CanDoImplicitNullCheckOn(HInstruction* obj) const OVERRIDE { 3674 // TODO: Add implicit null checks in intrinsics. 3675 return (obj == InputAt(0)) && !GetLocations()->Intrinsified(); 3676 } 3677 3678 uint32_t GetVTableIndex() const { return vtable_index_; } 3679 3680 DECLARE_INSTRUCTION(InvokeVirtual); 3681 3682 private: 3683 const uint32_t vtable_index_; 3684 3685 DISALLOW_COPY_AND_ASSIGN(HInvokeVirtual); 3686}; 3687 3688class HInvokeInterface : public HInvoke { 3689 public: 3690 HInvokeInterface(ArenaAllocator* arena, 3691 uint32_t number_of_arguments, 3692 Primitive::Type return_type, 3693 uint32_t dex_pc, 3694 uint32_t dex_method_index, 3695 uint32_t imt_index) 3696 : HInvoke(arena, number_of_arguments, 0u, return_type, dex_pc, dex_method_index, kInterface), 3697 imt_index_(imt_index) {} 3698 3699 bool CanDoImplicitNullCheckOn(HInstruction* obj) const OVERRIDE { 3700 // TODO: Add implicit null checks in intrinsics. 3701 return (obj == InputAt(0)) && !GetLocations()->Intrinsified(); 3702 } 3703 3704 uint32_t GetImtIndex() const { return imt_index_; } 3705 uint32_t GetDexMethodIndex() const { return dex_method_index_; } 3706 3707 DECLARE_INSTRUCTION(InvokeInterface); 3708 3709 private: 3710 const uint32_t imt_index_; 3711 3712 DISALLOW_COPY_AND_ASSIGN(HInvokeInterface); 3713}; 3714 3715class HNewInstance : public HExpression<2> { 3716 public: 3717 HNewInstance(HInstruction* cls, 3718 HCurrentMethod* current_method, 3719 uint32_t dex_pc, 3720 uint16_t type_index, 3721 const DexFile& dex_file, 3722 bool can_throw, 3723 bool finalizable, 3724 QuickEntrypointEnum entrypoint) 3725 : HExpression(Primitive::kPrimNot, SideEffects::CanTriggerGC(), dex_pc), 3726 type_index_(type_index), 3727 dex_file_(dex_file), 3728 can_throw_(can_throw), 3729 finalizable_(finalizable), 3730 entrypoint_(entrypoint) { 3731 SetRawInputAt(0, cls); 3732 SetRawInputAt(1, current_method); 3733 } 3734 3735 uint16_t GetTypeIndex() const { return type_index_; } 3736 const DexFile& GetDexFile() const { return dex_file_; } 3737 3738 // Calls runtime so needs an environment. 3739 bool NeedsEnvironment() const OVERRIDE { return true; } 3740 3741 // It may throw when called on type that's not instantiable/accessible. 3742 // It can throw OOME. 3743 // TODO: distinguish between the two cases so we can for example allow allocation elimination. 3744 bool CanThrow() const OVERRIDE { return can_throw_ || true; } 3745 3746 bool IsFinalizable() const { return finalizable_; } 3747 3748 bool CanBeNull() const OVERRIDE { return false; } 3749 3750 QuickEntrypointEnum GetEntrypoint() const { return entrypoint_; } 3751 3752 void SetEntrypoint(QuickEntrypointEnum entrypoint) { 3753 entrypoint_ = entrypoint; 3754 } 3755 3756 DECLARE_INSTRUCTION(NewInstance); 3757 3758 private: 3759 const uint16_t type_index_; 3760 const DexFile& dex_file_; 3761 const bool can_throw_; 3762 const bool finalizable_; 3763 QuickEntrypointEnum entrypoint_; 3764 3765 DISALLOW_COPY_AND_ASSIGN(HNewInstance); 3766}; 3767 3768class HNeg : public HUnaryOperation { 3769 public: 3770 HNeg(Primitive::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc) 3771 : HUnaryOperation(result_type, input, dex_pc) {} 3772 3773 template <typename T> T Compute(T x) const { return -x; } 3774 3775 HConstant* Evaluate(HIntConstant* x) const OVERRIDE { 3776 return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc()); 3777 } 3778 HConstant* Evaluate(HLongConstant* x) const OVERRIDE { 3779 return GetBlock()->GetGraph()->GetLongConstant(Compute(x->GetValue()), GetDexPc()); 3780 } 3781 3782 DECLARE_INSTRUCTION(Neg); 3783 3784 private: 3785 DISALLOW_COPY_AND_ASSIGN(HNeg); 3786}; 3787 3788class HNewArray : public HExpression<2> { 3789 public: 3790 HNewArray(HInstruction* length, 3791 HCurrentMethod* current_method, 3792 uint32_t dex_pc, 3793 uint16_t type_index, 3794 const DexFile& dex_file, 3795 QuickEntrypointEnum entrypoint) 3796 : HExpression(Primitive::kPrimNot, SideEffects::CanTriggerGC(), dex_pc), 3797 type_index_(type_index), 3798 dex_file_(dex_file), 3799 entrypoint_(entrypoint) { 3800 SetRawInputAt(0, length); 3801 SetRawInputAt(1, current_method); 3802 } 3803 3804 uint16_t GetTypeIndex() const { return type_index_; } 3805 const DexFile& GetDexFile() const { return dex_file_; } 3806 3807 // Calls runtime so needs an environment. 3808 bool NeedsEnvironment() const OVERRIDE { return true; } 3809 3810 // May throw NegativeArraySizeException, OutOfMemoryError, etc. 3811 bool CanThrow() const OVERRIDE { return true; } 3812 3813 bool CanBeNull() const OVERRIDE { return false; } 3814 3815 QuickEntrypointEnum GetEntrypoint() const { return entrypoint_; } 3816 3817 DECLARE_INSTRUCTION(NewArray); 3818 3819 private: 3820 const uint16_t type_index_; 3821 const DexFile& dex_file_; 3822 const QuickEntrypointEnum entrypoint_; 3823 3824 DISALLOW_COPY_AND_ASSIGN(HNewArray); 3825}; 3826 3827class HAdd : public HBinaryOperation { 3828 public: 3829 HAdd(Primitive::Type result_type, 3830 HInstruction* left, 3831 HInstruction* right, 3832 uint32_t dex_pc = kNoDexPc) 3833 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 3834 3835 bool IsCommutative() const OVERRIDE { return true; } 3836 3837 template <typename T> T Compute(T x, T y) const { return x + y; } 3838 3839 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3840 return GetBlock()->GetGraph()->GetIntConstant( 3841 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3842 } 3843 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3844 return GetBlock()->GetGraph()->GetLongConstant( 3845 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3846 } 3847 3848 DECLARE_INSTRUCTION(Add); 3849 3850 private: 3851 DISALLOW_COPY_AND_ASSIGN(HAdd); 3852}; 3853 3854class HSub : public HBinaryOperation { 3855 public: 3856 HSub(Primitive::Type result_type, 3857 HInstruction* left, 3858 HInstruction* right, 3859 uint32_t dex_pc = kNoDexPc) 3860 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 3861 3862 template <typename T> T Compute(T x, T y) const { return x - y; } 3863 3864 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3865 return GetBlock()->GetGraph()->GetIntConstant( 3866 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3867 } 3868 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3869 return GetBlock()->GetGraph()->GetLongConstant( 3870 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3871 } 3872 3873 DECLARE_INSTRUCTION(Sub); 3874 3875 private: 3876 DISALLOW_COPY_AND_ASSIGN(HSub); 3877}; 3878 3879class HMul : public HBinaryOperation { 3880 public: 3881 HMul(Primitive::Type result_type, 3882 HInstruction* left, 3883 HInstruction* right, 3884 uint32_t dex_pc = kNoDexPc) 3885 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 3886 3887 bool IsCommutative() const OVERRIDE { return true; } 3888 3889 template <typename T> T Compute(T x, T y) const { return x * y; } 3890 3891 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3892 return GetBlock()->GetGraph()->GetIntConstant( 3893 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3894 } 3895 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3896 return GetBlock()->GetGraph()->GetLongConstant( 3897 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3898 } 3899 3900 DECLARE_INSTRUCTION(Mul); 3901 3902 private: 3903 DISALLOW_COPY_AND_ASSIGN(HMul); 3904}; 3905 3906class HDiv : public HBinaryOperation { 3907 public: 3908 HDiv(Primitive::Type result_type, 3909 HInstruction* left, 3910 HInstruction* right, 3911 uint32_t dex_pc) 3912 : HBinaryOperation(result_type, left, right, SideEffectsForArchRuntimeCalls(), dex_pc) {} 3913 3914 template <typename T> 3915 T Compute(T x, T y) const { 3916 // Our graph structure ensures we never have 0 for `y` during 3917 // constant folding. 3918 DCHECK_NE(y, 0); 3919 // Special case -1 to avoid getting a SIGFPE on x86(_64). 3920 return (y == -1) ? -x : x / y; 3921 } 3922 3923 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3924 return GetBlock()->GetGraph()->GetIntConstant( 3925 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3926 } 3927 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3928 return GetBlock()->GetGraph()->GetLongConstant( 3929 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3930 } 3931 3932 static SideEffects SideEffectsForArchRuntimeCalls() { 3933 // The generated code can use a runtime call. 3934 return SideEffects::CanTriggerGC(); 3935 } 3936 3937 DECLARE_INSTRUCTION(Div); 3938 3939 private: 3940 DISALLOW_COPY_AND_ASSIGN(HDiv); 3941}; 3942 3943class HRem : public HBinaryOperation { 3944 public: 3945 HRem(Primitive::Type result_type, 3946 HInstruction* left, 3947 HInstruction* right, 3948 uint32_t dex_pc) 3949 : HBinaryOperation(result_type, left, right, SideEffectsForArchRuntimeCalls(), dex_pc) {} 3950 3951 template <typename T> 3952 T Compute(T x, T y) const { 3953 // Our graph structure ensures we never have 0 for `y` during 3954 // constant folding. 3955 DCHECK_NE(y, 0); 3956 // Special case -1 to avoid getting a SIGFPE on x86(_64). 3957 return (y == -1) ? 0 : x % y; 3958 } 3959 3960 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 3961 return GetBlock()->GetGraph()->GetIntConstant( 3962 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3963 } 3964 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 3965 return GetBlock()->GetGraph()->GetLongConstant( 3966 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 3967 } 3968 3969 3970 static SideEffects SideEffectsForArchRuntimeCalls() { 3971 return SideEffects::CanTriggerGC(); 3972 } 3973 3974 DECLARE_INSTRUCTION(Rem); 3975 3976 private: 3977 DISALLOW_COPY_AND_ASSIGN(HRem); 3978}; 3979 3980class HDivZeroCheck : public HExpression<1> { 3981 public: 3982 HDivZeroCheck(HInstruction* value, uint32_t dex_pc) 3983 : HExpression(value->GetType(), SideEffects::None(), dex_pc) { 3984 SetRawInputAt(0, value); 3985 } 3986 3987 Primitive::Type GetType() const OVERRIDE { return InputAt(0)->GetType(); } 3988 3989 bool CanBeMoved() const OVERRIDE { return true; } 3990 3991 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 3992 return true; 3993 } 3994 3995 bool NeedsEnvironment() const OVERRIDE { return true; } 3996 bool CanThrow() const OVERRIDE { return true; } 3997 3998 DECLARE_INSTRUCTION(DivZeroCheck); 3999 4000 private: 4001 DISALLOW_COPY_AND_ASSIGN(HDivZeroCheck); 4002}; 4003 4004class HShl : public HBinaryOperation { 4005 public: 4006 HShl(Primitive::Type result_type, 4007 HInstruction* left, 4008 HInstruction* right, 4009 uint32_t dex_pc = kNoDexPc) 4010 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 4011 4012 template <typename T, typename U, typename V> 4013 T Compute(T x, U y, V max_shift_value) const { 4014 static_assert(std::is_same<V, typename std::make_unsigned<T>::type>::value, 4015 "V is not the unsigned integer type corresponding to T"); 4016 return x << (y & max_shift_value); 4017 } 4018 4019 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4020 return GetBlock()->GetGraph()->GetIntConstant( 4021 Compute(x->GetValue(), y->GetValue(), kMaxIntShiftValue), GetDexPc()); 4022 } 4023 // There is no `Evaluate(HIntConstant* x, HLongConstant* y)`, as this 4024 // case is handled as `x << static_cast<int>(y)`. 4025 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4026 return GetBlock()->GetGraph()->GetLongConstant( 4027 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4028 } 4029 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4030 return GetBlock()->GetGraph()->GetLongConstant( 4031 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4032 } 4033 4034 DECLARE_INSTRUCTION(Shl); 4035 4036 private: 4037 DISALLOW_COPY_AND_ASSIGN(HShl); 4038}; 4039 4040class HShr : public HBinaryOperation { 4041 public: 4042 HShr(Primitive::Type result_type, 4043 HInstruction* left, 4044 HInstruction* right, 4045 uint32_t dex_pc = kNoDexPc) 4046 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 4047 4048 template <typename T, typename U, typename V> 4049 T Compute(T x, U y, V max_shift_value) const { 4050 static_assert(std::is_same<V, typename std::make_unsigned<T>::type>::value, 4051 "V is not the unsigned integer type corresponding to T"); 4052 return x >> (y & max_shift_value); 4053 } 4054 4055 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4056 return GetBlock()->GetGraph()->GetIntConstant( 4057 Compute(x->GetValue(), y->GetValue(), kMaxIntShiftValue), GetDexPc()); 4058 } 4059 // There is no `Evaluate(HIntConstant* x, HLongConstant* y)`, as this 4060 // case is handled as `x >> static_cast<int>(y)`. 4061 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4062 return GetBlock()->GetGraph()->GetLongConstant( 4063 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4064 } 4065 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4066 return GetBlock()->GetGraph()->GetLongConstant( 4067 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4068 } 4069 4070 DECLARE_INSTRUCTION(Shr); 4071 4072 private: 4073 DISALLOW_COPY_AND_ASSIGN(HShr); 4074}; 4075 4076class HUShr : public HBinaryOperation { 4077 public: 4078 HUShr(Primitive::Type result_type, 4079 HInstruction* left, 4080 HInstruction* right, 4081 uint32_t dex_pc = kNoDexPc) 4082 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 4083 4084 template <typename T, typename U, typename V> 4085 T Compute(T x, U y, V max_shift_value) const { 4086 static_assert(std::is_same<V, typename std::make_unsigned<T>::type>::value, 4087 "V is not the unsigned integer type corresponding to T"); 4088 V ux = static_cast<V>(x); 4089 return static_cast<T>(ux >> (y & max_shift_value)); 4090 } 4091 4092 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4093 return GetBlock()->GetGraph()->GetIntConstant( 4094 Compute(x->GetValue(), y->GetValue(), kMaxIntShiftValue), GetDexPc()); 4095 } 4096 // There is no `Evaluate(HIntConstant* x, HLongConstant* y)`, as this 4097 // case is handled as `x >>> static_cast<int>(y)`. 4098 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4099 return GetBlock()->GetGraph()->GetLongConstant( 4100 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4101 } 4102 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4103 return GetBlock()->GetGraph()->GetLongConstant( 4104 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4105 } 4106 4107 DECLARE_INSTRUCTION(UShr); 4108 4109 private: 4110 DISALLOW_COPY_AND_ASSIGN(HUShr); 4111}; 4112 4113class HAnd : public HBinaryOperation { 4114 public: 4115 HAnd(Primitive::Type result_type, 4116 HInstruction* left, 4117 HInstruction* right, 4118 uint32_t dex_pc = kNoDexPc) 4119 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 4120 4121 bool IsCommutative() const OVERRIDE { return true; } 4122 4123 template <typename T, typename U> 4124 auto Compute(T x, U y) const -> decltype(x & y) { return x & y; } 4125 4126 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4127 return GetBlock()->GetGraph()->GetIntConstant( 4128 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4129 } 4130 HConstant* Evaluate(HIntConstant* x, HLongConstant* y) const OVERRIDE { 4131 return GetBlock()->GetGraph()->GetLongConstant( 4132 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4133 } 4134 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4135 return GetBlock()->GetGraph()->GetLongConstant( 4136 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4137 } 4138 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4139 return GetBlock()->GetGraph()->GetLongConstant( 4140 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4141 } 4142 4143 DECLARE_INSTRUCTION(And); 4144 4145 private: 4146 DISALLOW_COPY_AND_ASSIGN(HAnd); 4147}; 4148 4149class HOr : public HBinaryOperation { 4150 public: 4151 HOr(Primitive::Type result_type, 4152 HInstruction* left, 4153 HInstruction* right, 4154 uint32_t dex_pc = kNoDexPc) 4155 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 4156 4157 bool IsCommutative() const OVERRIDE { return true; } 4158 4159 template <typename T, typename U> 4160 auto Compute(T x, U y) const -> decltype(x | y) { return x | y; } 4161 4162 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4163 return GetBlock()->GetGraph()->GetIntConstant( 4164 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4165 } 4166 HConstant* Evaluate(HIntConstant* x, HLongConstant* y) const OVERRIDE { 4167 return GetBlock()->GetGraph()->GetLongConstant( 4168 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4169 } 4170 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4171 return GetBlock()->GetGraph()->GetLongConstant( 4172 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4173 } 4174 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4175 return GetBlock()->GetGraph()->GetLongConstant( 4176 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4177 } 4178 4179 DECLARE_INSTRUCTION(Or); 4180 4181 private: 4182 DISALLOW_COPY_AND_ASSIGN(HOr); 4183}; 4184 4185class HXor : public HBinaryOperation { 4186 public: 4187 HXor(Primitive::Type result_type, 4188 HInstruction* left, 4189 HInstruction* right, 4190 uint32_t dex_pc = kNoDexPc) 4191 : HBinaryOperation(result_type, left, right, SideEffects::None(), dex_pc) {} 4192 4193 bool IsCommutative() const OVERRIDE { return true; } 4194 4195 template <typename T, typename U> 4196 auto Compute(T x, U y) const -> decltype(x ^ y) { return x ^ y; } 4197 4198 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4199 return GetBlock()->GetGraph()->GetIntConstant( 4200 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4201 } 4202 HConstant* Evaluate(HIntConstant* x, HLongConstant* y) const OVERRIDE { 4203 return GetBlock()->GetGraph()->GetLongConstant( 4204 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4205 } 4206 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4207 return GetBlock()->GetGraph()->GetLongConstant( 4208 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4209 } 4210 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4211 return GetBlock()->GetGraph()->GetLongConstant( 4212 Compute(x->GetValue(), y->GetValue()), GetDexPc()); 4213 } 4214 4215 DECLARE_INSTRUCTION(Xor); 4216 4217 private: 4218 DISALLOW_COPY_AND_ASSIGN(HXor); 4219}; 4220 4221class HRor : public HBinaryOperation { 4222 public: 4223 HRor(Primitive::Type result_type, HInstruction* value, HInstruction* distance) 4224 : HBinaryOperation(result_type, value, distance) {} 4225 4226 template <typename T, typename U, typename V> 4227 T Compute(T x, U y, V max_shift_value) const { 4228 static_assert(std::is_same<V, typename std::make_unsigned<T>::type>::value, 4229 "V is not the unsigned integer type corresponding to T"); 4230 V ux = static_cast<V>(x); 4231 if ((y & max_shift_value) == 0) { 4232 return static_cast<T>(ux); 4233 } else { 4234 const V reg_bits = sizeof(T) * 8; 4235 return static_cast<T>(ux >> (y & max_shift_value)) | 4236 (x << (reg_bits - (y & max_shift_value))); 4237 } 4238 } 4239 4240 HConstant* Evaluate(HIntConstant* x, HIntConstant* y) const OVERRIDE { 4241 return GetBlock()->GetGraph()->GetIntConstant( 4242 Compute(x->GetValue(), y->GetValue(), kMaxIntShiftValue), GetDexPc()); 4243 } 4244 HConstant* Evaluate(HLongConstant* x, HIntConstant* y) const OVERRIDE { 4245 return GetBlock()->GetGraph()->GetLongConstant( 4246 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4247 } 4248 HConstant* Evaluate(HLongConstant* x, HLongConstant* y) const OVERRIDE { 4249 return GetBlock()->GetGraph()->GetLongConstant( 4250 Compute(x->GetValue(), y->GetValue(), kMaxLongShiftValue), GetDexPc()); 4251 } 4252 4253 DECLARE_INSTRUCTION(Ror); 4254 4255 private: 4256 DISALLOW_COPY_AND_ASSIGN(HRor); 4257}; 4258 4259// The value of a parameter in this method. Its location depends on 4260// the calling convention. 4261class HParameterValue : public HExpression<0> { 4262 public: 4263 HParameterValue(const DexFile& dex_file, 4264 uint16_t type_index, 4265 uint8_t index, 4266 Primitive::Type parameter_type, 4267 bool is_this = false) 4268 : HExpression(parameter_type, SideEffects::None(), kNoDexPc), 4269 dex_file_(dex_file), 4270 type_index_(type_index), 4271 index_(index), 4272 is_this_(is_this), 4273 can_be_null_(!is_this) {} 4274 4275 const DexFile& GetDexFile() const { return dex_file_; } 4276 uint16_t GetTypeIndex() const { return type_index_; } 4277 uint8_t GetIndex() const { return index_; } 4278 bool IsThis() const { return is_this_; } 4279 4280 bool CanBeNull() const OVERRIDE { return can_be_null_; } 4281 void SetCanBeNull(bool can_be_null) { can_be_null_ = can_be_null; } 4282 4283 DECLARE_INSTRUCTION(ParameterValue); 4284 4285 private: 4286 const DexFile& dex_file_; 4287 const uint16_t type_index_; 4288 // The index of this parameter in the parameters list. Must be less 4289 // than HGraph::number_of_in_vregs_. 4290 const uint8_t index_; 4291 4292 // Whether or not the parameter value corresponds to 'this' argument. 4293 const bool is_this_; 4294 4295 bool can_be_null_; 4296 4297 DISALLOW_COPY_AND_ASSIGN(HParameterValue); 4298}; 4299 4300class HNot : public HUnaryOperation { 4301 public: 4302 HNot(Primitive::Type result_type, HInstruction* input, uint32_t dex_pc = kNoDexPc) 4303 : HUnaryOperation(result_type, input, dex_pc) {} 4304 4305 bool CanBeMoved() const OVERRIDE { return true; } 4306 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 4307 return true; 4308 } 4309 4310 template <typename T> T Compute(T x) const { return ~x; } 4311 4312 HConstant* Evaluate(HIntConstant* x) const OVERRIDE { 4313 return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc()); 4314 } 4315 HConstant* Evaluate(HLongConstant* x) const OVERRIDE { 4316 return GetBlock()->GetGraph()->GetLongConstant(Compute(x->GetValue()), GetDexPc()); 4317 } 4318 4319 DECLARE_INSTRUCTION(Not); 4320 4321 private: 4322 DISALLOW_COPY_AND_ASSIGN(HNot); 4323}; 4324 4325class HBooleanNot : public HUnaryOperation { 4326 public: 4327 explicit HBooleanNot(HInstruction* input, uint32_t dex_pc = kNoDexPc) 4328 : HUnaryOperation(Primitive::Type::kPrimBoolean, input, dex_pc) {} 4329 4330 bool CanBeMoved() const OVERRIDE { return true; } 4331 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 4332 return true; 4333 } 4334 4335 template <typename T> bool Compute(T x) const { 4336 DCHECK(IsUint<1>(x)); 4337 return !x; 4338 } 4339 4340 HConstant* Evaluate(HIntConstant* x) const OVERRIDE { 4341 return GetBlock()->GetGraph()->GetIntConstant(Compute(x->GetValue()), GetDexPc()); 4342 } 4343 HConstant* Evaluate(HLongConstant* x ATTRIBUTE_UNUSED) const OVERRIDE { 4344 LOG(FATAL) << DebugName() << " is not defined for long values"; 4345 UNREACHABLE(); 4346 } 4347 4348 DECLARE_INSTRUCTION(BooleanNot); 4349 4350 private: 4351 DISALLOW_COPY_AND_ASSIGN(HBooleanNot); 4352}; 4353 4354class HTypeConversion : public HExpression<1> { 4355 public: 4356 // Instantiate a type conversion of `input` to `result_type`. 4357 HTypeConversion(Primitive::Type result_type, HInstruction* input, uint32_t dex_pc) 4358 : HExpression(result_type, 4359 SideEffectsForArchRuntimeCalls(input->GetType(), result_type), 4360 dex_pc) { 4361 SetRawInputAt(0, input); 4362 DCHECK_NE(input->GetType(), result_type); 4363 } 4364 4365 HInstruction* GetInput() const { return InputAt(0); } 4366 Primitive::Type GetInputType() const { return GetInput()->GetType(); } 4367 Primitive::Type GetResultType() const { return GetType(); } 4368 4369 // Required by the x86, ARM, MIPS and MIPS64 code generators when producing calls 4370 // to the runtime. 4371 4372 bool CanBeMoved() const OVERRIDE { return true; } 4373 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { return true; } 4374 4375 // Try to statically evaluate the conversion and return a HConstant 4376 // containing the result. If the input cannot be converted, return nullptr. 4377 HConstant* TryStaticEvaluation() const; 4378 4379 static SideEffects SideEffectsForArchRuntimeCalls(Primitive::Type input_type, 4380 Primitive::Type result_type) { 4381 // Some architectures may not require the 'GC' side effects, but at this point 4382 // in the compilation process we do not know what architecture we will 4383 // generate code for, so we must be conservative. 4384 if ((Primitive::IsFloatingPointType(input_type) && Primitive::IsIntegralType(result_type)) 4385 || (input_type == Primitive::kPrimLong && Primitive::IsFloatingPointType(result_type))) { 4386 return SideEffects::CanTriggerGC(); 4387 } 4388 return SideEffects::None(); 4389 } 4390 4391 DECLARE_INSTRUCTION(TypeConversion); 4392 4393 private: 4394 DISALLOW_COPY_AND_ASSIGN(HTypeConversion); 4395}; 4396 4397static constexpr uint32_t kNoRegNumber = -1; 4398 4399class HPhi : public HInstruction { 4400 public: 4401 HPhi(ArenaAllocator* arena, 4402 uint32_t reg_number, 4403 size_t number_of_inputs, 4404 Primitive::Type type, 4405 uint32_t dex_pc = kNoDexPc) 4406 : HInstruction(SideEffects::None(), dex_pc), 4407 inputs_(number_of_inputs, arena->Adapter(kArenaAllocPhiInputs)), 4408 reg_number_(reg_number), 4409 type_(ToPhiType(type)), 4410 // Phis are constructed live and marked dead if conflicting or unused. 4411 // Individual steps of SsaBuilder should assume that if a phi has been 4412 // marked dead, it can be ignored and will be removed by SsaPhiElimination. 4413 is_live_(true), 4414 can_be_null_(true) { 4415 DCHECK_NE(type_, Primitive::kPrimVoid); 4416 } 4417 4418 // Returns a type equivalent to the given `type`, but that a `HPhi` can hold. 4419 static Primitive::Type ToPhiType(Primitive::Type type) { 4420 switch (type) { 4421 case Primitive::kPrimBoolean: 4422 case Primitive::kPrimByte: 4423 case Primitive::kPrimShort: 4424 case Primitive::kPrimChar: 4425 return Primitive::kPrimInt; 4426 default: 4427 return type; 4428 } 4429 } 4430 4431 bool IsCatchPhi() const { return GetBlock()->IsCatchBlock(); } 4432 4433 size_t InputCount() const OVERRIDE { return inputs_.size(); } 4434 4435 void AddInput(HInstruction* input); 4436 void RemoveInputAt(size_t index); 4437 4438 Primitive::Type GetType() const OVERRIDE { return type_; } 4439 void SetType(Primitive::Type type) { type_ = type; } 4440 4441 bool CanBeNull() const OVERRIDE { return can_be_null_; } 4442 void SetCanBeNull(bool can_be_null) { can_be_null_ = can_be_null; } 4443 4444 uint32_t GetRegNumber() const { return reg_number_; } 4445 4446 void SetDead() { is_live_ = false; } 4447 void SetLive() { is_live_ = true; } 4448 bool IsDead() const { return !is_live_; } 4449 bool IsLive() const { return is_live_; } 4450 4451 bool IsVRegEquivalentOf(HInstruction* other) const { 4452 return other != nullptr 4453 && other->IsPhi() 4454 && other->AsPhi()->GetBlock() == GetBlock() 4455 && other->AsPhi()->GetRegNumber() == GetRegNumber(); 4456 } 4457 4458 // Returns the next equivalent phi (starting from the current one) or null if there is none. 4459 // An equivalent phi is a phi having the same dex register and type. 4460 // It assumes that phis with the same dex register are adjacent. 4461 HPhi* GetNextEquivalentPhiWithSameType() { 4462 HInstruction* next = GetNext(); 4463 while (next != nullptr && next->AsPhi()->GetRegNumber() == reg_number_) { 4464 if (next->GetType() == GetType()) { 4465 return next->AsPhi(); 4466 } 4467 next = next->GetNext(); 4468 } 4469 return nullptr; 4470 } 4471 4472 DECLARE_INSTRUCTION(Phi); 4473 4474 protected: 4475 const HUserRecord<HInstruction*> InputRecordAt(size_t index) const OVERRIDE { 4476 return inputs_[index]; 4477 } 4478 4479 void SetRawInputRecordAt(size_t index, const HUserRecord<HInstruction*>& input) OVERRIDE { 4480 inputs_[index] = input; 4481 } 4482 4483 private: 4484 ArenaVector<HUserRecord<HInstruction*> > inputs_; 4485 const uint32_t reg_number_; 4486 Primitive::Type type_; 4487 bool is_live_; 4488 bool can_be_null_; 4489 4490 DISALLOW_COPY_AND_ASSIGN(HPhi); 4491}; 4492 4493class HNullCheck : public HExpression<1> { 4494 public: 4495 HNullCheck(HInstruction* value, uint32_t dex_pc) 4496 : HExpression(value->GetType(), SideEffects::None(), dex_pc) { 4497 SetRawInputAt(0, value); 4498 } 4499 4500 bool CanBeMoved() const OVERRIDE { return true; } 4501 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 4502 return true; 4503 } 4504 4505 bool NeedsEnvironment() const OVERRIDE { return true; } 4506 4507 bool CanThrow() const OVERRIDE { return true; } 4508 4509 bool CanBeNull() const OVERRIDE { return false; } 4510 4511 4512 DECLARE_INSTRUCTION(NullCheck); 4513 4514 private: 4515 DISALLOW_COPY_AND_ASSIGN(HNullCheck); 4516}; 4517 4518class FieldInfo : public ValueObject { 4519 public: 4520 FieldInfo(MemberOffset field_offset, 4521 Primitive::Type field_type, 4522 bool is_volatile, 4523 uint32_t index, 4524 uint16_t declaring_class_def_index, 4525 const DexFile& dex_file, 4526 Handle<mirror::DexCache> dex_cache) 4527 : field_offset_(field_offset), 4528 field_type_(field_type), 4529 is_volatile_(is_volatile), 4530 index_(index), 4531 declaring_class_def_index_(declaring_class_def_index), 4532 dex_file_(dex_file), 4533 dex_cache_(dex_cache) {} 4534 4535 MemberOffset GetFieldOffset() const { return field_offset_; } 4536 Primitive::Type GetFieldType() const { return field_type_; } 4537 uint32_t GetFieldIndex() const { return index_; } 4538 uint16_t GetDeclaringClassDefIndex() const { return declaring_class_def_index_;} 4539 const DexFile& GetDexFile() const { return dex_file_; } 4540 bool IsVolatile() const { return is_volatile_; } 4541 Handle<mirror::DexCache> GetDexCache() const { return dex_cache_; } 4542 4543 private: 4544 const MemberOffset field_offset_; 4545 const Primitive::Type field_type_; 4546 const bool is_volatile_; 4547 const uint32_t index_; 4548 const uint16_t declaring_class_def_index_; 4549 const DexFile& dex_file_; 4550 const Handle<mirror::DexCache> dex_cache_; 4551}; 4552 4553class HInstanceFieldGet : public HExpression<1> { 4554 public: 4555 HInstanceFieldGet(HInstruction* value, 4556 Primitive::Type field_type, 4557 MemberOffset field_offset, 4558 bool is_volatile, 4559 uint32_t field_idx, 4560 uint16_t declaring_class_def_index, 4561 const DexFile& dex_file, 4562 Handle<mirror::DexCache> dex_cache, 4563 uint32_t dex_pc) 4564 : HExpression(field_type, 4565 SideEffects::FieldReadOfType(field_type, is_volatile), 4566 dex_pc), 4567 field_info_(field_offset, 4568 field_type, 4569 is_volatile, 4570 field_idx, 4571 declaring_class_def_index, 4572 dex_file, 4573 dex_cache) { 4574 SetRawInputAt(0, value); 4575 } 4576 4577 bool CanBeMoved() const OVERRIDE { return !IsVolatile(); } 4578 4579 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 4580 HInstanceFieldGet* other_get = other->AsInstanceFieldGet(); 4581 return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue(); 4582 } 4583 4584 bool CanDoImplicitNullCheckOn(HInstruction* obj) const OVERRIDE { 4585 return (obj == InputAt(0)) && GetFieldOffset().Uint32Value() < kPageSize; 4586 } 4587 4588 size_t ComputeHashCode() const OVERRIDE { 4589 return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue(); 4590 } 4591 4592 const FieldInfo& GetFieldInfo() const { return field_info_; } 4593 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); } 4594 Primitive::Type GetFieldType() const { return field_info_.GetFieldType(); } 4595 bool IsVolatile() const { return field_info_.IsVolatile(); } 4596 4597 DECLARE_INSTRUCTION(InstanceFieldGet); 4598 4599 private: 4600 const FieldInfo field_info_; 4601 4602 DISALLOW_COPY_AND_ASSIGN(HInstanceFieldGet); 4603}; 4604 4605class HInstanceFieldSet : public HTemplateInstruction<2> { 4606 public: 4607 HInstanceFieldSet(HInstruction* object, 4608 HInstruction* value, 4609 Primitive::Type field_type, 4610 MemberOffset field_offset, 4611 bool is_volatile, 4612 uint32_t field_idx, 4613 uint16_t declaring_class_def_index, 4614 const DexFile& dex_file, 4615 Handle<mirror::DexCache> dex_cache, 4616 uint32_t dex_pc) 4617 : HTemplateInstruction(SideEffects::FieldWriteOfType(field_type, is_volatile), 4618 dex_pc), 4619 field_info_(field_offset, 4620 field_type, 4621 is_volatile, 4622 field_idx, 4623 declaring_class_def_index, 4624 dex_file, 4625 dex_cache), 4626 value_can_be_null_(true) { 4627 SetRawInputAt(0, object); 4628 SetRawInputAt(1, value); 4629 } 4630 4631 bool CanDoImplicitNullCheckOn(HInstruction* obj) const OVERRIDE { 4632 return (obj == InputAt(0)) && GetFieldOffset().Uint32Value() < kPageSize; 4633 } 4634 4635 const FieldInfo& GetFieldInfo() const { return field_info_; } 4636 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); } 4637 Primitive::Type GetFieldType() const { return field_info_.GetFieldType(); } 4638 bool IsVolatile() const { return field_info_.IsVolatile(); } 4639 HInstruction* GetValue() const { return InputAt(1); } 4640 bool GetValueCanBeNull() const { return value_can_be_null_; } 4641 void ClearValueCanBeNull() { value_can_be_null_ = false; } 4642 4643 DECLARE_INSTRUCTION(InstanceFieldSet); 4644 4645 private: 4646 const FieldInfo field_info_; 4647 bool value_can_be_null_; 4648 4649 DISALLOW_COPY_AND_ASSIGN(HInstanceFieldSet); 4650}; 4651 4652class HArrayGet : public HExpression<2> { 4653 public: 4654 HArrayGet(HInstruction* array, 4655 HInstruction* index, 4656 Primitive::Type type, 4657 uint32_t dex_pc, 4658 SideEffects additional_side_effects = SideEffects::None()) 4659 : HExpression(type, 4660 SideEffects::ArrayReadOfType(type).Union(additional_side_effects), 4661 dex_pc) { 4662 SetRawInputAt(0, array); 4663 SetRawInputAt(1, index); 4664 } 4665 4666 bool CanBeMoved() const OVERRIDE { return true; } 4667 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 4668 return true; 4669 } 4670 bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const OVERRIDE { 4671 // TODO: We can be smarter here. 4672 // Currently, the array access is always preceded by an ArrayLength or a NullCheck 4673 // which generates the implicit null check. There are cases when these can be removed 4674 // to produce better code. If we ever add optimizations to do so we should allow an 4675 // implicit check here (as long as the address falls in the first page). 4676 return false; 4677 } 4678 4679 void SetType(Primitive::Type type) { type_ = type; } 4680 4681 HInstruction* GetArray() const { return InputAt(0); } 4682 HInstruction* GetIndex() const { return InputAt(1); } 4683 4684 DECLARE_INSTRUCTION(ArrayGet); 4685 4686 private: 4687 DISALLOW_COPY_AND_ASSIGN(HArrayGet); 4688}; 4689 4690class HArraySet : public HTemplateInstruction<3> { 4691 public: 4692 HArraySet(HInstruction* array, 4693 HInstruction* index, 4694 HInstruction* value, 4695 Primitive::Type expected_component_type, 4696 uint32_t dex_pc, 4697 SideEffects additional_side_effects = SideEffects::None()) 4698 : HTemplateInstruction( 4699 SideEffects::ArrayWriteOfType(expected_component_type).Union( 4700 SideEffectsForArchRuntimeCalls(value->GetType())).Union( 4701 additional_side_effects), 4702 dex_pc), 4703 expected_component_type_(expected_component_type), 4704 needs_type_check_(value->GetType() == Primitive::kPrimNot), 4705 value_can_be_null_(true), 4706 static_type_of_array_is_object_array_(false) { 4707 SetRawInputAt(0, array); 4708 SetRawInputAt(1, index); 4709 SetRawInputAt(2, value); 4710 } 4711 4712 bool NeedsEnvironment() const OVERRIDE { 4713 // We currently always call a runtime method to catch array store 4714 // exceptions. 4715 return needs_type_check_; 4716 } 4717 4718 // Can throw ArrayStoreException. 4719 bool CanThrow() const OVERRIDE { return needs_type_check_; } 4720 4721 bool CanDoImplicitNullCheckOn(HInstruction* obj ATTRIBUTE_UNUSED) const OVERRIDE { 4722 // TODO: Same as for ArrayGet. 4723 return false; 4724 } 4725 4726 void ClearNeedsTypeCheck() { 4727 needs_type_check_ = false; 4728 } 4729 4730 void ClearValueCanBeNull() { 4731 value_can_be_null_ = false; 4732 } 4733 4734 void SetStaticTypeOfArrayIsObjectArray() { 4735 static_type_of_array_is_object_array_ = true; 4736 } 4737 4738 bool GetValueCanBeNull() const { return value_can_be_null_; } 4739 bool NeedsTypeCheck() const { return needs_type_check_; } 4740 bool StaticTypeOfArrayIsObjectArray() const { return static_type_of_array_is_object_array_; } 4741 4742 HInstruction* GetArray() const { return InputAt(0); } 4743 HInstruction* GetIndex() const { return InputAt(1); } 4744 HInstruction* GetValue() const { return InputAt(2); } 4745 4746 Primitive::Type GetComponentType() const { 4747 // The Dex format does not type floating point index operations. Since the 4748 // `expected_component_type_` is set during building and can therefore not 4749 // be correct, we also check what is the value type. If it is a floating 4750 // point type, we must use that type. 4751 Primitive::Type value_type = GetValue()->GetType(); 4752 return ((value_type == Primitive::kPrimFloat) || (value_type == Primitive::kPrimDouble)) 4753 ? value_type 4754 : expected_component_type_; 4755 } 4756 4757 Primitive::Type GetRawExpectedComponentType() const { 4758 return expected_component_type_; 4759 } 4760 4761 static SideEffects SideEffectsForArchRuntimeCalls(Primitive::Type value_type) { 4762 return (value_type == Primitive::kPrimNot) ? SideEffects::CanTriggerGC() : SideEffects::None(); 4763 } 4764 4765 DECLARE_INSTRUCTION(ArraySet); 4766 4767 private: 4768 const Primitive::Type expected_component_type_; 4769 bool needs_type_check_; 4770 bool value_can_be_null_; 4771 // Cached information for the reference_type_info_ so that codegen 4772 // does not need to inspect the static type. 4773 bool static_type_of_array_is_object_array_; 4774 4775 DISALLOW_COPY_AND_ASSIGN(HArraySet); 4776}; 4777 4778class HArrayLength : public HExpression<1> { 4779 public: 4780 HArrayLength(HInstruction* array, uint32_t dex_pc) 4781 : HExpression(Primitive::kPrimInt, SideEffects::None(), dex_pc) { 4782 // Note that arrays do not change length, so the instruction does not 4783 // depend on any write. 4784 SetRawInputAt(0, array); 4785 } 4786 4787 bool CanBeMoved() const OVERRIDE { return true; } 4788 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 4789 return true; 4790 } 4791 bool CanDoImplicitNullCheckOn(HInstruction* obj) const OVERRIDE { 4792 return obj == InputAt(0); 4793 } 4794 4795 DECLARE_INSTRUCTION(ArrayLength); 4796 4797 private: 4798 DISALLOW_COPY_AND_ASSIGN(HArrayLength); 4799}; 4800 4801class HBoundsCheck : public HExpression<2> { 4802 public: 4803 HBoundsCheck(HInstruction* index, HInstruction* length, uint32_t dex_pc) 4804 : HExpression(index->GetType(), SideEffects::None(), dex_pc) { 4805 DCHECK(index->GetType() == Primitive::kPrimInt); 4806 SetRawInputAt(0, index); 4807 SetRawInputAt(1, length); 4808 } 4809 4810 bool CanBeMoved() const OVERRIDE { return true; } 4811 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 4812 return true; 4813 } 4814 4815 bool NeedsEnvironment() const OVERRIDE { return true; } 4816 4817 bool CanThrow() const OVERRIDE { return true; } 4818 4819 HInstruction* GetIndex() const { return InputAt(0); } 4820 4821 DECLARE_INSTRUCTION(BoundsCheck); 4822 4823 private: 4824 DISALLOW_COPY_AND_ASSIGN(HBoundsCheck); 4825}; 4826 4827/** 4828 * Some DEX instructions are folded into multiple HInstructions that need 4829 * to stay live until the last HInstruction. This class 4830 * is used as a marker for the baseline compiler to ensure its preceding 4831 * HInstruction stays live. `index` represents the stack location index of the 4832 * instruction (the actual offset is computed as index * vreg_size). 4833 */ 4834class HTemporary : public HTemplateInstruction<0> { 4835 public: 4836 explicit HTemporary(size_t index, uint32_t dex_pc = kNoDexPc) 4837 : HTemplateInstruction(SideEffects::None(), dex_pc), index_(index) {} 4838 4839 size_t GetIndex() const { return index_; } 4840 4841 Primitive::Type GetType() const OVERRIDE { 4842 // The previous instruction is the one that will be stored in the temporary location. 4843 DCHECK(GetPrevious() != nullptr); 4844 return GetPrevious()->GetType(); 4845 } 4846 4847 DECLARE_INSTRUCTION(Temporary); 4848 4849 private: 4850 const size_t index_; 4851 DISALLOW_COPY_AND_ASSIGN(HTemporary); 4852}; 4853 4854class HSuspendCheck : public HTemplateInstruction<0> { 4855 public: 4856 explicit HSuspendCheck(uint32_t dex_pc) 4857 : HTemplateInstruction(SideEffects::CanTriggerGC(), dex_pc), slow_path_(nullptr) {} 4858 4859 bool NeedsEnvironment() const OVERRIDE { 4860 return true; 4861 } 4862 4863 void SetSlowPath(SlowPathCode* slow_path) { slow_path_ = slow_path; } 4864 SlowPathCode* GetSlowPath() const { return slow_path_; } 4865 4866 DECLARE_INSTRUCTION(SuspendCheck); 4867 4868 private: 4869 // Only used for code generation, in order to share the same slow path between back edges 4870 // of a same loop. 4871 SlowPathCode* slow_path_; 4872 4873 DISALLOW_COPY_AND_ASSIGN(HSuspendCheck); 4874}; 4875 4876// Pseudo-instruction which provides the native debugger with mapping information. 4877// It ensures that we can generate line number and local variables at this point. 4878class HNativeDebugInfo : public HTemplateInstruction<0> { 4879 public: 4880 explicit HNativeDebugInfo(uint32_t dex_pc) 4881 : HTemplateInstruction<0>(SideEffects::None(), dex_pc) {} 4882 4883 bool NeedsEnvironment() const OVERRIDE { 4884 return true; 4885 } 4886 4887 DECLARE_INSTRUCTION(NativeDebugInfo); 4888 4889 private: 4890 DISALLOW_COPY_AND_ASSIGN(HNativeDebugInfo); 4891}; 4892 4893/** 4894 * Instruction to load a Class object. 4895 */ 4896class HLoadClass : public HExpression<1> { 4897 public: 4898 HLoadClass(HCurrentMethod* current_method, 4899 uint16_t type_index, 4900 const DexFile& dex_file, 4901 bool is_referrers_class, 4902 uint32_t dex_pc, 4903 bool needs_access_check, 4904 bool is_in_dex_cache) 4905 : HExpression(Primitive::kPrimNot, SideEffectsForArchRuntimeCalls(), dex_pc), 4906 type_index_(type_index), 4907 dex_file_(dex_file), 4908 is_referrers_class_(is_referrers_class), 4909 generate_clinit_check_(false), 4910 needs_access_check_(needs_access_check), 4911 is_in_dex_cache_(is_in_dex_cache), 4912 loaded_class_rti_(ReferenceTypeInfo::CreateInvalid()) { 4913 // Referrers class should not need access check. We never inline unverified 4914 // methods so we can't possibly end up in this situation. 4915 DCHECK(!is_referrers_class_ || !needs_access_check_); 4916 SetRawInputAt(0, current_method); 4917 } 4918 4919 bool CanBeMoved() const OVERRIDE { return true; } 4920 4921 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 4922 // Note that we don't need to test for generate_clinit_check_. 4923 // Whether or not we need to generate the clinit check is processed in 4924 // prepare_for_register_allocator based on existing HInvokes and HClinitChecks. 4925 return other->AsLoadClass()->type_index_ == type_index_ && 4926 other->AsLoadClass()->needs_access_check_ == needs_access_check_; 4927 } 4928 4929 size_t ComputeHashCode() const OVERRIDE { return type_index_; } 4930 4931 uint16_t GetTypeIndex() const { return type_index_; } 4932 bool IsReferrersClass() const { return is_referrers_class_; } 4933 bool CanBeNull() const OVERRIDE { return false; } 4934 4935 bool NeedsEnvironment() const OVERRIDE { 4936 return CanCallRuntime(); 4937 } 4938 4939 bool MustGenerateClinitCheck() const { 4940 return generate_clinit_check_; 4941 } 4942 4943 void SetMustGenerateClinitCheck(bool generate_clinit_check) { 4944 // The entrypoint the code generator is going to call does not do 4945 // clinit of the class. 4946 DCHECK(!NeedsAccessCheck()); 4947 generate_clinit_check_ = generate_clinit_check; 4948 } 4949 4950 bool CanCallRuntime() const { 4951 return MustGenerateClinitCheck() || 4952 (!is_referrers_class_ && !is_in_dex_cache_) || 4953 needs_access_check_; 4954 } 4955 4956 bool NeedsAccessCheck() const { 4957 return needs_access_check_; 4958 } 4959 4960 bool CanThrow() const OVERRIDE { 4961 return CanCallRuntime(); 4962 } 4963 4964 ReferenceTypeInfo GetLoadedClassRTI() { 4965 return loaded_class_rti_; 4966 } 4967 4968 void SetLoadedClassRTI(ReferenceTypeInfo rti) { 4969 // Make sure we only set exact types (the loaded class should never be merged). 4970 DCHECK(rti.IsExact()); 4971 loaded_class_rti_ = rti; 4972 } 4973 4974 const DexFile& GetDexFile() { return dex_file_; } 4975 4976 bool NeedsDexCacheOfDeclaringClass() const OVERRIDE { return !is_referrers_class_; } 4977 4978 static SideEffects SideEffectsForArchRuntimeCalls() { 4979 return SideEffects::CanTriggerGC(); 4980 } 4981 4982 bool IsInDexCache() const { return is_in_dex_cache_; } 4983 4984 DECLARE_INSTRUCTION(LoadClass); 4985 4986 private: 4987 const uint16_t type_index_; 4988 const DexFile& dex_file_; 4989 const bool is_referrers_class_; 4990 // Whether this instruction must generate the initialization check. 4991 // Used for code generation. 4992 bool generate_clinit_check_; 4993 const bool needs_access_check_; 4994 const bool is_in_dex_cache_; 4995 4996 ReferenceTypeInfo loaded_class_rti_; 4997 4998 DISALLOW_COPY_AND_ASSIGN(HLoadClass); 4999}; 5000 5001class HLoadString : public HExpression<1> { 5002 public: 5003 HLoadString(HCurrentMethod* current_method, 5004 uint32_t string_index, 5005 uint32_t dex_pc, 5006 bool is_in_dex_cache) 5007 : HExpression(Primitive::kPrimNot, SideEffectsForArchRuntimeCalls(), dex_pc), 5008 string_index_(string_index), 5009 is_in_dex_cache_(is_in_dex_cache) { 5010 SetRawInputAt(0, current_method); 5011 } 5012 5013 bool CanBeMoved() const OVERRIDE { return true; } 5014 5015 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 5016 return other->AsLoadString()->string_index_ == string_index_; 5017 } 5018 5019 size_t ComputeHashCode() const OVERRIDE { return string_index_; } 5020 5021 uint32_t GetStringIndex() const { return string_index_; } 5022 5023 // TODO: Can we deopt or debug when we resolve a string? 5024 bool NeedsEnvironment() const OVERRIDE { return false; } 5025 bool NeedsDexCacheOfDeclaringClass() const OVERRIDE { return true; } 5026 bool CanBeNull() const OVERRIDE { return false; } 5027 bool IsInDexCache() const { return is_in_dex_cache_; } 5028 5029 static SideEffects SideEffectsForArchRuntimeCalls() { 5030 return SideEffects::CanTriggerGC(); 5031 } 5032 5033 DECLARE_INSTRUCTION(LoadString); 5034 5035 private: 5036 const uint32_t string_index_; 5037 const bool is_in_dex_cache_; 5038 5039 DISALLOW_COPY_AND_ASSIGN(HLoadString); 5040}; 5041 5042/** 5043 * Performs an initialization check on its Class object input. 5044 */ 5045class HClinitCheck : public HExpression<1> { 5046 public: 5047 HClinitCheck(HLoadClass* constant, uint32_t dex_pc) 5048 : HExpression( 5049 Primitive::kPrimNot, 5050 SideEffects::AllChanges(), // Assume write/read on all fields/arrays. 5051 dex_pc) { 5052 SetRawInputAt(0, constant); 5053 } 5054 5055 bool CanBeMoved() const OVERRIDE { return true; } 5056 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 5057 return true; 5058 } 5059 5060 bool NeedsEnvironment() const OVERRIDE { 5061 // May call runtime to initialize the class. 5062 return true; 5063 } 5064 5065 bool CanThrow() const OVERRIDE { return true; } 5066 5067 HLoadClass* GetLoadClass() const { return InputAt(0)->AsLoadClass(); } 5068 5069 DECLARE_INSTRUCTION(ClinitCheck); 5070 5071 private: 5072 DISALLOW_COPY_AND_ASSIGN(HClinitCheck); 5073}; 5074 5075class HStaticFieldGet : public HExpression<1> { 5076 public: 5077 HStaticFieldGet(HInstruction* cls, 5078 Primitive::Type field_type, 5079 MemberOffset field_offset, 5080 bool is_volatile, 5081 uint32_t field_idx, 5082 uint16_t declaring_class_def_index, 5083 const DexFile& dex_file, 5084 Handle<mirror::DexCache> dex_cache, 5085 uint32_t dex_pc) 5086 : HExpression(field_type, 5087 SideEffects::FieldReadOfType(field_type, is_volatile), 5088 dex_pc), 5089 field_info_(field_offset, 5090 field_type, 5091 is_volatile, 5092 field_idx, 5093 declaring_class_def_index, 5094 dex_file, 5095 dex_cache) { 5096 SetRawInputAt(0, cls); 5097 } 5098 5099 5100 bool CanBeMoved() const OVERRIDE { return !IsVolatile(); } 5101 5102 bool InstructionDataEquals(HInstruction* other) const OVERRIDE { 5103 HStaticFieldGet* other_get = other->AsStaticFieldGet(); 5104 return GetFieldOffset().SizeValue() == other_get->GetFieldOffset().SizeValue(); 5105 } 5106 5107 size_t ComputeHashCode() const OVERRIDE { 5108 return (HInstruction::ComputeHashCode() << 7) | GetFieldOffset().SizeValue(); 5109 } 5110 5111 const FieldInfo& GetFieldInfo() const { return field_info_; } 5112 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); } 5113 Primitive::Type GetFieldType() const { return field_info_.GetFieldType(); } 5114 bool IsVolatile() const { return field_info_.IsVolatile(); } 5115 5116 DECLARE_INSTRUCTION(StaticFieldGet); 5117 5118 private: 5119 const FieldInfo field_info_; 5120 5121 DISALLOW_COPY_AND_ASSIGN(HStaticFieldGet); 5122}; 5123 5124class HStaticFieldSet : public HTemplateInstruction<2> { 5125 public: 5126 HStaticFieldSet(HInstruction* cls, 5127 HInstruction* value, 5128 Primitive::Type field_type, 5129 MemberOffset field_offset, 5130 bool is_volatile, 5131 uint32_t field_idx, 5132 uint16_t declaring_class_def_index, 5133 const DexFile& dex_file, 5134 Handle<mirror::DexCache> dex_cache, 5135 uint32_t dex_pc) 5136 : HTemplateInstruction(SideEffects::FieldWriteOfType(field_type, is_volatile), 5137 dex_pc), 5138 field_info_(field_offset, 5139 field_type, 5140 is_volatile, 5141 field_idx, 5142 declaring_class_def_index, 5143 dex_file, 5144 dex_cache), 5145 value_can_be_null_(true) { 5146 SetRawInputAt(0, cls); 5147 SetRawInputAt(1, value); 5148 } 5149 5150 const FieldInfo& GetFieldInfo() const { return field_info_; } 5151 MemberOffset GetFieldOffset() const { return field_info_.GetFieldOffset(); } 5152 Primitive::Type GetFieldType() const { return field_info_.GetFieldType(); } 5153 bool IsVolatile() const { return field_info_.IsVolatile(); } 5154 5155 HInstruction* GetValue() const { return InputAt(1); } 5156 bool GetValueCanBeNull() const { return value_can_be_null_; } 5157 void ClearValueCanBeNull() { value_can_be_null_ = false; } 5158 5159 DECLARE_INSTRUCTION(StaticFieldSet); 5160 5161 private: 5162 const FieldInfo field_info_; 5163 bool value_can_be_null_; 5164 5165 DISALLOW_COPY_AND_ASSIGN(HStaticFieldSet); 5166}; 5167 5168class HUnresolvedInstanceFieldGet : public HExpression<1> { 5169 public: 5170 HUnresolvedInstanceFieldGet(HInstruction* obj, 5171 Primitive::Type field_type, 5172 uint32_t field_index, 5173 uint32_t dex_pc) 5174 : HExpression(field_type, SideEffects::AllExceptGCDependency(), dex_pc), 5175 field_index_(field_index) { 5176 SetRawInputAt(0, obj); 5177 } 5178 5179 bool NeedsEnvironment() const OVERRIDE { return true; } 5180 bool CanThrow() const OVERRIDE { return true; } 5181 5182 Primitive::Type GetFieldType() const { return GetType(); } 5183 uint32_t GetFieldIndex() const { return field_index_; } 5184 5185 DECLARE_INSTRUCTION(UnresolvedInstanceFieldGet); 5186 5187 private: 5188 const uint32_t field_index_; 5189 5190 DISALLOW_COPY_AND_ASSIGN(HUnresolvedInstanceFieldGet); 5191}; 5192 5193class HUnresolvedInstanceFieldSet : public HTemplateInstruction<2> { 5194 public: 5195 HUnresolvedInstanceFieldSet(HInstruction* obj, 5196 HInstruction* value, 5197 Primitive::Type field_type, 5198 uint32_t field_index, 5199 uint32_t dex_pc) 5200 : HTemplateInstruction(SideEffects::AllExceptGCDependency(), dex_pc), 5201 field_type_(field_type), 5202 field_index_(field_index) { 5203 DCHECK_EQ(field_type, value->GetType()); 5204 SetRawInputAt(0, obj); 5205 SetRawInputAt(1, value); 5206 } 5207 5208 bool NeedsEnvironment() const OVERRIDE { return true; } 5209 bool CanThrow() const OVERRIDE { return true; } 5210 5211 Primitive::Type GetFieldType() const { return field_type_; } 5212 uint32_t GetFieldIndex() const { return field_index_; } 5213 5214 DECLARE_INSTRUCTION(UnresolvedInstanceFieldSet); 5215 5216 private: 5217 const Primitive::Type field_type_; 5218 const uint32_t field_index_; 5219 5220 DISALLOW_COPY_AND_ASSIGN(HUnresolvedInstanceFieldSet); 5221}; 5222 5223class HUnresolvedStaticFieldGet : public HExpression<0> { 5224 public: 5225 HUnresolvedStaticFieldGet(Primitive::Type field_type, 5226 uint32_t field_index, 5227 uint32_t dex_pc) 5228 : HExpression(field_type, SideEffects::AllExceptGCDependency(), dex_pc), 5229 field_index_(field_index) { 5230 } 5231 5232 bool NeedsEnvironment() const OVERRIDE { return true; } 5233 bool CanThrow() const OVERRIDE { return true; } 5234 5235 Primitive::Type GetFieldType() const { return GetType(); } 5236 uint32_t GetFieldIndex() const { return field_index_; } 5237 5238 DECLARE_INSTRUCTION(UnresolvedStaticFieldGet); 5239 5240 private: 5241 const uint32_t field_index_; 5242 5243 DISALLOW_COPY_AND_ASSIGN(HUnresolvedStaticFieldGet); 5244}; 5245 5246class HUnresolvedStaticFieldSet : public HTemplateInstruction<1> { 5247 public: 5248 HUnresolvedStaticFieldSet(HInstruction* value, 5249 Primitive::Type field_type, 5250 uint32_t field_index, 5251 uint32_t dex_pc) 5252 : HTemplateInstruction(SideEffects::AllExceptGCDependency(), dex_pc), 5253 field_type_(field_type), 5254 field_index_(field_index) { 5255 DCHECK_EQ(field_type, value->GetType()); 5256 SetRawInputAt(0, value); 5257 } 5258 5259 bool NeedsEnvironment() const OVERRIDE { return true; } 5260 bool CanThrow() const OVERRIDE { return true; } 5261 5262 Primitive::Type GetFieldType() const { return field_type_; } 5263 uint32_t GetFieldIndex() const { return field_index_; } 5264 5265 DECLARE_INSTRUCTION(UnresolvedStaticFieldSet); 5266 5267 private: 5268 const Primitive::Type field_type_; 5269 const uint32_t field_index_; 5270 5271 DISALLOW_COPY_AND_ASSIGN(HUnresolvedStaticFieldSet); 5272}; 5273 5274// Implement the move-exception DEX instruction. 5275class HLoadException : public HExpression<0> { 5276 public: 5277 explicit HLoadException(uint32_t dex_pc = kNoDexPc) 5278 : HExpression(Primitive::kPrimNot, SideEffects::None(), dex_pc) {} 5279 5280 bool CanBeNull() const OVERRIDE { return false; } 5281 5282 DECLARE_INSTRUCTION(LoadException); 5283 5284 private: 5285 DISALLOW_COPY_AND_ASSIGN(HLoadException); 5286}; 5287 5288// Implicit part of move-exception which clears thread-local exception storage. 5289// Must not be removed because the runtime expects the TLS to get cleared. 5290class HClearException : public HTemplateInstruction<0> { 5291 public: 5292 explicit HClearException(uint32_t dex_pc = kNoDexPc) 5293 : HTemplateInstruction(SideEffects::AllWrites(), dex_pc) {} 5294 5295 DECLARE_INSTRUCTION(ClearException); 5296 5297 private: 5298 DISALLOW_COPY_AND_ASSIGN(HClearException); 5299}; 5300 5301class HThrow : public HTemplateInstruction<1> { 5302 public: 5303 HThrow(HInstruction* exception, uint32_t dex_pc) 5304 : HTemplateInstruction(SideEffects::CanTriggerGC(), dex_pc) { 5305 SetRawInputAt(0, exception); 5306 } 5307 5308 bool IsControlFlow() const OVERRIDE { return true; } 5309 5310 bool NeedsEnvironment() const OVERRIDE { return true; } 5311 5312 bool CanThrow() const OVERRIDE { return true; } 5313 5314 5315 DECLARE_INSTRUCTION(Throw); 5316 5317 private: 5318 DISALLOW_COPY_AND_ASSIGN(HThrow); 5319}; 5320 5321/** 5322 * Implementation strategies for the code generator of a HInstanceOf 5323 * or `HCheckCast`. 5324 */ 5325enum class TypeCheckKind { 5326 kUnresolvedCheck, // Check against an unresolved type. 5327 kExactCheck, // Can do a single class compare. 5328 kClassHierarchyCheck, // Can just walk the super class chain. 5329 kAbstractClassCheck, // Can just walk the super class chain, starting one up. 5330 kInterfaceCheck, // No optimization yet when checking against an interface. 5331 kArrayObjectCheck, // Can just check if the array is not primitive. 5332 kArrayCheck // No optimization yet when checking against a generic array. 5333}; 5334 5335class HInstanceOf : public HExpression<2> { 5336 public: 5337 HInstanceOf(HInstruction* object, 5338 HLoadClass* constant, 5339 TypeCheckKind check_kind, 5340 uint32_t dex_pc) 5341 : HExpression(Primitive::kPrimBoolean, 5342 SideEffectsForArchRuntimeCalls(check_kind), 5343 dex_pc), 5344 check_kind_(check_kind), 5345 must_do_null_check_(true) { 5346 SetRawInputAt(0, object); 5347 SetRawInputAt(1, constant); 5348 } 5349 5350 bool CanBeMoved() const OVERRIDE { return true; } 5351 5352 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 5353 return true; 5354 } 5355 5356 bool NeedsEnvironment() const OVERRIDE { 5357 return false; 5358 } 5359 5360 bool IsExactCheck() const { return check_kind_ == TypeCheckKind::kExactCheck; } 5361 5362 TypeCheckKind GetTypeCheckKind() const { return check_kind_; } 5363 5364 // Used only in code generation. 5365 bool MustDoNullCheck() const { return must_do_null_check_; } 5366 void ClearMustDoNullCheck() { must_do_null_check_ = false; } 5367 5368 static SideEffects SideEffectsForArchRuntimeCalls(TypeCheckKind check_kind) { 5369 return (check_kind == TypeCheckKind::kExactCheck) 5370 ? SideEffects::None() 5371 // Mips currently does runtime calls for any other checks. 5372 : SideEffects::CanTriggerGC(); 5373 } 5374 5375 DECLARE_INSTRUCTION(InstanceOf); 5376 5377 private: 5378 const TypeCheckKind check_kind_; 5379 bool must_do_null_check_; 5380 5381 DISALLOW_COPY_AND_ASSIGN(HInstanceOf); 5382}; 5383 5384class HBoundType : public HExpression<1> { 5385 public: 5386 // Constructs an HBoundType with the given upper_bound. 5387 // Ensures that the upper_bound is valid. 5388 HBoundType(HInstruction* input, 5389 ReferenceTypeInfo upper_bound, 5390 bool upper_can_be_null, 5391 uint32_t dex_pc = kNoDexPc) 5392 : HExpression(Primitive::kPrimNot, SideEffects::None(), dex_pc), 5393 upper_bound_(upper_bound), 5394 upper_can_be_null_(upper_can_be_null), 5395 can_be_null_(upper_can_be_null) { 5396 DCHECK_EQ(input->GetType(), Primitive::kPrimNot); 5397 SetRawInputAt(0, input); 5398 SetReferenceTypeInfo(upper_bound_); 5399 } 5400 5401 // GetUpper* should only be used in reference type propagation. 5402 const ReferenceTypeInfo& GetUpperBound() const { return upper_bound_; } 5403 bool GetUpperCanBeNull() const { return upper_can_be_null_; } 5404 5405 void SetCanBeNull(bool can_be_null) { 5406 DCHECK(upper_can_be_null_ || !can_be_null); 5407 can_be_null_ = can_be_null; 5408 } 5409 5410 bool CanBeNull() const OVERRIDE { return can_be_null_; } 5411 5412 DECLARE_INSTRUCTION(BoundType); 5413 5414 private: 5415 // Encodes the most upper class that this instruction can have. In other words 5416 // it is always the case that GetUpperBound().IsSupertypeOf(GetReferenceType()). 5417 // It is used to bound the type in cases like: 5418 // if (x instanceof ClassX) { 5419 // // uper_bound_ will be ClassX 5420 // } 5421 const ReferenceTypeInfo upper_bound_; 5422 // Represents the top constraint that can_be_null_ cannot exceed (i.e. if this 5423 // is false then can_be_null_ cannot be true). 5424 const bool upper_can_be_null_; 5425 bool can_be_null_; 5426 5427 DISALLOW_COPY_AND_ASSIGN(HBoundType); 5428}; 5429 5430class HCheckCast : public HTemplateInstruction<2> { 5431 public: 5432 HCheckCast(HInstruction* object, 5433 HLoadClass* constant, 5434 TypeCheckKind check_kind, 5435 uint32_t dex_pc) 5436 : HTemplateInstruction(SideEffects::CanTriggerGC(), dex_pc), 5437 check_kind_(check_kind), 5438 must_do_null_check_(true) { 5439 SetRawInputAt(0, object); 5440 SetRawInputAt(1, constant); 5441 } 5442 5443 bool CanBeMoved() const OVERRIDE { return true; } 5444 5445 bool InstructionDataEquals(HInstruction* other ATTRIBUTE_UNUSED) const OVERRIDE { 5446 return true; 5447 } 5448 5449 bool NeedsEnvironment() const OVERRIDE { 5450 // Instruction may throw a CheckCastError. 5451 return true; 5452 } 5453 5454 bool CanThrow() const OVERRIDE { return true; } 5455 5456 bool MustDoNullCheck() const { return must_do_null_check_; } 5457 void ClearMustDoNullCheck() { must_do_null_check_ = false; } 5458 TypeCheckKind GetTypeCheckKind() const { return check_kind_; } 5459 5460 bool IsExactCheck() const { return check_kind_ == TypeCheckKind::kExactCheck; } 5461 5462 DECLARE_INSTRUCTION(CheckCast); 5463 5464 private: 5465 const TypeCheckKind check_kind_; 5466 bool must_do_null_check_; 5467 5468 DISALLOW_COPY_AND_ASSIGN(HCheckCast); 5469}; 5470 5471class HMemoryBarrier : public HTemplateInstruction<0> { 5472 public: 5473 explicit HMemoryBarrier(MemBarrierKind barrier_kind, uint32_t dex_pc = kNoDexPc) 5474 : HTemplateInstruction( 5475 SideEffects::AllWritesAndReads(), dex_pc), // Assume write/read on all fields/arrays. 5476 barrier_kind_(barrier_kind) {} 5477 5478 MemBarrierKind GetBarrierKind() { return barrier_kind_; } 5479 5480 DECLARE_INSTRUCTION(MemoryBarrier); 5481 5482 private: 5483 const MemBarrierKind barrier_kind_; 5484 5485 DISALLOW_COPY_AND_ASSIGN(HMemoryBarrier); 5486}; 5487 5488class HMonitorOperation : public HTemplateInstruction<1> { 5489 public: 5490 enum OperationKind { 5491 kEnter, 5492 kExit, 5493 }; 5494 5495 HMonitorOperation(HInstruction* object, OperationKind kind, uint32_t dex_pc) 5496 : HTemplateInstruction( 5497 SideEffects::AllExceptGCDependency(), dex_pc), // Assume write/read on all fields/arrays. 5498 kind_(kind) { 5499 SetRawInputAt(0, object); 5500 } 5501 5502 // Instruction may throw a Java exception, so we need an environment. 5503 bool NeedsEnvironment() const OVERRIDE { return CanThrow(); } 5504 5505 bool CanThrow() const OVERRIDE { 5506 // Verifier guarantees that monitor-exit cannot throw. 5507 // This is important because it allows the HGraphBuilder to remove 5508 // a dead throw-catch loop generated for `synchronized` blocks/methods. 5509 return IsEnter(); 5510 } 5511 5512 5513 bool IsEnter() const { return kind_ == kEnter; } 5514 5515 DECLARE_INSTRUCTION(MonitorOperation); 5516 5517 private: 5518 const OperationKind kind_; 5519 5520 private: 5521 DISALLOW_COPY_AND_ASSIGN(HMonitorOperation); 5522}; 5523 5524/** 5525 * A HInstruction used as a marker for the replacement of new + <init> 5526 * of a String to a call to a StringFactory. Only baseline will see 5527 * the node at code generation, where it will be be treated as null. 5528 * When compiling non-baseline, `HFakeString` instructions are being removed 5529 * in the instruction simplifier. 5530 */ 5531class HFakeString : public HTemplateInstruction<0> { 5532 public: 5533 explicit HFakeString(uint32_t dex_pc = kNoDexPc) 5534 : HTemplateInstruction(SideEffects::None(), dex_pc) {} 5535 5536 Primitive::Type GetType() const OVERRIDE { return Primitive::kPrimNot; } 5537 5538 DECLARE_INSTRUCTION(FakeString); 5539 5540 private: 5541 DISALLOW_COPY_AND_ASSIGN(HFakeString); 5542}; 5543 5544class MoveOperands : public ArenaObject<kArenaAllocMoveOperands> { 5545 public: 5546 MoveOperands(Location source, 5547 Location destination, 5548 Primitive::Type type, 5549 HInstruction* instruction) 5550 : source_(source), destination_(destination), type_(type), instruction_(instruction) {} 5551 5552 Location GetSource() const { return source_; } 5553 Location GetDestination() const { return destination_; } 5554 5555 void SetSource(Location value) { source_ = value; } 5556 void SetDestination(Location value) { destination_ = value; } 5557 5558 // The parallel move resolver marks moves as "in-progress" by clearing the 5559 // destination (but not the source). 5560 Location MarkPending() { 5561 DCHECK(!IsPending()); 5562 Location dest = destination_; 5563 destination_ = Location::NoLocation(); 5564 return dest; 5565 } 5566 5567 void ClearPending(Location dest) { 5568 DCHECK(IsPending()); 5569 destination_ = dest; 5570 } 5571 5572 bool IsPending() const { 5573 DCHECK(!source_.IsInvalid() || destination_.IsInvalid()); 5574 return destination_.IsInvalid() && !source_.IsInvalid(); 5575 } 5576 5577 // True if this blocks a move from the given location. 5578 bool Blocks(Location loc) const { 5579 return !IsEliminated() && source_.OverlapsWith(loc); 5580 } 5581 5582 // A move is redundant if it's been eliminated, if its source and 5583 // destination are the same, or if its destination is unneeded. 5584 bool IsRedundant() const { 5585 return IsEliminated() || destination_.IsInvalid() || source_.Equals(destination_); 5586 } 5587 5588 // We clear both operands to indicate move that's been eliminated. 5589 void Eliminate() { 5590 source_ = destination_ = Location::NoLocation(); 5591 } 5592 5593 bool IsEliminated() const { 5594 DCHECK(!source_.IsInvalid() || destination_.IsInvalid()); 5595 return source_.IsInvalid(); 5596 } 5597 5598 Primitive::Type GetType() const { return type_; } 5599 5600 bool Is64BitMove() const { 5601 return Primitive::Is64BitType(type_); 5602 } 5603 5604 HInstruction* GetInstruction() const { return instruction_; } 5605 5606 private: 5607 Location source_; 5608 Location destination_; 5609 // The type this move is for. 5610 Primitive::Type type_; 5611 // The instruction this move is assocatied with. Null when this move is 5612 // for moving an input in the expected locations of user (including a phi user). 5613 // This is only used in debug mode, to ensure we do not connect interval siblings 5614 // in the same parallel move. 5615 HInstruction* instruction_; 5616}; 5617 5618static constexpr size_t kDefaultNumberOfMoves = 4; 5619 5620class HParallelMove : public HTemplateInstruction<0> { 5621 public: 5622 explicit HParallelMove(ArenaAllocator* arena, uint32_t dex_pc = kNoDexPc) 5623 : HTemplateInstruction(SideEffects::None(), dex_pc), 5624 moves_(arena->Adapter(kArenaAllocMoveOperands)) { 5625 moves_.reserve(kDefaultNumberOfMoves); 5626 } 5627 5628 void AddMove(Location source, 5629 Location destination, 5630 Primitive::Type type, 5631 HInstruction* instruction) { 5632 DCHECK(source.IsValid()); 5633 DCHECK(destination.IsValid()); 5634 if (kIsDebugBuild) { 5635 if (instruction != nullptr) { 5636 for (const MoveOperands& move : moves_) { 5637 if (move.GetInstruction() == instruction) { 5638 // Special case the situation where the move is for the spill slot 5639 // of the instruction. 5640 if ((GetPrevious() == instruction) 5641 || ((GetPrevious() == nullptr) 5642 && instruction->IsPhi() 5643 && instruction->GetBlock() == GetBlock())) { 5644 DCHECK_NE(destination.GetKind(), move.GetDestination().GetKind()) 5645 << "Doing parallel moves for the same instruction."; 5646 } else { 5647 DCHECK(false) << "Doing parallel moves for the same instruction."; 5648 } 5649 } 5650 } 5651 } 5652 for (const MoveOperands& move : moves_) { 5653 DCHECK(!destination.OverlapsWith(move.GetDestination())) 5654 << "Overlapped destination for two moves in a parallel move: " 5655 << move.GetSource() << " ==> " << move.GetDestination() << " and " 5656 << source << " ==> " << destination; 5657 } 5658 } 5659 moves_.emplace_back(source, destination, type, instruction); 5660 } 5661 5662 MoveOperands* MoveOperandsAt(size_t index) { 5663 return &moves_[index]; 5664 } 5665 5666 size_t NumMoves() const { return moves_.size(); } 5667 5668 DECLARE_INSTRUCTION(ParallelMove); 5669 5670 private: 5671 ArenaVector<MoveOperands> moves_; 5672 5673 DISALLOW_COPY_AND_ASSIGN(HParallelMove); 5674}; 5675 5676} // namespace art 5677 5678#ifdef ART_ENABLE_CODEGEN_arm 5679#include "nodes_arm.h" 5680#endif 5681#ifdef ART_ENABLE_CODEGEN_arm64 5682#include "nodes_arm64.h" 5683#endif 5684#ifdef ART_ENABLE_CODEGEN_x86 5685#include "nodes_x86.h" 5686#endif 5687 5688namespace art { 5689 5690class HGraphVisitor : public ValueObject { 5691 public: 5692 explicit HGraphVisitor(HGraph* graph) : graph_(graph) {} 5693 virtual ~HGraphVisitor() {} 5694 5695 virtual void VisitInstruction(HInstruction* instruction ATTRIBUTE_UNUSED) {} 5696 virtual void VisitBasicBlock(HBasicBlock* block); 5697 5698 // Visit the graph following basic block insertion order. 5699 void VisitInsertionOrder(); 5700 5701 // Visit the graph following dominator tree reverse post-order. 5702 void VisitReversePostOrder(); 5703 5704 HGraph* GetGraph() const { return graph_; } 5705 5706 // Visit functions for instruction classes. 5707#define DECLARE_VISIT_INSTRUCTION(name, super) \ 5708 virtual void Visit##name(H##name* instr) { VisitInstruction(instr); } 5709 5710 FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION) 5711 5712#undef DECLARE_VISIT_INSTRUCTION 5713 5714 private: 5715 HGraph* const graph_; 5716 5717 DISALLOW_COPY_AND_ASSIGN(HGraphVisitor); 5718}; 5719 5720class HGraphDelegateVisitor : public HGraphVisitor { 5721 public: 5722 explicit HGraphDelegateVisitor(HGraph* graph) : HGraphVisitor(graph) {} 5723 virtual ~HGraphDelegateVisitor() {} 5724 5725 // Visit functions that delegate to to super class. 5726#define DECLARE_VISIT_INSTRUCTION(name, super) \ 5727 void Visit##name(H##name* instr) OVERRIDE { Visit##super(instr); } 5728 5729 FOR_EACH_INSTRUCTION(DECLARE_VISIT_INSTRUCTION) 5730 5731#undef DECLARE_VISIT_INSTRUCTION 5732 5733 private: 5734 DISALLOW_COPY_AND_ASSIGN(HGraphDelegateVisitor); 5735}; 5736 5737class HInsertionOrderIterator : public ValueObject { 5738 public: 5739 explicit HInsertionOrderIterator(const HGraph& graph) : graph_(graph), index_(0) {} 5740 5741 bool Done() const { return index_ == graph_.GetBlocks().size(); } 5742 HBasicBlock* Current() const { return graph_.GetBlocks()[index_]; } 5743 void Advance() { ++index_; } 5744 5745 private: 5746 const HGraph& graph_; 5747 size_t index_; 5748 5749 DISALLOW_COPY_AND_ASSIGN(HInsertionOrderIterator); 5750}; 5751 5752class HReversePostOrderIterator : public ValueObject { 5753 public: 5754 explicit HReversePostOrderIterator(const HGraph& graph) : graph_(graph), index_(0) { 5755 // Check that reverse post order of the graph has been built. 5756 DCHECK(!graph.GetReversePostOrder().empty()); 5757 } 5758 5759 bool Done() const { return index_ == graph_.GetReversePostOrder().size(); } 5760 HBasicBlock* Current() const { return graph_.GetReversePostOrder()[index_]; } 5761 void Advance() { ++index_; } 5762 5763 private: 5764 const HGraph& graph_; 5765 size_t index_; 5766 5767 DISALLOW_COPY_AND_ASSIGN(HReversePostOrderIterator); 5768}; 5769 5770class HPostOrderIterator : public ValueObject { 5771 public: 5772 explicit HPostOrderIterator(const HGraph& graph) 5773 : graph_(graph), index_(graph_.GetReversePostOrder().size()) { 5774 // Check that reverse post order of the graph has been built. 5775 DCHECK(!graph.GetReversePostOrder().empty()); 5776 } 5777 5778 bool Done() const { return index_ == 0; } 5779 HBasicBlock* Current() const { return graph_.GetReversePostOrder()[index_ - 1u]; } 5780 void Advance() { --index_; } 5781 5782 private: 5783 const HGraph& graph_; 5784 size_t index_; 5785 5786 DISALLOW_COPY_AND_ASSIGN(HPostOrderIterator); 5787}; 5788 5789class HLinearPostOrderIterator : public ValueObject { 5790 public: 5791 explicit HLinearPostOrderIterator(const HGraph& graph) 5792 : order_(graph.GetLinearOrder()), index_(graph.GetLinearOrder().size()) {} 5793 5794 bool Done() const { return index_ == 0; } 5795 5796 HBasicBlock* Current() const { return order_[index_ - 1u]; } 5797 5798 void Advance() { 5799 --index_; 5800 DCHECK_GE(index_, 0U); 5801 } 5802 5803 private: 5804 const ArenaVector<HBasicBlock*>& order_; 5805 size_t index_; 5806 5807 DISALLOW_COPY_AND_ASSIGN(HLinearPostOrderIterator); 5808}; 5809 5810class HLinearOrderIterator : public ValueObject { 5811 public: 5812 explicit HLinearOrderIterator(const HGraph& graph) 5813 : order_(graph.GetLinearOrder()), index_(0) {} 5814 5815 bool Done() const { return index_ == order_.size(); } 5816 HBasicBlock* Current() const { return order_[index_]; } 5817 void Advance() { ++index_; } 5818 5819 private: 5820 const ArenaVector<HBasicBlock*>& order_; 5821 size_t index_; 5822 5823 DISALLOW_COPY_AND_ASSIGN(HLinearOrderIterator); 5824}; 5825 5826// Iterator over the blocks that art part of the loop. Includes blocks part 5827// of an inner loop. The order in which the blocks are iterated is on their 5828// block id. 5829class HBlocksInLoopIterator : public ValueObject { 5830 public: 5831 explicit HBlocksInLoopIterator(const HLoopInformation& info) 5832 : blocks_in_loop_(info.GetBlocks()), 5833 blocks_(info.GetHeader()->GetGraph()->GetBlocks()), 5834 index_(0) { 5835 if (!blocks_in_loop_.IsBitSet(index_)) { 5836 Advance(); 5837 } 5838 } 5839 5840 bool Done() const { return index_ == blocks_.size(); } 5841 HBasicBlock* Current() const { return blocks_[index_]; } 5842 void Advance() { 5843 ++index_; 5844 for (size_t e = blocks_.size(); index_ < e; ++index_) { 5845 if (blocks_in_loop_.IsBitSet(index_)) { 5846 break; 5847 } 5848 } 5849 } 5850 5851 private: 5852 const BitVector& blocks_in_loop_; 5853 const ArenaVector<HBasicBlock*>& blocks_; 5854 size_t index_; 5855 5856 DISALLOW_COPY_AND_ASSIGN(HBlocksInLoopIterator); 5857}; 5858 5859// Iterator over the blocks that art part of the loop. Includes blocks part 5860// of an inner loop. The order in which the blocks are iterated is reverse 5861// post order. 5862class HBlocksInLoopReversePostOrderIterator : public ValueObject { 5863 public: 5864 explicit HBlocksInLoopReversePostOrderIterator(const HLoopInformation& info) 5865 : blocks_in_loop_(info.GetBlocks()), 5866 blocks_(info.GetHeader()->GetGraph()->GetReversePostOrder()), 5867 index_(0) { 5868 if (!blocks_in_loop_.IsBitSet(blocks_[index_]->GetBlockId())) { 5869 Advance(); 5870 } 5871 } 5872 5873 bool Done() const { return index_ == blocks_.size(); } 5874 HBasicBlock* Current() const { return blocks_[index_]; } 5875 void Advance() { 5876 ++index_; 5877 for (size_t e = blocks_.size(); index_ < e; ++index_) { 5878 if (blocks_in_loop_.IsBitSet(blocks_[index_]->GetBlockId())) { 5879 break; 5880 } 5881 } 5882 } 5883 5884 private: 5885 const BitVector& blocks_in_loop_; 5886 const ArenaVector<HBasicBlock*>& blocks_; 5887 size_t index_; 5888 5889 DISALLOW_COPY_AND_ASSIGN(HBlocksInLoopReversePostOrderIterator); 5890}; 5891 5892inline int64_t Int64FromConstant(HConstant* constant) { 5893 DCHECK(constant->IsIntConstant() || constant->IsLongConstant()); 5894 return constant->IsIntConstant() ? constant->AsIntConstant()->GetValue() 5895 : constant->AsLongConstant()->GetValue(); 5896} 5897 5898inline bool IsSameDexFile(const DexFile& lhs, const DexFile& rhs) { 5899 // For the purposes of the compiler, the dex files must actually be the same object 5900 // if we want to safely treat them as the same. This is especially important for JIT 5901 // as custom class loaders can open the same underlying file (or memory) multiple 5902 // times and provide different class resolution but no two class loaders should ever 5903 // use the same DexFile object - doing so is an unsupported hack that can lead to 5904 // all sorts of weird failures. 5905 return &lhs == &rhs; 5906} 5907 5908#define INSTRUCTION_TYPE_CHECK(type, super) \ 5909 inline bool HInstruction::Is##type() const { return GetKind() == k##type; } \ 5910 inline const H##type* HInstruction::As##type() const { \ 5911 return Is##type() ? down_cast<const H##type*>(this) : nullptr; \ 5912 } \ 5913 inline H##type* HInstruction::As##type() { \ 5914 return Is##type() ? static_cast<H##type*>(this) : nullptr; \ 5915 } 5916 5917 FOR_EACH_CONCRETE_INSTRUCTION(INSTRUCTION_TYPE_CHECK) 5918#undef INSTRUCTION_TYPE_CHECK 5919 5920} // namespace art 5921 5922#endif // ART_COMPILER_OPTIMIZING_NODES_H_ 5923