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