mir_graph.h revision cdacac4a8196bdc620185079ec9e886329606f3d
1/* 2 * Copyright (C) 2013 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_DEX_MIR_GRAPH_H_ 18#define ART_COMPILER_DEX_MIR_GRAPH_H_ 19 20#include <stdint.h> 21 22#include "dex_file.h" 23#include "dex_instruction.h" 24#include "compiler_ir.h" 25#include "invoke_type.h" 26#include "mir_field_info.h" 27#include "mir_method_info.h" 28#include "utils/arena_bit_vector.h" 29#include "utils/growable_array.h" 30#include "reg_storage.h" 31 32namespace art { 33 34enum InstructionAnalysisAttributePos { 35 kUninterestingOp = 0, 36 kArithmeticOp, 37 kFPOp, 38 kSingleOp, 39 kDoubleOp, 40 kIntOp, 41 kLongOp, 42 kBranchOp, 43 kInvokeOp, 44 kArrayOp, 45 kHeavyweightOp, 46 kSimpleConstOp, 47 kMoveOp, 48 kSwitch 49}; 50 51#define AN_NONE (1 << kUninterestingOp) 52#define AN_MATH (1 << kArithmeticOp) 53#define AN_FP (1 << kFPOp) 54#define AN_LONG (1 << kLongOp) 55#define AN_INT (1 << kIntOp) 56#define AN_SINGLE (1 << kSingleOp) 57#define AN_DOUBLE (1 << kDoubleOp) 58#define AN_FLOATMATH (1 << kFPOp) 59#define AN_BRANCH (1 << kBranchOp) 60#define AN_INVOKE (1 << kInvokeOp) 61#define AN_ARRAYOP (1 << kArrayOp) 62#define AN_HEAVYWEIGHT (1 << kHeavyweightOp) 63#define AN_SIMPLECONST (1 << kSimpleConstOp) 64#define AN_MOVE (1 << kMoveOp) 65#define AN_SWITCH (1 << kSwitch) 66#define AN_COMPUTATIONAL (AN_MATH | AN_ARRAYOP | AN_MOVE | AN_SIMPLECONST) 67 68enum DataFlowAttributePos { 69 kUA = 0, 70 kUB, 71 kUC, 72 kAWide, 73 kBWide, 74 kCWide, 75 kDA, 76 kIsMove, 77 kSetsConst, 78 kFormat35c, 79 kFormat3rc, 80 kNullCheckSrc0, // Null check of uses[0]. 81 kNullCheckSrc1, // Null check of uses[1]. 82 kNullCheckSrc2, // Null check of uses[2]. 83 kNullCheckOut0, // Null check out outgoing arg0. 84 kDstNonNull, // May assume dst is non-null. 85 kRetNonNull, // May assume retval is non-null. 86 kNullTransferSrc0, // Object copy src[0] -> dst. 87 kNullTransferSrcN, // Phi null check state transfer. 88 kRangeCheckSrc1, // Range check of uses[1]. 89 kRangeCheckSrc2, // Range check of uses[2]. 90 kRangeCheckSrc3, // Range check of uses[3]. 91 kFPA, 92 kFPB, 93 kFPC, 94 kCoreA, 95 kCoreB, 96 kCoreC, 97 kRefA, 98 kRefB, 99 kRefC, 100 kUsesMethodStar, // Implicit use of Method*. 101 kUsesIField, // Accesses an instance field (IGET/IPUT). 102 kUsesSField, // Accesses a static field (SGET/SPUT). 103 kDoLVN, // Worth computing local value numbers. 104}; 105 106#define DF_NOP UINT64_C(0) 107#define DF_UA (UINT64_C(1) << kUA) 108#define DF_UB (UINT64_C(1) << kUB) 109#define DF_UC (UINT64_C(1) << kUC) 110#define DF_A_WIDE (UINT64_C(1) << kAWide) 111#define DF_B_WIDE (UINT64_C(1) << kBWide) 112#define DF_C_WIDE (UINT64_C(1) << kCWide) 113#define DF_DA (UINT64_C(1) << kDA) 114#define DF_IS_MOVE (UINT64_C(1) << kIsMove) 115#define DF_SETS_CONST (UINT64_C(1) << kSetsConst) 116#define DF_FORMAT_35C (UINT64_C(1) << kFormat35c) 117#define DF_FORMAT_3RC (UINT64_C(1) << kFormat3rc) 118#define DF_NULL_CHK_0 (UINT64_C(1) << kNullCheckSrc0) 119#define DF_NULL_CHK_1 (UINT64_C(1) << kNullCheckSrc1) 120#define DF_NULL_CHK_2 (UINT64_C(1) << kNullCheckSrc2) 121#define DF_NULL_CHK_OUT0 (UINT64_C(1) << kNullCheckOut0) 122#define DF_NON_NULL_DST (UINT64_C(1) << kDstNonNull) 123#define DF_NON_NULL_RET (UINT64_C(1) << kRetNonNull) 124#define DF_NULL_TRANSFER_0 (UINT64_C(1) << kNullTransferSrc0) 125#define DF_NULL_TRANSFER_N (UINT64_C(1) << kNullTransferSrcN) 126#define DF_RANGE_CHK_1 (UINT64_C(1) << kRangeCheckSrc1) 127#define DF_RANGE_CHK_2 (UINT64_C(1) << kRangeCheckSrc2) 128#define DF_RANGE_CHK_3 (UINT64_C(1) << kRangeCheckSrc3) 129#define DF_FP_A (UINT64_C(1) << kFPA) 130#define DF_FP_B (UINT64_C(1) << kFPB) 131#define DF_FP_C (UINT64_C(1) << kFPC) 132#define DF_CORE_A (UINT64_C(1) << kCoreA) 133#define DF_CORE_B (UINT64_C(1) << kCoreB) 134#define DF_CORE_C (UINT64_C(1) << kCoreC) 135#define DF_REF_A (UINT64_C(1) << kRefA) 136#define DF_REF_B (UINT64_C(1) << kRefB) 137#define DF_REF_C (UINT64_C(1) << kRefC) 138#define DF_UMS (UINT64_C(1) << kUsesMethodStar) 139#define DF_IFIELD (UINT64_C(1) << kUsesIField) 140#define DF_SFIELD (UINT64_C(1) << kUsesSField) 141#define DF_LVN (UINT64_C(1) << kDoLVN) 142 143#define DF_HAS_USES (DF_UA | DF_UB | DF_UC) 144 145#define DF_HAS_DEFS (DF_DA) 146 147#define DF_HAS_NULL_CHKS (DF_NULL_CHK_0 | \ 148 DF_NULL_CHK_1 | \ 149 DF_NULL_CHK_2 | \ 150 DF_NULL_CHK_OUT0) 151 152#define DF_HAS_RANGE_CHKS (DF_RANGE_CHK_1 | \ 153 DF_RANGE_CHK_2 | \ 154 DF_RANGE_CHK_3) 155 156#define DF_HAS_NR_CHKS (DF_HAS_NULL_CHKS | \ 157 DF_HAS_RANGE_CHKS) 158 159#define DF_A_IS_REG (DF_UA | DF_DA) 160#define DF_B_IS_REG (DF_UB) 161#define DF_C_IS_REG (DF_UC) 162#define DF_IS_GETTER_OR_SETTER (DF_IS_GETTER | DF_IS_SETTER) 163#define DF_USES_FP (DF_FP_A | DF_FP_B | DF_FP_C) 164#define DF_NULL_TRANSFER (DF_NULL_TRANSFER_0 | DF_NULL_TRANSFER_N) 165enum OatMethodAttributes { 166 kIsLeaf, // Method is leaf. 167 kHasLoop, // Method contains simple loop. 168}; 169 170#define METHOD_IS_LEAF (1 << kIsLeaf) 171#define METHOD_HAS_LOOP (1 << kHasLoop) 172 173// Minimum field size to contain Dalvik v_reg number. 174#define VREG_NUM_WIDTH 16 175 176#define INVALID_SREG (-1) 177#define INVALID_VREG (0xFFFFU) 178#define INVALID_REG (0x7F) 179#define INVALID_OFFSET (0xDEADF00FU) 180 181#define MIR_IGNORE_NULL_CHECK (1 << kMIRIgnoreNullCheck) 182#define MIR_NULL_CHECK_ONLY (1 << kMIRNullCheckOnly) 183#define MIR_IGNORE_RANGE_CHECK (1 << kMIRIgnoreRangeCheck) 184#define MIR_RANGE_CHECK_ONLY (1 << kMIRRangeCheckOnly) 185#define MIR_IGNORE_CLINIT_CHECK (1 << kMIRIgnoreClInitCheck) 186#define MIR_INLINED (1 << kMIRInlined) 187#define MIR_INLINED_PRED (1 << kMIRInlinedPred) 188#define MIR_CALLEE (1 << kMIRCallee) 189#define MIR_IGNORE_SUSPEND_CHECK (1 << kMIRIgnoreSuspendCheck) 190#define MIR_DUP (1 << kMIRDup) 191 192#define BLOCK_NAME_LEN 80 193 194typedef uint16_t BasicBlockId; 195static const BasicBlockId NullBasicBlockId = 0; 196 197/* 198 * In general, vreg/sreg describe Dalvik registers that originated with dx. However, 199 * it is useful to have compiler-generated temporary registers and have them treated 200 * in the same manner as dx-generated virtual registers. This struct records the SSA 201 * name of compiler-introduced temporaries. 202 */ 203struct CompilerTemp { 204 int32_t v_reg; // Virtual register number for temporary. 205 int32_t s_reg_low; // SSA name for low Dalvik word. 206}; 207 208enum CompilerTempType { 209 kCompilerTempVR, // A virtual register temporary. 210 kCompilerTempSpecialMethodPtr, // Temporary that keeps track of current method pointer. 211}; 212 213// When debug option enabled, records effectiveness of null and range check elimination. 214struct Checkstats { 215 int32_t null_checks; 216 int32_t null_checks_eliminated; 217 int32_t range_checks; 218 int32_t range_checks_eliminated; 219}; 220 221// Dataflow attributes of a basic block. 222struct BasicBlockDataFlow { 223 ArenaBitVector* use_v; 224 ArenaBitVector* def_v; 225 ArenaBitVector* live_in_v; 226 ArenaBitVector* phi_v; 227 int32_t* vreg_to_ssa_map; 228 ArenaBitVector* ending_check_v; // For null check and class init check elimination. 229}; 230 231/* 232 * Normalized use/def for a MIR operation using SSA names rather than vregs. Note that 233 * uses/defs retain the Dalvik convention that long operations operate on a pair of 32-bit 234 * vregs. For example, "ADD_LONG v0, v2, v3" would have 2 defs (v0/v1) and 4 uses (v2/v3, v4/v5). 235 * Following SSA renaming, this is the primary struct used by code generators to locate 236 * operand and result registers. This is a somewhat confusing and unhelpful convention that 237 * we may want to revisit in the future. 238 */ 239struct SSARepresentation { 240 int16_t num_uses; 241 int16_t num_defs; 242 int32_t* uses; 243 bool* fp_use; 244 int32_t* defs; 245 bool* fp_def; 246}; 247 248/* 249 * The Midlevel Intermediate Representation node, which may be largely considered a 250 * wrapper around a Dalvik byte code. 251 */ 252struct MIR { 253 /* 254 * TODO: remove embedded DecodedInstruction to save space, keeping only opcode. Recover 255 * additional fields on as-needed basis. Question: how to support MIR Pseudo-ops; probably 256 * need to carry aux data pointer. 257 */ 258 DecodedInstruction dalvikInsn; 259 uint16_t width; // Note: width can include switch table or fill array data. 260 NarrowDexOffset offset; // Offset of the instruction in code units. 261 uint16_t optimization_flags; 262 int16_t m_unit_index; // From which method was this MIR included 263 MIR* next; 264 SSARepresentation* ssa_rep; 265 union { 266 // Incoming edges for phi node. 267 BasicBlockId* phi_incoming; 268 // Establish link from check instruction (kMirOpCheck) to the actual throwing instruction. 269 MIR* throw_insn; 270 // Branch condition for fused cmp or select. 271 ConditionCode ccode; 272 // IGET/IPUT lowering info index, points to MIRGraph::ifield_lowering_infos_. Due to limit on 273 // the number of code points (64K) and size of IGET/IPUT insn (2), this will never exceed 32K. 274 uint32_t ifield_lowering_info; 275 // SGET/SPUT lowering info index, points to MIRGraph::sfield_lowering_infos_. Due to limit on 276 // the number of code points (64K) and size of SGET/SPUT insn (2), this will never exceed 32K. 277 uint32_t sfield_lowering_info; 278 // INVOKE data index, points to MIRGraph::method_lowering_infos_. 279 uint32_t method_lowering_info; 280 } meta; 281}; 282 283struct SuccessorBlockInfo; 284 285struct BasicBlock { 286 BasicBlockId id; 287 BasicBlockId dfs_id; 288 NarrowDexOffset start_offset; // Offset in code units. 289 BasicBlockId fall_through; 290 BasicBlockId taken; 291 BasicBlockId i_dom; // Immediate dominator. 292 uint16_t nesting_depth; 293 BBType block_type:4; 294 BlockListType successor_block_list_type:4; 295 bool visited:1; 296 bool hidden:1; 297 bool catch_entry:1; 298 bool explicit_throw:1; 299 bool conditional_branch:1; 300 bool terminated_by_return:1; // Block ends with a Dalvik return opcode. 301 bool dominates_return:1; // Is a member of return extended basic block. 302 bool use_lvn:1; // Run local value numbering on this block. 303 MIR* first_mir_insn; 304 MIR* last_mir_insn; 305 BasicBlockDataFlow* data_flow_info; 306 ArenaBitVector* dominators; 307 ArenaBitVector* i_dominated; // Set nodes being immediately dominated. 308 ArenaBitVector* dom_frontier; // Dominance frontier. 309 GrowableArray<BasicBlockId>* predecessors; 310 GrowableArray<SuccessorBlockInfo*>* successor_blocks; 311 312 void AppendMIR(MIR* mir); 313 void PrependMIR(MIR* mir); 314 void InsertMIRAfter(MIR* current_mir, MIR* new_mir); 315 316 /** 317 * @brief Used to obtain the next MIR that follows unconditionally. 318 * @details The implementation does not guarantee that a MIR does not 319 * follow even if this method returns nullptr. 320 * @param mir_graph the MIRGraph. 321 * @param current The MIR for which to find an unconditional follower. 322 * @return Returns the following MIR if one can be found. 323 */ 324 MIR* GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current); 325}; 326 327/* 328 * The "blocks" field in "successor_block_list" points to an array of elements with the type 329 * "SuccessorBlockInfo". For catch blocks, key is type index for the exception. For swtich 330 * blocks, key is the case value. 331 */ 332struct SuccessorBlockInfo { 333 BasicBlockId block; 334 int key; 335}; 336 337/* 338 * Whereas a SSA name describes a definition of a Dalvik vreg, the RegLocation describes 339 * the type of an SSA name (and, can also be used by code generators to record where the 340 * value is located (i.e. - physical register, frame, spill, etc.). For each SSA name (SReg) 341 * there is a RegLocation. 342 * A note on SSA names: 343 * o SSA names for Dalvik vRegs v0..vN will be assigned 0..N. These represent the "vN_0" 344 * names. Negative SSA names represent special values not present in the Dalvik byte code. 345 * For example, SSA name -1 represents an invalid SSA name, and SSA name -2 represents the 346 * the Method pointer. SSA names < -2 are reserved for future use. 347 * o The vN_0 names for non-argument Dalvik should in practice never be used (as they would 348 * represent the read of an undefined local variable). The first definition of the 349 * underlying Dalvik vReg will result in a vN_1 name. 350 * 351 * FIXME: The orig_sreg field was added as a workaround for llvm bitcode generation. With 352 * the latest restructuring, we should be able to remove it and rely on s_reg_low throughout. 353 */ 354struct RegLocation { 355 RegLocationType location:3; 356 unsigned wide:1; 357 unsigned defined:1; // Do we know the type? 358 unsigned is_const:1; // Constant, value in mir_graph->constant_values[]. 359 unsigned fp:1; // Floating point? 360 unsigned core:1; // Non-floating point? 361 unsigned ref:1; // Something GC cares about. 362 unsigned high_word:1; // High word of pair? 363 unsigned home:1; // Does this represent the home location? 364 VectorLengthType vec_len:3; // TODO: remove. Is this value in a vector register, and how big is it? 365 RegStorage reg; // Encoded physical registers. 366 int16_t s_reg_low; // SSA name for low Dalvik word. 367 int16_t orig_sreg; // TODO: remove after Bitcode gen complete 368 // and consolidate usage w/ s_reg_low. 369 370 bool IsVectorScalar() const { return vec_len == kVectorLength4 || vec_len == kVectorLength8;} 371}; 372 373/* 374 * Collection of information describing an invoke, and the destination of 375 * the subsequent MOVE_RESULT (if applicable). Collected as a unit to enable 376 * more efficient invoke code generation. 377 */ 378struct CallInfo { 379 int num_arg_words; // Note: word count, not arg count. 380 RegLocation* args; // One for each word of arguments. 381 RegLocation result; // Eventual target of MOVE_RESULT. 382 int opt_flags; 383 InvokeType type; 384 uint32_t dex_idx; 385 uint32_t index; // Method idx for invokes, type idx for FilledNewArray. 386 uintptr_t direct_code; 387 uintptr_t direct_method; 388 RegLocation target; // Target of following move_result. 389 bool skip_this; 390 bool is_range; 391 DexOffset offset; // Offset in code units. 392 MIR* mir; 393}; 394 395 396const RegLocation bad_loc = {kLocDalvikFrame, 0, 0, 0, 0, 0, 0, 0, 0, kVectorNotUsed, 397 RegStorage(RegStorage::kInvalid), INVALID_SREG, INVALID_SREG}; 398 399class MIRGraph { 400 public: 401 MIRGraph(CompilationUnit* cu, ArenaAllocator* arena); 402 ~MIRGraph(); 403 404 /* 405 * Examine the graph to determine whether it's worthwile to spend the time compiling 406 * this method. 407 */ 408 bool SkipCompilation(); 409 410 /* 411 * Should we skip the compilation of this method based on its name? 412 */ 413 bool SkipCompilation(const std::string& methodname); 414 415 /* 416 * Parse dex method and add MIR at current insert point. Returns id (which is 417 * actually the index of the method in the m_units_ array). 418 */ 419 void InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags, 420 InvokeType invoke_type, uint16_t class_def_idx, 421 uint32_t method_idx, jobject class_loader, const DexFile& dex_file); 422 423 /* Find existing block */ 424 BasicBlock* FindBlock(DexOffset code_offset) { 425 return FindBlock(code_offset, false, false, NULL); 426 } 427 428 const uint16_t* GetCurrentInsns() const { 429 return current_code_item_->insns_; 430 } 431 432 const uint16_t* GetInsns(int m_unit_index) const { 433 return m_units_[m_unit_index]->GetCodeItem()->insns_; 434 } 435 436 int GetNumBlocks() const { 437 return num_blocks_; 438 } 439 440 size_t GetNumDalvikInsns() const { 441 return cu_->code_item->insns_size_in_code_units_; 442 } 443 444 ArenaBitVector* GetTryBlockAddr() const { 445 return try_block_addr_; 446 } 447 448 BasicBlock* GetEntryBlock() const { 449 return entry_block_; 450 } 451 452 BasicBlock* GetExitBlock() const { 453 return exit_block_; 454 } 455 456 BasicBlock* GetBasicBlock(int block_id) const { 457 return (block_id == NullBasicBlockId) ? NULL : block_list_.Get(block_id); 458 } 459 460 size_t GetBasicBlockListCount() const { 461 return block_list_.Size(); 462 } 463 464 GrowableArray<BasicBlock*>* GetBlockList() { 465 return &block_list_; 466 } 467 468 GrowableArray<BasicBlockId>* GetDfsOrder() { 469 return dfs_order_; 470 } 471 472 GrowableArray<BasicBlockId>* GetDfsPostOrder() { 473 return dfs_post_order_; 474 } 475 476 GrowableArray<BasicBlockId>* GetDomPostOrder() { 477 return dom_post_order_traversal_; 478 } 479 480 int GetDefCount() const { 481 return def_count_; 482 } 483 484 ArenaAllocator* GetArena() { 485 return arena_; 486 } 487 488 void EnableOpcodeCounting() { 489 opcode_count_ = static_cast<int*>(arena_->Alloc(kNumPackedOpcodes * sizeof(int), 490 kArenaAllocMisc)); 491 } 492 493 void ShowOpcodeStats(); 494 495 DexCompilationUnit* GetCurrentDexCompilationUnit() const { 496 return m_units_[current_method_]; 497 } 498 499 /** 500 * @brief Dump a CFG into a dot file format. 501 * @param dir_prefix the directory the file will be created in. 502 * @param all_blocks does the dumper use all the basic blocks or use the reachable blocks. 503 * @param suffix does the filename require a suffix or not (default = nullptr). 504 */ 505 void DumpCFG(const char* dir_prefix, bool all_blocks, const char* suffix = nullptr); 506 507 bool HasFieldAccess() const { 508 return (merged_df_flags_ & (DF_IFIELD | DF_SFIELD)) != 0u; 509 } 510 511 bool HasStaticFieldAccess() const { 512 return (merged_df_flags_ & DF_SFIELD) != 0u; 513 } 514 515 bool HasInvokes() const { 516 // NOTE: These formats include the rare filled-new-array/range. 517 return (merged_df_flags_ & (DF_FORMAT_35C | DF_FORMAT_3RC)) != 0u; 518 } 519 520 void DoCacheFieldLoweringInfo(); 521 522 const MirIFieldLoweringInfo& GetIFieldLoweringInfo(MIR* mir) const { 523 DCHECK_LT(mir->meta.ifield_lowering_info, ifield_lowering_infos_.Size()); 524 return ifield_lowering_infos_.GetRawStorage()[mir->meta.ifield_lowering_info]; 525 } 526 527 const MirSFieldLoweringInfo& GetSFieldLoweringInfo(MIR* mir) const { 528 DCHECK_LT(mir->meta.sfield_lowering_info, sfield_lowering_infos_.Size()); 529 return sfield_lowering_infos_.GetRawStorage()[mir->meta.sfield_lowering_info]; 530 } 531 532 void DoCacheMethodLoweringInfo(); 533 534 const MirMethodLoweringInfo& GetMethodLoweringInfo(MIR* mir) { 535 DCHECK_LT(mir->meta.method_lowering_info, method_lowering_infos_.Size()); 536 return method_lowering_infos_.GetRawStorage()[mir->meta.method_lowering_info]; 537 } 538 539 void ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput); 540 541 void InitRegLocations(); 542 543 void RemapRegLocations(); 544 545 void DumpRegLocTable(RegLocation* table, int count); 546 547 void BasicBlockOptimization(); 548 549 bool IsConst(int32_t s_reg) const { 550 return is_constant_v_->IsBitSet(s_reg); 551 } 552 553 bool IsConst(RegLocation loc) const { 554 return loc.orig_sreg < 0 ? false : IsConst(loc.orig_sreg); 555 } 556 557 int32_t ConstantValue(RegLocation loc) const { 558 DCHECK(IsConst(loc)); 559 return constant_values_[loc.orig_sreg]; 560 } 561 562 int32_t ConstantValue(int32_t s_reg) const { 563 DCHECK(IsConst(s_reg)); 564 return constant_values_[s_reg]; 565 } 566 567 int64_t ConstantValueWide(RegLocation loc) const { 568 DCHECK(IsConst(loc)); 569 return (static_cast<int64_t>(constant_values_[loc.orig_sreg + 1]) << 32) | 570 Low32Bits(static_cast<int64_t>(constant_values_[loc.orig_sreg])); 571 } 572 573 bool IsConstantNullRef(RegLocation loc) const { 574 return loc.ref && loc.is_const && (ConstantValue(loc) == 0); 575 } 576 577 int GetNumSSARegs() const { 578 return num_ssa_regs_; 579 } 580 581 void SetNumSSARegs(int new_num) { 582 /* 583 * TODO: It's theoretically possible to exceed 32767, though any cases which did 584 * would be filtered out with current settings. When orig_sreg field is removed 585 * from RegLocation, expand s_reg_low to handle all possible cases and remove DCHECK(). 586 */ 587 DCHECK_EQ(new_num, static_cast<int16_t>(new_num)); 588 num_ssa_regs_ = new_num; 589 } 590 591 unsigned int GetNumReachableBlocks() const { 592 return num_reachable_blocks_; 593 } 594 595 int GetUseCount(int vreg) const { 596 return use_counts_.Get(vreg); 597 } 598 599 int GetRawUseCount(int vreg) const { 600 return raw_use_counts_.Get(vreg); 601 } 602 603 int GetSSASubscript(int ssa_reg) const { 604 return ssa_subscripts_->Get(ssa_reg); 605 } 606 607 RegLocation GetRawSrc(MIR* mir, int num) { 608 DCHECK(num < mir->ssa_rep->num_uses); 609 RegLocation res = reg_location_[mir->ssa_rep->uses[num]]; 610 return res; 611 } 612 613 RegLocation GetRawDest(MIR* mir) { 614 DCHECK_GT(mir->ssa_rep->num_defs, 0); 615 RegLocation res = reg_location_[mir->ssa_rep->defs[0]]; 616 return res; 617 } 618 619 RegLocation GetDest(MIR* mir) { 620 RegLocation res = GetRawDest(mir); 621 DCHECK(!res.wide); 622 return res; 623 } 624 625 RegLocation GetSrc(MIR* mir, int num) { 626 RegLocation res = GetRawSrc(mir, num); 627 DCHECK(!res.wide); 628 return res; 629 } 630 631 RegLocation GetDestWide(MIR* mir) { 632 RegLocation res = GetRawDest(mir); 633 DCHECK(res.wide); 634 return res; 635 } 636 637 RegLocation GetSrcWide(MIR* mir, int low) { 638 RegLocation res = GetRawSrc(mir, low); 639 DCHECK(res.wide); 640 return res; 641 } 642 643 RegLocation GetBadLoc() { 644 return bad_loc; 645 } 646 647 int GetMethodSReg() const { 648 return method_sreg_; 649 } 650 651 /** 652 * @brief Used to obtain the number of compiler temporaries being used. 653 * @return Returns the number of compiler temporaries. 654 */ 655 size_t GetNumUsedCompilerTemps() const { 656 size_t total_num_temps = compiler_temps_.Size(); 657 DCHECK_LE(num_non_special_compiler_temps_, total_num_temps); 658 return total_num_temps; 659 } 660 661 /** 662 * @brief Used to obtain the number of non-special compiler temporaries being used. 663 * @return Returns the number of non-special compiler temporaries. 664 */ 665 size_t GetNumNonSpecialCompilerTemps() const { 666 return num_non_special_compiler_temps_; 667 } 668 669 /** 670 * @brief Used to set the total number of available non-special compiler temporaries. 671 * @details Can fail setting the new max if there are more temps being used than the new_max. 672 * @param new_max The new maximum number of non-special compiler temporaries. 673 * @return Returns true if the max was set and false if failed to set. 674 */ 675 bool SetMaxAvailableNonSpecialCompilerTemps(size_t new_max) { 676 if (new_max < GetNumNonSpecialCompilerTemps()) { 677 return false; 678 } else { 679 max_available_non_special_compiler_temps_ = new_max; 680 return true; 681 } 682 } 683 684 /** 685 * @brief Provides the number of non-special compiler temps available. 686 * @details Even if this returns zero, special compiler temps are guaranteed to be available. 687 * @return Returns the number of available temps. 688 */ 689 size_t GetNumAvailableNonSpecialCompilerTemps(); 690 691 /** 692 * @brief Used to obtain an existing compiler temporary. 693 * @param index The index of the temporary which must be strictly less than the 694 * number of temporaries. 695 * @return Returns the temporary that was asked for. 696 */ 697 CompilerTemp* GetCompilerTemp(size_t index) const { 698 return compiler_temps_.Get(index); 699 } 700 701 /** 702 * @brief Used to obtain the maximum number of compiler temporaries that can be requested. 703 * @return Returns the maximum number of compiler temporaries, whether used or not. 704 */ 705 size_t GetMaxPossibleCompilerTemps() const { 706 return max_available_special_compiler_temps_ + max_available_non_special_compiler_temps_; 707 } 708 709 /** 710 * @brief Used to obtain a new unique compiler temporary. 711 * @param ct_type Type of compiler temporary requested. 712 * @param wide Whether we should allocate a wide temporary. 713 * @return Returns the newly created compiler temporary. 714 */ 715 CompilerTemp* GetNewCompilerTemp(CompilerTempType ct_type, bool wide); 716 717 bool MethodIsLeaf() { 718 return attributes_ & METHOD_IS_LEAF; 719 } 720 721 RegLocation GetRegLocation(int index) { 722 DCHECK((index >= 0) && (index < num_ssa_regs_)); 723 return reg_location_[index]; 724 } 725 726 RegLocation GetMethodLoc() { 727 return reg_location_[method_sreg_]; 728 } 729 730 bool IsBackedge(BasicBlock* branch_bb, BasicBlockId target_bb_id) { 731 return ((target_bb_id != NullBasicBlockId) && 732 (GetBasicBlock(target_bb_id)->start_offset <= branch_bb->start_offset)); 733 } 734 735 bool IsBackwardsBranch(BasicBlock* branch_bb) { 736 return IsBackedge(branch_bb, branch_bb->taken) || IsBackedge(branch_bb, branch_bb->fall_through); 737 } 738 739 void CountBranch(DexOffset target_offset) { 740 if (target_offset <= current_offset_) { 741 backward_branches_++; 742 } else { 743 forward_branches_++; 744 } 745 } 746 747 int GetBranchCount() { 748 return backward_branches_ + forward_branches_; 749 } 750 751 bool IsPseudoMirOp(Instruction::Code opcode) { 752 return static_cast<int>(opcode) >= static_cast<int>(kMirOpFirst); 753 } 754 755 bool IsPseudoMirOp(int opcode) { 756 return opcode >= static_cast<int>(kMirOpFirst); 757 } 758 759 // Is this vreg in the in set? 760 bool IsInVReg(int vreg) { 761 return (vreg >= cu_->num_regs); 762 } 763 764 void DumpCheckStats(); 765 MIR* FindMoveResult(BasicBlock* bb, MIR* mir); 766 int SRegToVReg(int ssa_reg) const; 767 void VerifyDataflow(); 768 void CheckForDominanceFrontier(BasicBlock* dom_bb, const BasicBlock* succ_bb); 769 void EliminateNullChecksAndInferTypesStart(); 770 bool EliminateNullChecksAndInferTypes(BasicBlock *bb); 771 void EliminateNullChecksAndInferTypesEnd(); 772 bool EliminateClassInitChecksGate(); 773 bool EliminateClassInitChecks(BasicBlock* bb); 774 void EliminateClassInitChecksEnd(); 775 /* 776 * Type inference handling helpers. Because Dalvik's bytecode is not fully typed, 777 * we have to do some work to figure out the sreg type. For some operations it is 778 * clear based on the opcode (i.e. ADD_FLOAT v0, v1, v2), but for others (MOVE), we 779 * may never know the "real" type. 780 * 781 * We perform the type inference operation by using an iterative walk over 782 * the graph, propagating types "defined" by typed opcodes to uses and defs in 783 * non-typed opcodes (such as MOVE). The Setxx(index) helpers are used to set defined 784 * types on typed opcodes (such as ADD_INT). The Setxx(index, is_xx) form is used to 785 * propagate types through non-typed opcodes such as PHI and MOVE. The is_xx flag 786 * tells whether our guess of the type is based on a previously typed definition. 787 * If so, the defined type takes precedence. Note that it's possible to have the same sreg 788 * show multiple defined types because dx treats constants as untyped bit patterns. 789 * The return value of the Setxx() helpers says whether or not the Setxx() action changed 790 * the current guess, and is used to know when to terminate the iterative walk. 791 */ 792 bool SetFp(int index, bool is_fp); 793 bool SetFp(int index); 794 bool SetCore(int index, bool is_core); 795 bool SetCore(int index); 796 bool SetRef(int index, bool is_ref); 797 bool SetRef(int index); 798 bool SetWide(int index, bool is_wide); 799 bool SetWide(int index); 800 bool SetHigh(int index, bool is_high); 801 bool SetHigh(int index); 802 803 char* GetDalvikDisassembly(const MIR* mir); 804 void ReplaceSpecialChars(std::string& str); 805 std::string GetSSAName(int ssa_reg); 806 std::string GetSSANameWithConst(int ssa_reg, bool singles_only); 807 void GetBlockName(BasicBlock* bb, char* name); 808 const char* GetShortyFromTargetIdx(int); 809 void DumpMIRGraph(); 810 CallInfo* NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type, bool is_range); 811 BasicBlock* NewMemBB(BBType block_type, int block_id); 812 MIR* AdvanceMIR(BasicBlock** p_bb, MIR* mir); 813 BasicBlock* NextDominatedBlock(BasicBlock* bb); 814 bool LayoutBlocks(BasicBlock* bb); 815 816 bool InlineCallsGate(); 817 void InlineCallsStart(); 818 void InlineCalls(BasicBlock* bb); 819 void InlineCallsEnd(); 820 821 /** 822 * @brief Perform the initial preparation for the Method Uses. 823 */ 824 void InitializeMethodUses(); 825 826 /** 827 * @brief Perform the initial preparation for the Constant Propagation. 828 */ 829 void InitializeConstantPropagation(); 830 831 /** 832 * @brief Perform the initial preparation for the SSA Transformation. 833 */ 834 void InitializeSSATransformation(); 835 836 /** 837 * @brief Insert a the operands for the Phi nodes. 838 * @param bb the considered BasicBlock. 839 * @return true 840 */ 841 bool InsertPhiNodeOperands(BasicBlock* bb); 842 843 /** 844 * @brief Perform constant propagation on a BasicBlock. 845 * @param bb the considered BasicBlock. 846 */ 847 void DoConstantPropagation(BasicBlock* bb); 848 849 /** 850 * @brief Count the uses in the BasicBlock 851 * @param bb the BasicBlock 852 */ 853 void CountUses(struct BasicBlock* bb); 854 855 /** 856 * @brief Combine BasicBlocks 857 * @param the BasicBlock we are considering 858 */ 859 void CombineBlocks(BasicBlock* bb); 860 861 void ClearAllVisitedFlags(); 862 /* 863 * IsDebugBuild sanity check: keep track of the Dex PCs for catch entries so that later on 864 * we can verify that all catch entries have native PC entries. 865 */ 866 std::set<uint32_t> catches_; 867 868 // TODO: make these private. 869 RegLocation* reg_location_; // Map SSA names to location. 870 SafeMap<unsigned int, unsigned int> block_id_map_; // Block collapse lookup cache. 871 872 static const uint64_t oat_data_flow_attributes_[kMirOpLast]; 873 static const char* extended_mir_op_names_[kMirOpLast - kMirOpFirst]; 874 static const uint32_t analysis_attributes_[kMirOpLast]; 875 876 private: 877 int FindCommonParent(int block1, int block2); 878 void ComputeSuccLineIn(ArenaBitVector* dest, const ArenaBitVector* src1, 879 const ArenaBitVector* src2); 880 void HandleLiveInUse(ArenaBitVector* use_v, ArenaBitVector* def_v, 881 ArenaBitVector* live_in_v, int dalvik_reg_id); 882 void HandleDef(ArenaBitVector* def_v, int dalvik_reg_id); 883 void CompilerInitializeSSAConversion(); 884 bool DoSSAConversion(BasicBlock* bb); 885 bool InvokeUsesMethodStar(MIR* mir); 886 int ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction); 887 bool ContentIsInsn(const uint16_t* code_ptr); 888 BasicBlock* SplitBlock(DexOffset code_offset, BasicBlock* orig_block, 889 BasicBlock** immed_pred_block_p); 890 BasicBlock* FindBlock(DexOffset code_offset, bool split, bool create, 891 BasicBlock** immed_pred_block_p); 892 void ProcessTryCatchBlocks(); 893 BasicBlock* ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset, int width, 894 int flags, const uint16_t* code_ptr, const uint16_t* code_end); 895 BasicBlock* ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset, int width, 896 int flags); 897 BasicBlock* ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset, int width, 898 int flags, ArenaBitVector* try_block_addr, const uint16_t* code_ptr, 899 const uint16_t* code_end); 900 int AddNewSReg(int v_reg); 901 void HandleSSAUse(int* uses, int dalvik_reg, int reg_index); 902 void HandleSSADef(int* defs, int dalvik_reg, int reg_index); 903 void DataFlowSSAFormat35C(MIR* mir); 904 void DataFlowSSAFormat3RC(MIR* mir); 905 bool FindLocalLiveIn(BasicBlock* bb); 906 bool InferTypeAndSize(BasicBlock* bb, MIR* mir, bool changed); 907 bool VerifyPredInfo(BasicBlock* bb); 908 BasicBlock* NeedsVisit(BasicBlock* bb); 909 BasicBlock* NextUnvisitedSuccessor(BasicBlock* bb); 910 void MarkPreOrder(BasicBlock* bb); 911 void RecordDFSOrders(BasicBlock* bb); 912 void ComputeDFSOrders(); 913 void ComputeDefBlockMatrix(); 914 void ComputeDomPostOrderTraversal(BasicBlock* bb); 915 void ComputeDominators(); 916 void InsertPhiNodes(); 917 void DoDFSPreOrderSSARename(BasicBlock* block); 918 void SetConstant(int32_t ssa_reg, int value); 919 void SetConstantWide(int ssa_reg, int64_t value); 920 int GetSSAUseCount(int s_reg); 921 bool BasicBlockOpt(BasicBlock* bb); 922 bool BuildExtendedBBList(struct BasicBlock* bb); 923 bool FillDefBlockMatrix(BasicBlock* bb); 924 void InitializeDominationInfo(BasicBlock* bb); 925 bool ComputeblockIDom(BasicBlock* bb); 926 bool ComputeBlockDominators(BasicBlock* bb); 927 bool SetDominators(BasicBlock* bb); 928 bool ComputeBlockLiveIns(BasicBlock* bb); 929 bool ComputeDominanceFrontier(BasicBlock* bb); 930 931 void CountChecks(BasicBlock* bb); 932 void AnalyzeBlock(BasicBlock* bb, struct MethodStats* stats); 933 bool ComputeSkipCompilation(struct MethodStats* stats, bool skip_default); 934 935 CompilationUnit* const cu_; 936 GrowableArray<int>* ssa_base_vregs_; 937 GrowableArray<int>* ssa_subscripts_; 938 // Map original Dalvik virtual reg i to the current SSA name. 939 int* vreg_to_ssa_map_; // length == method->registers_size 940 int* ssa_last_defs_; // length == method->registers_size 941 ArenaBitVector* is_constant_v_; // length == num_ssa_reg 942 int* constant_values_; // length == num_ssa_reg 943 // Use counts of ssa names. 944 GrowableArray<uint32_t> use_counts_; // Weighted by nesting depth 945 GrowableArray<uint32_t> raw_use_counts_; // Not weighted 946 unsigned int num_reachable_blocks_; 947 GrowableArray<BasicBlockId>* dfs_order_; 948 GrowableArray<BasicBlockId>* dfs_post_order_; 949 GrowableArray<BasicBlockId>* dom_post_order_traversal_; 950 int* i_dom_list_; 951 ArenaBitVector** def_block_matrix_; // num_dalvik_register x num_blocks. 952 ArenaBitVector* temp_dalvik_register_v_; 953 UniquePtr<ScopedArenaAllocator> temp_scoped_alloc_; 954 uint16_t* temp_insn_data_; 955 uint32_t temp_bit_vector_size_; 956 ArenaBitVector* temp_bit_vector_; 957 static const int kInvalidEntry = -1; 958 GrowableArray<BasicBlock*> block_list_; 959 ArenaBitVector* try_block_addr_; 960 BasicBlock* entry_block_; 961 BasicBlock* exit_block_; 962 int num_blocks_; 963 const DexFile::CodeItem* current_code_item_; 964 GrowableArray<uint16_t> dex_pc_to_block_map_; // FindBlock lookup cache. 965 std::vector<DexCompilationUnit*> m_units_; // List of methods included in this graph 966 typedef std::pair<int, int> MIRLocation; // Insert point, (m_unit_ index, offset) 967 std::vector<MIRLocation> method_stack_; // Include stack 968 int current_method_; 969 DexOffset current_offset_; // Offset in code units 970 int def_count_; // Used to estimate size of ssa name storage. 971 int* opcode_count_; // Dex opcode coverage stats. 972 int num_ssa_regs_; // Number of names following SSA transformation. 973 std::vector<BasicBlockId> extended_basic_blocks_; // Heads of block "traces". 974 int method_sreg_; 975 unsigned int attributes_; 976 Checkstats* checkstats_; 977 ArenaAllocator* arena_; 978 int backward_branches_; 979 int forward_branches_; 980 GrowableArray<CompilerTemp*> compiler_temps_; 981 size_t num_non_special_compiler_temps_; 982 size_t max_available_non_special_compiler_temps_; 983 size_t max_available_special_compiler_temps_; 984 bool punt_to_interpreter_; // Difficult or not worthwhile - just interpret. 985 uint64_t merged_df_flags_; 986 GrowableArray<MirIFieldLoweringInfo> ifield_lowering_infos_; 987 GrowableArray<MirSFieldLoweringInfo> sfield_lowering_infos_; 988 GrowableArray<MirMethodLoweringInfo> method_lowering_infos_; 989 990 friend class ClassInitCheckEliminationTest; 991 friend class LocalValueNumberingTest; 992}; 993 994} // namespace art 995 996#endif // ART_COMPILER_DEX_MIR_GRAPH_H_ 997