blob: 72ad1e698c626c2a0ff0fb41725757fb13e54afd [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
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
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070023#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080025#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070026#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010027#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000028#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000030#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070031#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010033#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000034
buzbee311ca162013-02-28 15:56:43 -080035namespace art {
36
37#define MAX_PATTERN_LEN 5
38
buzbee1fd33462013-03-25 13:40:45 -070039const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
40 "Phi",
41 "Copy",
42 "FusedCmplFloat",
43 "FusedCmpgFloat",
44 "FusedCmplDouble",
45 "FusedCmpgDouble",
46 "FusedCmpLong",
47 "Nop",
48 "OpNullCheck",
49 "OpRangeCheck",
50 "OpDivZeroCheck",
51 "Check1",
52 "Check2",
53 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040054 "ConstVector",
55 "MoveVector",
56 "PackedMultiply",
57 "PackedAddition",
58 "PackedSubtract",
59 "PackedShiftLeft",
60 "PackedSignedShiftRight",
61 "PackedUnsignedShiftRight",
62 "PackedAnd",
63 "PackedOr",
64 "PackedXor",
65 "PackedAddReduce",
66 "PackedReduce",
67 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070068 "ReserveVectorRegisters",
69 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070070 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070071 "PackedArrayGet",
72 "PackedArrayPut",
Ningsheng Jiana262f772014-11-25 16:48:07 +080073 "MaddInt",
74 "MsubInt",
75 "MaddLong",
76 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070077};
78
buzbee862a7602013-04-05 10:58:54 -070079MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070080 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010081 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070082 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010083 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
84 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
buzbee311ca162013-02-28 15:56:43 -080085 is_constant_v_(NULL),
86 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010087 use_counts_(arena->Adapter()),
88 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080089 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070090 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010091 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000092 domination_up_to_date_(false),
93 mir_ssa_rep_up_to_date_(false),
94 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010095 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
96 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
97 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
98 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
99 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
100 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
101 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100102 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -0800103 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000104 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100105 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800106 try_block_addr_(NULL),
107 entry_block_(NULL),
108 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800109 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100110 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100111 m_units_(arena->Adapter()),
112 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800113 current_method_(kInvalidEntry),
114 current_offset_(kInvalidEntry),
115 def_count_(0),
116 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700117 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100118 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700119 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700120 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
121 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700122 arena_(arena),
123 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800124 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800125 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700126 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
127 requested_backend_temp_(false),
128 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000129 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000130 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100131 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
132 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
133 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
Vladimir Marko8b858e12014-11-27 14:52:37 +0000134 suspend_checks_in_loops_(nullptr) {
Vladimir Markof585e542014-11-21 13:41:32 +0000135 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100136 use_counts_.reserve(256);
137 raw_use_counts_.reserve(256);
138 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700139 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700140
141
142 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
143 // X86 requires a temp to keep track of the method address.
144 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
145 // this needs to be updated to reserve 0 temps for BE.
146 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
147 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
148 } else {
149 // Other architectures do not have a known lower bound for non-special temps.
150 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
151 max_available_non_special_compiler_temps_ = 0;
152 reserved_temps_for_backend_ = 0;
153 }
buzbee311ca162013-02-28 15:56:43 -0800154}
155
Ian Rogers6282dc12013-04-18 15:54:02 -0700156MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100157 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700158 STLDeleteElements(&m_units_);
159}
160
buzbee311ca162013-02-28 15:56:43 -0800161/*
162 * Parse an instruction, return the length of the instruction
163 */
Ian Rogers29a26482014-05-02 15:27:29 -0700164int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
165 const Instruction* inst = Instruction::At(code_ptr);
166 decoded_instruction->opcode = inst->Opcode();
167 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
168 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
169 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
170 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
171 if (inst->HasVarArgs()) {
172 inst->GetVarArgs(decoded_instruction->arg);
173 }
174 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800175}
176
177
178/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700179BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700180 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700181 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800182 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400183 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800184 while (insn) {
185 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700186 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800187 insn = insn->next;
188 }
189 if (insn == NULL) {
190 LOG(FATAL) << "Break split failed";
191 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400192 // Now insn is at the instruction where we want to split, namely
193 // insn will be the first instruction of the "bottom" block.
194 // Similarly, prev will be the last instruction of the "top" block
195
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100196 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800197
198 bottom_block->start_offset = code_offset;
199 bottom_block->first_mir_insn = insn;
200 bottom_block->last_mir_insn = orig_block->last_mir_insn;
201
Junmo Park90223cc2014-08-04 18:51:21 +0900202 /* If this block was terminated by a return, conditional branch or throw,
203 * the flag needs to go with the bottom block
204 */
buzbee311ca162013-02-28 15:56:43 -0800205 bottom_block->terminated_by_return = orig_block->terminated_by_return;
206 orig_block->terminated_by_return = false;
207
Junmo Park90223cc2014-08-04 18:51:21 +0900208 bottom_block->conditional_branch = orig_block->conditional_branch;
209 orig_block->conditional_branch = false;
210
211 bottom_block->explicit_throw = orig_block->explicit_throw;
212 orig_block->explicit_throw = false;
213
buzbee311ca162013-02-28 15:56:43 -0800214 /* Handle the taken path */
215 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700216 if (bottom_block->taken != NullBasicBlockId) {
217 orig_block->taken = NullBasicBlockId;
218 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100219 bb_taken->ErasePredecessor(orig_block->id);
220 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800221 }
222
223 /* Handle the fallthrough path */
224 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700225 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100226 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700227 if (bottom_block->fall_through != NullBasicBlockId) {
228 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100229 bb_fall_through->ErasePredecessor(orig_block->id);
230 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800231 }
232
233 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700234 if (orig_block->successor_block_list_type != kNotUsed) {
235 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100236 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700237 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100238 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
239 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700240 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700241 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100242 bb->ErasePredecessor(orig_block->id);
243 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700244 }
buzbee311ca162013-02-28 15:56:43 -0800245 }
246 }
247
buzbee0d829482013-10-11 15:24:55 -0700248 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700249 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800250
buzbee311ca162013-02-28 15:56:43 -0800251 /*
252 * Update the immediate predecessor block pointer so that outgoing edges
253 * can be applied to the proper block.
254 */
255 if (immed_pred_block_p) {
256 DCHECK_EQ(*immed_pred_block_p, orig_block);
257 *immed_pred_block_p = bottom_block;
258 }
buzbeeb48819d2013-09-14 16:15:25 -0700259
260 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000261 DCHECK(insn != nullptr);
262 DCHECK(insn != orig_block->first_mir_insn);
263 DCHECK(insn == bottom_block->first_mir_insn);
264 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100265 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400266 // Scan the "bottom" instructions, remapping them to the
267 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000268 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400269 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100270 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000271 while (p != bottom_block->last_mir_insn) {
272 p = p->next;
273 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700274 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700275 int opcode = p->dalvikInsn.opcode;
276 /*
277 * Some messiness here to ensure that we only enter real opcodes and only the
278 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000279 * CHECK and work portions. Since the 2nd half of a split operation is always
280 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700281 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700282 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400283 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
284 // At first glance the instructions should all be mapped to orig_block.
285 // However, multiple instructions may correspond to the same dex, hence an earlier
286 // instruction may have already moved the mapping for dex to bottom_block.
287 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100288 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700289 }
buzbeeb48819d2013-09-14 16:15:25 -0700290 }
291
buzbee311ca162013-02-28 15:56:43 -0800292 return bottom_block;
293}
294
295/*
296 * Given a code offset, find out the block that starts with it. If the offset
297 * is in the middle of an existing block, split it into two. If immed_pred_block_p
298 * is not non-null and is the block being split, update *immed_pred_block_p to
299 * point to the bottom block so that outgoing edges can be set up properly
300 * (by the caller)
301 * Utilizes a map for fast lookup of the typical cases.
302 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700303BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700304 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700305 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700306 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800307 }
buzbeeb48819d2013-09-14 16:15:25 -0700308
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100309 int block_id = dex_pc_to_block_map_[code_offset];
310 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700311
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700312 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700313 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700314 return bb;
315 }
buzbee311ca162013-02-28 15:56:43 -0800316
buzbeeb48819d2013-09-14 16:15:25 -0700317 // No direct hit.
318 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700319 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800320 }
321
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700322 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700323 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700324 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700325 }
326
327 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100328 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800329 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100330 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800331 return bb;
332}
333
buzbeeb48819d2013-09-14 16:15:25 -0700334
buzbee311ca162013-02-28 15:56:43 -0800335/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700336void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800337 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700338 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800339
340 if (tries_size == 0) {
341 return;
342 }
343
344 for (int i = 0; i < tries_size; i++) {
345 const DexFile::TryItem* pTry =
346 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700347 DexOffset start_offset = pTry->start_addr_;
348 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800349 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700350 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800351 }
352 }
353
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700354 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700355 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800356 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
357 for (uint32_t idx = 0; idx < handlers_size; idx++) {
358 CatchHandlerIterator iterator(handlers_ptr);
359 for (; iterator.HasNext(); iterator.Next()) {
360 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700361 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800362 }
363 handlers_ptr = iterator.EndDataPointer();
364 }
365}
366
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100367bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
368 NarrowDexOffset catch_offset) {
369 // Catches for monitor-exit during stack unwinding have the pattern
370 // move-exception (move)* (goto)? monitor-exit throw
371 // In the currently generated dex bytecode we see these catching a bytecode range including
372 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
373 // it's the case for a given monitor-exit and catch block so that we can ignore it.
374 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
375 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
376 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700377 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100378 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
379 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700380 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100381 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
382 if (check_insn->VRegA_11x() == monitor_reg) {
383 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
384 return false;
385 }
386 check_insn = check_insn->Next();
387 while (true) {
388 int dest = -1;
389 bool wide = false;
390 switch (check_insn->Opcode()) {
391 case Instruction::MOVE_WIDE:
392 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700393 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100394 case Instruction::MOVE_OBJECT:
395 case Instruction::MOVE:
396 dest = check_insn->VRegA_12x();
397 break;
398
399 case Instruction::MOVE_WIDE_FROM16:
400 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700401 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100402 case Instruction::MOVE_OBJECT_FROM16:
403 case Instruction::MOVE_FROM16:
404 dest = check_insn->VRegA_22x();
405 break;
406
407 case Instruction::MOVE_WIDE_16:
408 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700409 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100410 case Instruction::MOVE_OBJECT_16:
411 case Instruction::MOVE_16:
412 dest = check_insn->VRegA_32x();
413 break;
414
415 case Instruction::GOTO:
416 case Instruction::GOTO_16:
417 case Instruction::GOTO_32:
418 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700419 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100420 default:
421 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
422 check_insn->VRegA_11x() == monitor_reg;
423 }
424
425 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
426 return false;
427 }
428
429 check_insn = check_insn->Next();
430 }
431}
432
buzbee311ca162013-02-28 15:56:43 -0800433/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700434BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
435 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700436 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700437 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800438 switch (insn->dalvikInsn.opcode) {
439 case Instruction::GOTO:
440 case Instruction::GOTO_16:
441 case Instruction::GOTO_32:
442 target += insn->dalvikInsn.vA;
443 break;
444 case Instruction::IF_EQ:
445 case Instruction::IF_NE:
446 case Instruction::IF_LT:
447 case Instruction::IF_GE:
448 case Instruction::IF_GT:
449 case Instruction::IF_LE:
450 cur_block->conditional_branch = true;
451 target += insn->dalvikInsn.vC;
452 break;
453 case Instruction::IF_EQZ:
454 case Instruction::IF_NEZ:
455 case Instruction::IF_LTZ:
456 case Instruction::IF_GEZ:
457 case Instruction::IF_GTZ:
458 case Instruction::IF_LEZ:
459 cur_block->conditional_branch = true;
460 target += insn->dalvikInsn.vB;
461 break;
462 default:
463 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
464 }
buzbeeb48819d2013-09-14 16:15:25 -0700465 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700466 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800467 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700468 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100469 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800470
471 /* Always terminate the current block for conditional branches */
472 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700473 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800474 /* create */
475 true,
476 /* immed_pred_block_p */
477 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700478 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100479 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800480 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700481 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800482 }
483 return cur_block;
484}
485
486/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800487BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
488 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700489 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800490 const uint16_t* switch_data =
491 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
492 int size;
493 const int* keyTable;
494 const int* target_table;
495 int i;
496 int first_key;
497
498 /*
499 * Packed switch data format:
500 * ushort ident = 0x0100 magic value
501 * ushort size number of entries in the table
502 * int first_key first (and lowest) switch case value
503 * int targets[size] branch targets, relative to switch opcode
504 *
505 * Total size is (4+size*2) 16-bit code units.
506 */
507 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
508 DCHECK_EQ(static_cast<int>(switch_data[0]),
509 static_cast<int>(Instruction::kPackedSwitchSignature));
510 size = switch_data[1];
511 first_key = switch_data[2] | (switch_data[3] << 16);
512 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700513 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800514 /*
515 * Sparse switch data format:
516 * ushort ident = 0x0200 magic value
517 * ushort size number of entries in the table; > 0
518 * int keys[size] keys, sorted low-to-high; 32-bit aligned
519 * int targets[size] branch targets, relative to switch opcode
520 *
521 * Total size is (2+size*4) 16-bit code units.
522 */
523 } else {
524 DCHECK_EQ(static_cast<int>(switch_data[0]),
525 static_cast<int>(Instruction::kSparseSwitchSignature));
526 size = switch_data[1];
527 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
528 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700529 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800530 }
531
buzbee0d829482013-10-11 15:24:55 -0700532 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800533 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700534 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800535 }
buzbee0d829482013-10-11 15:24:55 -0700536 cur_block->successor_block_list_type =
537 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100538 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800539
540 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700541 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
542 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700543 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700544 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000545 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700546 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800547 successor_block_info->key =
548 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
549 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100550 cur_block->successor_blocks.push_back(successor_block_info);
551 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800552 }
553
554 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700555 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
556 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700557 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100558 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800559 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800560}
561
562/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700563BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
564 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700565 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700566 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700567 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800568 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800569
570 /* In try block */
571 if (in_try_block) {
572 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
573
buzbee0d829482013-10-11 15:24:55 -0700574 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800575 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
576 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700577 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800578 }
579
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700580 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700581 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
582 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100583 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
584 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
585 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
586 continue;
587 }
588 if (cur_block->successor_block_list_type == kNotUsed) {
589 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100590 }
buzbee311ca162013-02-28 15:56:43 -0800591 catch_block->catch_entry = true;
592 if (kIsDebugBuild) {
593 catches_.insert(catch_block->start_offset);
594 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700595 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000596 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700597 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800598 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100599 cur_block->successor_blocks.push_back(successor_block_info);
600 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800601 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100602 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
603 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100604 bool build_all_edges =
605 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100606 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100607 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700608 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800609 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100610 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800611 }
612
buzbee17189ac2013-11-08 11:07:02 -0800613 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800614 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700615 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700616 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700617 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800618 }
619 if (!in_try_block) {
620 // Don't split a THROW that can't rethrow - we're done.
621 return cur_block;
622 }
623 }
624
buzbee17189ac2013-11-08 11:07:02 -0800625 if (!build_all_edges) {
626 /*
627 * Even though there is an exception edge here, control cannot return to this
628 * method. Thus, for the purposes of dataflow analysis and optimization, we can
629 * ignore the edge. Doing this reduces compile time, and increases the scope
630 * of the basic-block level optimization pass.
631 */
632 return cur_block;
633 }
634
buzbee311ca162013-02-28 15:56:43 -0800635 /*
636 * Split the potentially-throwing instruction into two parts.
637 * The first half will be a pseudo-op that captures the exception
638 * edges and terminates the basic block. It always falls through.
639 * Then, create a new basic block that begins with the throwing instruction
640 * (minus exceptions). Note: this new basic block must NOT be entered into
641 * the block_map. If the potentially-throwing instruction is the target of a
642 * future branch, we need to find the check psuedo half. The new
643 * basic block containing the work portion of the instruction should
644 * only be entered via fallthrough from the block containing the
645 * pseudo exception edge MIR. Note also that this new block is
646 * not automatically terminated after the work portion, and may
647 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700648 *
649 * Note also that the dex_pc_to_block_map_ entry for the potentially
650 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800651 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100652 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800653 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700654 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100655 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700656 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800657 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700658 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700659 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800660 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700661 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800662 return new_block;
663}
664
665/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
666void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700667 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700668 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800669 current_code_item_ = code_item;
670 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
671 current_method_ = m_units_.size();
672 current_offset_ = 0;
673 // TODO: will need to snapshot stack image and use that as the mir context identification.
674 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000675 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
676 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800677 const uint16_t* code_ptr = current_code_item_->insns_;
678 const uint16_t* code_end =
679 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
680
681 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700682 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100683 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
684 dex_pc_to_block_map_.resize(dex_pc_to_block_map_.size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700685
buzbee311ca162013-02-28 15:56:43 -0800686 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700687 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
688 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800689
690 // If this is the first method, set up default entry and exit blocks.
691 if (current_method_ == 0) {
692 DCHECK(entry_block_ == NULL);
693 DCHECK(exit_block_ == NULL);
Vladimir Markoffda4992014-12-18 17:05:58 +0000694 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700695 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100696 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700697 DCHECK_EQ(null_block->id, NullBasicBlockId);
698 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100699 entry_block_ = CreateNewBB(kEntryBlock);
700 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800701 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
702 cu_->dex_file = &dex_file;
703 cu_->class_def_idx = class_def_idx;
704 cu_->method_idx = method_idx;
705 cu_->access_flags = access_flags;
706 cu_->invoke_type = invoke_type;
707 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800708 } else {
709 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
710 /*
711 * Will need to manage storage for ins & outs, push prevous state and update
712 * insert point.
713 */
714 }
715
716 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100717 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700718 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800719 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700720 // TODO: for inlining support, insert at the insert point rather than entry block.
721 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100722 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800723
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000724 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800725 ProcessTryCatchBlocks();
726
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000727 uint64_t merged_df_flags = 0u;
728
buzbee311ca162013-02-28 15:56:43 -0800729 /* Parse all instructions and put them into containing basic blocks */
730 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700731 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800732 insn->offset = current_offset_;
733 insn->m_unit_index = current_method_;
734 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800735 Instruction::Code opcode = insn->dalvikInsn.opcode;
736 if (opcode_count_ != NULL) {
737 opcode_count_[static_cast<int>(opcode)]++;
738 }
739
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700740 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800741 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800742
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700743 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000744 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800745
746 if (df_flags & DF_HAS_DEFS) {
747 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
748 }
749
buzbee1da1e2f2013-11-15 13:37:01 -0800750 if (df_flags & DF_LVN) {
751 cur_block->use_lvn = true; // Run local value numbering on this basic block.
752 }
753
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700754 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700755 if (opcode == Instruction::NOP) {
756 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
757 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
758 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
759 uint16_t following_raw_instruction = code_ptr[1];
760 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
761 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
762 (following_raw_instruction == Instruction::kArrayDataSignature)) {
763 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
764 }
765 }
766 if (width == 1) {
767 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700768 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700769 } else {
buzbee0d829482013-10-11 15:24:55 -0700770 DCHECK(cur_block->fall_through == NullBasicBlockId);
771 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800772 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700773 flags &= ~Instruction::kContinue;
buzbee6489d222014-11-25 10:52:19 -0800774 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee27247762013-07-28 12:03:58 -0700775 }
776 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700777 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700778 }
779
buzbeeb48819d2013-09-14 16:15:25 -0700780 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100781 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700782
buzbee27247762013-07-28 12:03:58 -0700783 code_ptr += width;
784
buzbee311ca162013-02-28 15:56:43 -0800785 if (flags & Instruction::kBranch) {
786 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
787 width, flags, code_ptr, code_end);
788 } else if (flags & Instruction::kReturn) {
789 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700790 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100791 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800792 /*
793 * Terminate the current block if there are instructions
794 * afterwards.
795 */
796 if (code_ptr < code_end) {
797 /*
798 * Create a fallthrough block for real instructions
799 * (incl. NOP).
800 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700801 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800802 }
803 } else if (flags & Instruction::kThrow) {
804 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
805 code_ptr, code_end);
806 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800807 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800808 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700809 if (verify_flags & Instruction::kVerifyVarArgRange ||
810 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800811 /*
812 * The Quick backend's runtime model includes a gap between a method's
813 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
814 * which spans the gap is somewhat complicated, and should not happen
815 * in normal usage of dx. Punt to the interpreter.
816 */
817 int first_reg_in_range = insn->dalvikInsn.vC;
818 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
819 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
820 punt_to_interpreter_ = true;
821 }
822 }
buzbee311ca162013-02-28 15:56:43 -0800823 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700824 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
825 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800826 if (next_block) {
827 /*
828 * The next instruction could be the target of a previously parsed
829 * forward branch so a block is already created. If the current
830 * instruction is not an unconditional branch, connect them through
831 * the fall-through link.
832 */
buzbee0d829482013-10-11 15:24:55 -0700833 DCHECK(cur_block->fall_through == NullBasicBlockId ||
834 GetBasicBlock(cur_block->fall_through) == next_block ||
835 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800836
buzbee0d829482013-10-11 15:24:55 -0700837 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
838 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100839 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800840 }
841 cur_block = next_block;
842 }
843 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000844 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000845
buzbee311ca162013-02-28 15:56:43 -0800846 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
847 DumpCFG("/sdcard/1_post_parse_cfg/", true);
848 }
849
850 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700851 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800852 }
853}
854
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700855void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800856 DCHECK(opcode_count_ != NULL);
857 LOG(INFO) << "Opcode Count";
858 for (int i = 0; i < kNumPackedOpcodes; i++) {
859 if (opcode_count_[i] != 0) {
860 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
861 << " " << opcode_count_[i];
862 }
863 }
864}
865
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700866uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
867 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
868 return oat_data_flow_attributes_[opcode];
869}
870
871uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
872 DCHECK(mir != nullptr);
873 Instruction::Code opcode = mir->dalvikInsn.opcode;
874 return GetDataFlowAttributes(opcode);
875}
876
buzbee311ca162013-02-28 15:56:43 -0800877// TODO: use a configurable base prefix, and adjust callers to supply pass name.
878/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800879void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800880 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700881 static AtomicInteger cnt(0);
882
883 // Increment counter to get a unique file number.
884 cnt++;
885
buzbee311ca162013-02-28 15:56:43 -0800886 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
887 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700888 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800889 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700890 suffix == nullptr ? "" : suffix,
891 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800892 file = fopen(fname.c_str(), "w");
893 if (file == NULL) {
894 return;
895 }
896 fprintf(file, "digraph G {\n");
897
898 fprintf(file, " rankdir=TB\n");
899
900 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
901 int idx;
902
903 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100904 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700905 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700906 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800907 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700908 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800909 if (bb->block_type == kEntryBlock) {
910 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
911 } else if (bb->block_type == kExitBlock) {
912 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
913 } else if (bb->block_type == kDalvikByteCode) {
914 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
915 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700916 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800917 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
918 bb->first_mir_insn ? " | " : " ");
919 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
920 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800921 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400922 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700923 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
924 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400925 extended_mir_op_names_[opcode - kMirOpFirst],
926 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
927 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700928 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700929 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700930 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100931 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
932 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800933 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400934 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800935 }
936 fprintf(file, " }\"];\n\n");
937 } else if (bb->block_type == kExceptionHandling) {
938 char block_name[BLOCK_NAME_LEN];
939
940 GetBlockName(bb, block_name);
941 fprintf(file, " %s [shape=invhouse];\n", block_name);
942 }
943
944 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
945
buzbee0d829482013-10-11 15:24:55 -0700946 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800947 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700948 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800949 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
950 block_name1, block_name2);
951 }
buzbee0d829482013-10-11 15:24:55 -0700952 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800953 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700954 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800955 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
956 }
957
buzbee0d829482013-10-11 15:24:55 -0700958 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800959 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
960 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700961 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800962
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100963 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800964 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100965 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700966 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800967 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100968 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800969 successor_block_info->key,
970 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100971 (succ_id != last_succ_id) ? " | " : " ");
972 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800973 }
974 fprintf(file, " }\"];\n\n");
975
976 GetBlockName(bb, block_name1);
977 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
978 block_name1, bb->start_offset, bb->id);
979
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700980 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700981 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100982 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700983 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800984
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700985 GetBlockName(dest_block, block_name2);
986 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
987 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800988 }
989 }
990 fprintf(file, "\n");
991
992 if (cu_->verbose) {
993 /* Display the dominator tree */
994 GetBlockName(bb, block_name1);
995 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
996 block_name1, block_name1);
997 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700998 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800999 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1000 }
1001 }
1002 }
1003 fprintf(file, "}\n");
1004 fclose(file);
1005}
1006
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001007/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001008void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001009 // Insert it after the last MIR.
1010 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001011}
1012
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001013void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1014 // Insert it after the last MIR.
1015 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1016}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001017
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001018void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1019 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1020 MIR* new_mir = *it;
1021
1022 // Add a copy of each MIR.
1023 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1024 }
buzbee1fd33462013-03-25 13:40:45 -07001025}
1026
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001027/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001028void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001029 InsertMIRListAfter(current_mir, new_mir, new_mir);
1030}
buzbee1fd33462013-03-25 13:40:45 -07001031
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001032void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1033 // If no MIR, we are done.
1034 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1035 return;
buzbee1fd33462013-03-25 13:40:45 -07001036 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001037
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001038 // If insert_after is null, assume BB is empty.
1039 if (insert_after == nullptr) {
1040 first_mir_insn = first_list_mir;
1041 last_mir_insn = last_list_mir;
1042 last_list_mir->next = nullptr;
1043 } else {
1044 MIR* after_list = insert_after->next;
1045 insert_after->next = first_list_mir;
1046 last_list_mir->next = after_list;
1047 if (after_list == nullptr) {
1048 last_mir_insn = last_list_mir;
1049 }
1050 }
1051
1052 // Set this BB to be the basic block of the MIRs.
1053 MIR* last = last_list_mir->next;
1054 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1055 mir->bb = id;
1056 }
1057}
1058
1059/* Insert an MIR instruction to the head of a basic block. */
1060void BasicBlock::PrependMIR(MIR* mir) {
1061 InsertMIRListBefore(first_mir_insn, mir, mir);
1062}
1063
1064void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1065 // Insert it before the first MIR.
1066 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1067}
1068
1069void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1070 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1071 MIR* mir = *it;
1072
1073 InsertMIRListBefore(first_mir_insn, mir, mir);
1074 }
1075}
1076
1077/* Insert a MIR instruction before the specified MIR. */
1078void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1079 // Insert as a single element list.
1080 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001081}
1082
1083MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1084 MIR* current = first_mir_insn;
1085
1086 while (current != nullptr) {
1087 MIR* next = current->next;
1088
1089 if (next == mir) {
1090 return current;
1091 }
1092
1093 current = next;
1094 }
1095
1096 return nullptr;
1097}
1098
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001099void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1100 // If no MIR, we are done.
1101 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1102 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001103 }
1104
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001105 // If insert_before is null, assume BB is empty.
1106 if (insert_before == nullptr) {
1107 first_mir_insn = first_list_mir;
1108 last_mir_insn = last_list_mir;
1109 last_list_mir->next = nullptr;
1110 } else {
1111 if (first_mir_insn == insert_before) {
1112 last_list_mir->next = first_mir_insn;
1113 first_mir_insn = first_list_mir;
1114 } else {
1115 // Find the preceding MIR.
1116 MIR* before_list = FindPreviousMIR(insert_before);
1117 DCHECK(before_list != nullptr);
1118 before_list->next = first_list_mir;
1119 last_list_mir->next = insert_before;
1120 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001121 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001122
1123 // Set this BB to be the basic block of the MIRs.
1124 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1125 mir->bb = id;
1126 }
1127}
1128
1129bool BasicBlock::RemoveMIR(MIR* mir) {
1130 // Remove as a single element list.
1131 return RemoveMIRList(mir, mir);
1132}
1133
1134bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1135 if (first_list_mir == nullptr) {
1136 return false;
1137 }
1138
1139 // Try to find the MIR.
1140 MIR* before_list = nullptr;
1141 MIR* after_list = nullptr;
1142
1143 // If we are removing from the beginning of the MIR list.
1144 if (first_mir_insn == first_list_mir) {
1145 before_list = nullptr;
1146 } else {
1147 before_list = FindPreviousMIR(first_list_mir);
1148 if (before_list == nullptr) {
1149 // We did not find the mir.
1150 return false;
1151 }
1152 }
1153
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001154 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001155 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001156 mir->bb = NullBasicBlockId;
1157 }
1158
1159 after_list = last_list_mir->next;
1160
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001161 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001162 if (before_list == nullptr) {
1163 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001164 } else {
1165 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001166 }
1167
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001168 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001169 if (after_list == nullptr) {
1170 last_mir_insn = before_list;
1171 }
1172
1173 return true;
buzbee1fd33462013-03-25 13:40:45 -07001174}
1175
Vladimir Marko26e7d452014-11-24 14:09:46 +00001176MIR* BasicBlock::GetFirstNonPhiInsn() {
1177 MIR* mir = first_mir_insn;
1178 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1179 mir = mir->next;
1180 }
1181 return mir;
1182}
1183
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001184MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001185 MIR* next_mir = nullptr;
1186
1187 if (current != nullptr) {
1188 next_mir = current->next;
1189 }
1190
1191 if (next_mir == nullptr) {
1192 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001193 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1194 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001195 }
1196 }
1197
1198 return next_mir;
1199}
1200
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001201static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1202 DCHECK(decoded_mir != nullptr);
1203 OpSize type = static_cast<OpSize>(type_size >> 16);
1204 uint16_t vect_size = (type_size & 0xFFFF);
1205
1206 // Now print the type and vector size.
1207 std::stringstream ss;
1208 ss << " (type:";
1209 ss << type;
1210 ss << " vectsize:";
1211 ss << vect_size;
1212 ss << ")";
1213
1214 decoded_mir->append(ss.str());
1215}
1216
1217void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1218 DCHECK(decoded_mir != nullptr);
1219 int opcode = mir->dalvikInsn.opcode;
1220 SSARepresentation* ssa_rep = mir->ssa_rep;
1221 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1222 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1223
Vladimirf41b92c2014-10-13 13:41:38 +07001224 if (opcode < kMirOpFirst) {
1225 return; // It is not an extended instruction.
1226 }
1227
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001228 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1229
1230 switch (opcode) {
1231 case kMirOpPhi: {
1232 if (defs > 0 && uses > 0) {
1233 BasicBlockId* incoming = mir->meta.phi_incoming;
1234 decoded_mir->append(StringPrintf(" %s = (%s",
1235 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1236 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1237 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1238 for (int i = 1; i < uses; i++) {
1239 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1240 }
1241 decoded_mir->append(")");
1242 }
1243 break;
1244 }
1245 case kMirOpCopy:
1246 if (ssa_rep != nullptr) {
1247 decoded_mir->append(" ");
1248 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1249 if (defs > 1) {
1250 decoded_mir->append(", ");
1251 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1252 }
1253 decoded_mir->append(" = ");
1254 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1255 if (uses > 1) {
1256 decoded_mir->append(", ");
1257 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1258 }
1259 } else {
1260 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1261 }
1262 break;
1263 case kMirOpFusedCmplFloat:
1264 case kMirOpFusedCmpgFloat:
1265 case kMirOpFusedCmplDouble:
1266 case kMirOpFusedCmpgDouble:
1267 case kMirOpFusedCmpLong:
1268 if (ssa_rep != nullptr) {
1269 decoded_mir->append(" ");
1270 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1271 for (int i = 1; i < uses; i++) {
1272 decoded_mir->append(", ");
1273 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1274 }
1275 } else {
1276 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1277 }
1278 break;
1279 case kMirOpMoveVector:
1280 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1281 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1282 break;
1283 case kMirOpPackedAddition:
1284 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1285 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1286 break;
1287 case kMirOpPackedMultiply:
1288 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1289 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1290 break;
1291 case kMirOpPackedSubtract:
1292 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1293 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1294 break;
1295 case kMirOpPackedAnd:
1296 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1297 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1298 break;
1299 case kMirOpPackedOr:
1300 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1301 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1302 break;
1303 case kMirOpPackedXor:
1304 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1305 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1306 break;
1307 case kMirOpPackedShiftLeft:
1308 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1309 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1310 break;
1311 case kMirOpPackedUnsignedShiftRight:
1312 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1313 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1314 break;
1315 case kMirOpPackedSignedShiftRight:
1316 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1317 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1318 break;
1319 case kMirOpConstVector:
1320 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1321 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1322 break;
1323 case kMirOpPackedSet:
1324 if (ssa_rep != nullptr) {
1325 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1326 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1327 if (uses > 1) {
1328 decoded_mir->append(", ");
1329 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1330 }
1331 } else {
1332 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1333 }
1334 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1335 break;
1336 case kMirOpPackedAddReduce:
1337 if (ssa_rep != nullptr) {
1338 decoded_mir->append(" ");
1339 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1340 if (defs > 1) {
1341 decoded_mir->append(", ");
1342 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1343 }
1344 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1345 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1346 if (uses > 1) {
1347 decoded_mir->append(", ");
1348 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1349 }
1350 } else {
1351 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1352 }
1353 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1354 break;
1355 case kMirOpPackedReduce:
1356 if (ssa_rep != nullptr) {
1357 decoded_mir->append(" ");
1358 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1359 if (defs > 1) {
1360 decoded_mir->append(", ");
1361 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1362 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001363 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001364 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001365 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1366 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001367 }
1368 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1369 break;
1370 case kMirOpReserveVectorRegisters:
1371 case kMirOpReturnVectorRegisters:
1372 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1373 break;
1374 case kMirOpMemBarrier: {
1375 decoded_mir->append(" type:");
1376 std::stringstream ss;
1377 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1378 decoded_mir->append(ss.str());
1379 break;
1380 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001381 case kMirOpPackedArrayGet:
1382 case kMirOpPackedArrayPut:
1383 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1384 if (ssa_rep != nullptr) {
1385 decoded_mir->append(StringPrintf(", %s[%s]",
1386 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1387 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1388 } else {
1389 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1390 }
1391 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1392 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001393 case kMirOpMaddInt:
1394 case kMirOpMsubInt:
1395 case kMirOpMaddLong:
1396 case kMirOpMsubLong:
1397 if (ssa_rep != nullptr) {
1398 decoded_mir->append(" ");
1399 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1400 if (defs > 1) {
1401 decoded_mir->append(", ");
1402 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1403 }
1404 for (int i = 0; i < uses; i++) {
1405 decoded_mir->append(", ");
1406 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1407 }
1408 } else {
1409 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1410 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1411 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1412 }
1413 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001414 default:
1415 break;
1416 }
1417}
1418
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001419char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001420 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001421 std::string str;
1422 int flags = 0;
1423 int opcode = insn.opcode;
1424 char* ret;
1425 bool nop = false;
1426 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001427 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001428
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001429 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001430 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1431 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1432 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001433 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001434 insn = mir->meta.throw_insn->dalvikInsn;
1435 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001436 opcode = insn.opcode;
1437 } else if (opcode == kMirOpNop) {
1438 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001439 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1440 // Recover original opcode.
1441 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1442 opcode = insn.opcode;
1443 }
buzbee1fd33462013-03-25 13:40:45 -07001444 nop = true;
1445 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001446 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1447 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001448
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001449 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001450 // Note that this does not check the MIR's opcode in all cases. In cases where it
1451 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1452 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001453 } else {
1454 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001455 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001456 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001457
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001458 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001459 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1460 (dalvik_format == Instruction::k3rc));
1461 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001462 str.append(" ");
1463 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1464 if (defs > 1) {
1465 str.append(", ");
1466 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1467 }
buzbee1fd33462013-03-25 13:40:45 -07001468 if (uses != 0) {
1469 str.append(", ");
1470 }
1471 }
1472 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001473 str.append(" ");
1474 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001475 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1476 // For the listing, skip the high sreg.
1477 i++;
1478 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001479 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001480 str.append(",");
1481 }
1482 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001483
buzbee1fd33462013-03-25 13:40:45 -07001484 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001485 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001486 case Instruction::k21s:
1487 case Instruction::k31i:
1488 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001489 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001490 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001491 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001492 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001493 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001494 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001495 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001496 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001497 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001498 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001499 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001500 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001501 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001502 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001503 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001504 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001505 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001506 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001507 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001508 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001509
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001510 if ((flags & Instruction::kBranch) != 0) {
1511 // For branches, decode the instructions to print out the branch targets.
1512 int offset = 0;
1513 switch (dalvik_format) {
1514 case Instruction::k21t:
1515 offset = insn.vB;
1516 break;
1517 case Instruction::k22t:
1518 offset = insn.vC;
1519 break;
1520 case Instruction::k10t:
1521 case Instruction::k20t:
1522 case Instruction::k30t:
1523 offset = insn.vA;
1524 break;
1525 default:
1526 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001527 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001528 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001529 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001530 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1531 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001532
1533 if (nop) {
1534 str.append("]--optimized away");
1535 }
buzbee1fd33462013-03-25 13:40:45 -07001536 }
1537 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001538 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001539 strncpy(ret, str.c_str(), length);
1540 return ret;
1541}
1542
1543/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001544void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001545 static const struct { const char before; const char after; } match[] = {
1546 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1547 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1548 };
buzbee1fd33462013-03-25 13:40:45 -07001549 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1550 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1551 }
1552}
1553
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001554std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001555 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1556 // the arena. We should be smarter and just place straight into the arena, or compute the
1557 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001558 int vreg = SRegToVReg(ssa_reg);
1559 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1560 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1561 } else {
1562 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1563 }
buzbee1fd33462013-03-25 13:40:45 -07001564}
1565
1566// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001567std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001568 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001569 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001570 return GetSSAName(ssa_reg);
1571 }
1572 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001573 if (!singles_only && reg_location_[ssa_reg].wide &&
1574 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001575 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001576 ConstantValueWide(reg_location_[ssa_reg]));
1577 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001578 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001579 ConstantValue(reg_location_[ssa_reg]));
1580 }
1581 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001582 int vreg = SRegToVReg(ssa_reg);
1583 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1584 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1585 } else {
1586 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1587 }
buzbee1fd33462013-03-25 13:40:45 -07001588 }
1589}
1590
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001591void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001592 switch (bb->block_type) {
1593 case kEntryBlock:
1594 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1595 break;
1596 case kExitBlock:
1597 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1598 break;
1599 case kDalvikByteCode:
1600 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1601 break;
1602 case kExceptionHandling:
1603 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1604 bb->id);
1605 break;
1606 default:
1607 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1608 break;
1609 }
1610}
1611
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001612const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001613 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001614 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1615 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1616}
1617
Serguei Katkov717a3e42014-11-13 17:19:42 +06001618const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1619 const DexFile::MethodId& method_id =
1620 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1621 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1622}
1623
buzbee1fd33462013-03-25 13:40:45 -07001624/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001625void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001626 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001627 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001628 "Entry Block",
1629 "Code Block",
1630 "Exit Block",
1631 "Exception Handling",
1632 "Catch Block"
1633 };
1634
1635 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001636 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001637 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001638
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001639 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001640 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1641 bb->id,
1642 block_type_names[bb->block_type],
1643 bb->start_offset,
1644 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1645 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001646 if (bb->taken != NullBasicBlockId) {
1647 LOG(INFO) << " Taken branch: block " << bb->taken
1648 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001649 }
buzbee0d829482013-10-11 15:24:55 -07001650 if (bb->fall_through != NullBasicBlockId) {
1651 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1652 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001653 }
1654 }
1655}
1656
1657/*
1658 * Build an array of location records for the incoming arguments.
1659 * Note: one location record per word of arguments, with dummy
1660 * high-word loc for wide arguments. Also pull up any following
1661 * MOVE_RESULT and incorporate it into the invoke.
1662 */
1663CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001664 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001665 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001666 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001667 MIR* move_result_mir = FindMoveResult(bb, mir);
1668 if (move_result_mir == NULL) {
1669 info->result.location = kLocInvalid;
1670 } else {
1671 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001672 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1673 }
1674 info->num_arg_words = mir->ssa_rep->num_uses;
1675 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001676 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001677 for (int i = 0; i < info->num_arg_words; i++) {
1678 info->args[i] = GetRawSrc(mir, i);
1679 }
1680 info->opt_flags = mir->optimization_flags;
1681 info->type = type;
1682 info->is_range = is_range;
1683 info->index = mir->dalvikInsn.vB;
1684 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001685 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001686 return info;
1687}
1688
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001689// Allocate a new MIR.
1690MIR* MIRGraph::NewMIR() {
1691 MIR* mir = new (arena_) MIR();
1692 return mir;
1693}
1694
buzbee862a7602013-04-05 10:58:54 -07001695// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001696BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001697 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001698
buzbee862a7602013-04-05 10:58:54 -07001699 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001700 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001701 block_id_map_.Put(block_id, block_id);
1702 return bb;
1703}
buzbee1fd33462013-03-25 13:40:45 -07001704
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001705void MIRGraph::InitializeConstantPropagation() {
1706 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001707 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001708}
1709
1710void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001711 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001712 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001713 use_counts_.clear();
1714 use_counts_.reserve(num_ssa_regs + 32);
1715 use_counts_.resize(num_ssa_regs, 0u);
1716 raw_use_counts_.clear();
1717 raw_use_counts_.reserve(num_ssa_regs + 32);
1718 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001719}
1720
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001721void MIRGraph::SSATransformationStart() {
1722 DCHECK(temp_scoped_alloc_.get() == nullptr);
1723 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001724 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1725 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1726 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001727}
1728
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001729void MIRGraph::SSATransformationEnd() {
1730 // Verify the dataflow information after the pass.
1731 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1732 VerifyDataflow();
1733 }
1734
Vladimir Markof585e542014-11-21 13:41:32 +00001735 temp_.ssa.num_vregs = 0u;
1736 temp_.ssa.work_live_vregs = nullptr;
1737 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001738 DCHECK(temp_scoped_alloc_.get() != nullptr);
1739 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001740
1741 // Update the maximum number of reachable blocks.
1742 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001743
1744 // Mark MIR SSA representations as up to date.
1745 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001746}
1747
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001748size_t MIRGraph::GetNumDalvikInsns() const {
1749 size_t cumulative_size = 0u;
1750 bool counted_current_item = false;
1751 const uint8_t size_for_null_code_item = 2u;
1752
1753 for (auto it : m_units_) {
1754 const DexFile::CodeItem* code_item = it->GetCodeItem();
1755 // Even if the code item is null, we still count non-zero value so that
1756 // each m_unit is counted as having impact.
1757 cumulative_size += (code_item == nullptr ?
1758 size_for_null_code_item : code_item->insns_size_in_code_units_);
1759 if (code_item == current_code_item_) {
1760 counted_current_item = true;
1761 }
1762 }
1763
1764 // If the current code item was not counted yet, count it now.
1765 // This can happen for example in unit tests where some fields like m_units_
1766 // are not initialized.
1767 if (counted_current_item == false) {
1768 cumulative_size += (current_code_item_ == nullptr ?
1769 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1770 }
1771
1772 return cumulative_size;
1773}
1774
Vladimir Marko55fff042014-07-10 12:42:52 +01001775static BasicBlock* SelectTopologicalSortOrderFallBack(
1776 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1777 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1778 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1779 // No true loop head has been found but there may be true loop heads after the mess we need
1780 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1781 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1782 BasicBlock* fall_back = nullptr;
1783 size_t fall_back_num_reachable = 0u;
1784 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1785 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1786 AllNodesIterator iter(mir_graph);
1787 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1788 if (candidate->hidden || // Hidden, or
1789 candidate->visited || // already processed, or
1790 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1791 (current_loop != nullptr && // outside current loop.
1792 !current_loop->IsBitSet(candidate->id))) {
1793 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001794 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001795 DCHECK(tmp_stack->empty());
1796 tmp_stack->push_back(candidate->id);
1797 candidate_reachable.ClearAllBits();
1798 size_t num_reachable = 0u;
1799 while (!tmp_stack->empty()) {
1800 BasicBlockId current_id = tmp_stack->back();
1801 tmp_stack->pop_back();
1802 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1803 DCHECK(current_bb != nullptr);
1804 ChildBlockIterator child_iter(current_bb, mir_graph);
1805 BasicBlock* child_bb = child_iter.Next();
1806 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1807 DCHECK(!child_bb->hidden);
1808 if (child_bb->visited || // Already processed, or
1809 (current_loop != nullptr && // outside current loop.
1810 !current_loop->IsBitSet(child_bb->id))) {
1811 continue;
1812 }
1813 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1814 candidate_reachable.SetBit(child_bb->id);
1815 tmp_stack->push_back(child_bb->id);
1816 num_reachable += 1u;
1817 }
1818 }
1819 }
1820 if (fall_back_num_reachable < num_reachable) {
1821 fall_back_num_reachable = num_reachable;
1822 fall_back = candidate;
1823 }
1824 }
1825 return fall_back;
1826}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001827
Vladimir Marko55fff042014-07-10 12:42:52 +01001828// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1829static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1830 ArenaBitVector* reachable,
1831 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1832 // NOTE: Loop heads indicated by the "visited" flag.
1833 DCHECK(tmp_stack->empty());
1834 reachable->ClearAllBits();
1835 tmp_stack->push_back(bb_id);
1836 while (!tmp_stack->empty()) {
1837 BasicBlockId current_id = tmp_stack->back();
1838 tmp_stack->pop_back();
1839 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1840 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001841 for (BasicBlockId pred_id : current_bb->predecessors) {
1842 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1843 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001844 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1845 reachable->SetBit(pred_bb->id);
1846 tmp_stack->push_back(pred_bb->id);
1847 }
1848 }
1849 }
1850}
1851
1852void MIRGraph::ComputeTopologicalSortOrder() {
1853 ScopedArenaAllocator allocator(&cu_->arena_stack);
1854 unsigned int num_blocks = GetNumBlocks();
1855
1856 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1857 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1858 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1859 size_t max_nested_loops = 0u;
1860 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1861 loop_exit_blocks.ClearAllBits();
1862
1863 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001864 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001865 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001866 if (bb->hidden == true) {
1867 continue;
1868 }
1869
Vladimir Marko55fff042014-07-10 12:42:52 +01001870 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001871
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001872 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001873 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001874 q.push(bb);
1875 }
1876 }
1877
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001878 // Clear the topological order arrays.
1879 topological_order_.clear();
1880 topological_order_.reserve(num_blocks);
1881 topological_order_loop_ends_.clear();
1882 topological_order_loop_ends_.resize(num_blocks, 0u);
1883 topological_order_indexes_.clear();
1884 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001885
1886 // Mark all blocks as unvisited.
1887 ClearAllVisitedFlags();
1888
1889 // For loop heads, keep track from which blocks they are reachable not going through other
1890 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1891 // in this set go into the loop body, the other children are jumping over the loop.
1892 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1893 loop_head_reachable_from.resize(num_blocks, nullptr);
1894 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1895 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1896
1897 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001898 BasicBlock* bb = nullptr;
1899 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001900 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001901 // Get top.
1902 bb = q.front();
1903 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001904 if (bb->visited) {
1905 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1906 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001907 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1908 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001909 DCHECK_EQ(loop_head_stack.back(), bb->id);
1910 loop_head_stack.pop_back();
1911 ArenaBitVector* reachable =
1912 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1913 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1914 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1915 q.push(GetBasicBlock(candidate_id));
1916 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1917 // so clearing the bit has no effect on the iterator.
1918 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001919 }
1920 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001921 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001922 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001923 } else {
1924 // Find the new loop head.
1925 AllNodesIterator iter(this);
1926 while (true) {
1927 BasicBlock* candidate = iter.Next();
1928 if (candidate == nullptr) {
1929 // We did not find a true loop head, fall back to a reachable block in any loop.
1930 ArenaBitVector* current_loop =
1931 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1932 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1933 &allocator, &tmp_stack);
1934 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1935 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1936 LOG(INFO) << "Topological sort order: Using fall-back in "
1937 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1938 << " @0x" << std::hex << bb->start_offset
1939 << ", num_blocks = " << std::dec << num_blocks;
1940 }
1941 break;
1942 }
1943 if (candidate->hidden || // Hidden, or
1944 candidate->visited || // already processed, or
1945 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1946 (!loop_head_stack.empty() && // outside current loop.
1947 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1948 continue;
1949 }
1950
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001951 for (BasicBlockId pred_id : candidate->predecessors) {
1952 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1953 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001954 if (pred_bb != candidate && !pred_bb->visited &&
1955 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001956 candidate = nullptr; // Set candidate to null to indicate failure.
1957 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001958 }
1959 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001960 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001961 bb = candidate;
1962 break;
1963 }
1964 }
1965 // Compute blocks from which the loop head is reachable and process those blocks first.
1966 ArenaBitVector* reachable =
1967 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1968 loop_head_reachable_from[bb->id] = reachable;
1969 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1970 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1971 loop_head_stack.push_back(bb->id);
1972 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001973 }
1974
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001975 DCHECK_EQ(bb->hidden, false);
1976 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001977 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00001978 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001979
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001980 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001981 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1982 topological_order_indexes_[bb->id] = idx;
1983 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001984
Vladimir Marko55fff042014-07-10 12:42:52 +01001985 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001986 ChildBlockIterator succIter(bb, this);
1987 BasicBlock* successor = succIter.Next();
1988 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001989 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001990 continue;
1991 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001992
Vladimir Marko55fff042014-07-10 12:42:52 +01001993 // One more predecessor was visited.
1994 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001995 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001996 if (loop_head_stack.empty() ||
1997 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1998 q.push(successor);
1999 } else {
2000 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2001 loop_exit_blocks.SetBit(successor->id);
2002 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002003 }
2004 }
2005 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002006
2007 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002008 topological_order_loop_head_stack_.clear();
2009 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002010 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002011 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002012}
2013
2014bool BasicBlock::IsExceptionBlock() const {
2015 if (block_type == kExceptionHandling) {
2016 return true;
2017 }
2018 return false;
2019}
2020
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002021ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2022 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2023 visited_taken_(false), have_successors_(false) {
2024 // Check if we actually do have successors.
2025 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2026 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002027 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002028 }
2029}
2030
2031BasicBlock* ChildBlockIterator::Next() {
2032 // We check if we have a basic block. If we don't we cannot get next child.
2033 if (basic_block_ == nullptr) {
2034 return nullptr;
2035 }
2036
2037 // If we haven't visited fallthrough, return that.
2038 if (visited_fallthrough_ == false) {
2039 visited_fallthrough_ = true;
2040
2041 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2042 if (result != nullptr) {
2043 return result;
2044 }
2045 }
2046
2047 // If we haven't visited taken, return that.
2048 if (visited_taken_ == false) {
2049 visited_taken_ = true;
2050
2051 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2052 if (result != nullptr) {
2053 return result;
2054 }
2055 }
2056
2057 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2058 if (have_successors_ == true) {
2059 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002060 auto end = basic_block_->successor_blocks.cend();
2061 while (successor_iter_ != end) {
2062 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2063 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002064 // If block was replaced by zero block, take next one.
2065 if (successor_block_info->block != NullBasicBlockId) {
2066 return mir_graph_->GetBasicBlock(successor_block_info->block);
2067 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002068 }
2069 }
2070
2071 // We do not have anything.
2072 return nullptr;
2073}
2074
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002075BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2076 MIRGraph* mir_graph = c_unit->mir_graph.get();
2077 return Copy(mir_graph);
2078}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002079
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002080BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2081 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002082
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002083 // We don't do a memcpy style copy here because it would lead to a lot of things
2084 // to clean up. Let us do it by hand instead.
2085 // Copy in taken and fallthrough.
2086 result_bb->fall_through = fall_through;
2087 result_bb->taken = taken;
2088
2089 // Copy successor links if needed.
2090 ArenaAllocator* arena = mir_graph->GetArena();
2091
2092 result_bb->successor_block_list_type = successor_block_list_type;
2093 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002094 result_bb->successor_blocks.reserve(successor_blocks.size());
2095 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2096 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2097 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002098 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002099 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002100 }
2101 }
2102
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002103 // Copy offset, method.
2104 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002105
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002106 // Now copy instructions.
2107 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2108 // Get a copy first.
2109 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002110
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002111 // Append it.
2112 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002113 }
2114
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002115 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002116}
2117
2118MIR* MIR::Copy(MIRGraph* mir_graph) {
2119 MIR* res = mir_graph->NewMIR();
2120 *res = *this;
2121
2122 // Remove links
2123 res->next = nullptr;
2124 res->bb = NullBasicBlockId;
2125 res->ssa_rep = nullptr;
2126
2127 return res;
2128}
2129
2130MIR* MIR::Copy(CompilationUnit* c_unit) {
2131 return Copy(c_unit->mir_graph.get());
2132}
2133
2134uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2135 // Default result.
2136 int res = 0;
2137
2138 // We are basically setting the iputs to their igets counterparts.
2139 switch (opcode) {
2140 case Instruction::IPUT:
2141 case Instruction::IPUT_OBJECT:
2142 case Instruction::IPUT_BOOLEAN:
2143 case Instruction::IPUT_BYTE:
2144 case Instruction::IPUT_CHAR:
2145 case Instruction::IPUT_SHORT:
2146 case Instruction::IPUT_QUICK:
2147 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002148 case Instruction::IPUT_BOOLEAN_QUICK:
2149 case Instruction::IPUT_BYTE_QUICK:
2150 case Instruction::IPUT_CHAR_QUICK:
2151 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002152 case Instruction::APUT:
2153 case Instruction::APUT_OBJECT:
2154 case Instruction::APUT_BOOLEAN:
2155 case Instruction::APUT_BYTE:
2156 case Instruction::APUT_CHAR:
2157 case Instruction::APUT_SHORT:
2158 case Instruction::SPUT:
2159 case Instruction::SPUT_OBJECT:
2160 case Instruction::SPUT_BOOLEAN:
2161 case Instruction::SPUT_BYTE:
2162 case Instruction::SPUT_CHAR:
2163 case Instruction::SPUT_SHORT:
2164 // Skip the VR containing what to store.
2165 res = 1;
2166 break;
2167 case Instruction::IPUT_WIDE:
2168 case Instruction::IPUT_WIDE_QUICK:
2169 case Instruction::APUT_WIDE:
2170 case Instruction::SPUT_WIDE:
2171 // Skip the two VRs containing what to store.
2172 res = 2;
2173 break;
2174 default:
2175 // Do nothing in the general case.
2176 break;
2177 }
2178
2179 return res;
2180}
2181
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002182/**
2183 * @brief Given a decoded instruction, it checks whether the instruction
2184 * sets a constant and if it does, more information is provided about the
2185 * constant being set.
2186 * @param ptr_value pointer to a 64-bit holder for the constant.
2187 * @param wide Updated by function whether a wide constant is being set by bytecode.
2188 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2189 */
2190bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2191 bool sets_const = true;
2192 int64_t value = vB;
2193
2194 DCHECK(ptr_value != nullptr);
2195 DCHECK(wide != nullptr);
2196
2197 switch (opcode) {
2198 case Instruction::CONST_4:
2199 case Instruction::CONST_16:
2200 case Instruction::CONST:
2201 *wide = false;
2202 value <<= 32; // In order to get the sign extend.
2203 value >>= 32;
2204 break;
2205 case Instruction::CONST_HIGH16:
2206 *wide = false;
2207 value <<= 48; // In order to get the sign extend.
2208 value >>= 32;
2209 break;
2210 case Instruction::CONST_WIDE_16:
2211 case Instruction::CONST_WIDE_32:
2212 *wide = true;
2213 value <<= 32; // In order to get the sign extend.
2214 value >>= 32;
2215 break;
2216 case Instruction::CONST_WIDE:
2217 *wide = true;
2218 value = vB_wide;
2219 break;
2220 case Instruction::CONST_WIDE_HIGH16:
2221 *wide = true;
2222 value <<= 48; // In order to get the sign extend.
2223 break;
2224 default:
2225 sets_const = false;
2226 break;
2227 }
2228
2229 if (sets_const) {
2230 *ptr_value = value;
2231 }
2232
2233 return sets_const;
2234}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002235
2236void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2237 // Reset flags for all MIRs in bb.
2238 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2239 mir->optimization_flags &= (~reset_flags);
2240 }
2241}
2242
Vladimir Markocb873d82014-12-08 15:16:54 +00002243void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002244 for (BasicBlockId pred_id : predecessors) {
2245 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2246 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002247
2248 // Sadly we have to go through the children by hand here.
2249 pred_bb->ReplaceChild(id, NullBasicBlockId);
2250 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002251 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002252
Vladimir Markocb873d82014-12-08 15:16:54 +00002253 KillUnreachable(mir_graph);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002254}
2255
Vladimir Marko312eb252014-10-07 15:01:57 +01002256void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2257 DCHECK(predecessors.empty()); // Unreachable.
2258
2259 // Mark as dead and hidden.
2260 block_type = kDead;
2261 hidden = true;
2262
2263 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2264 // are updated to know that they no longer have a parent.
2265 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2266 mir->bb = NullBasicBlockId;
2267 }
2268 first_mir_insn = nullptr;
2269 last_mir_insn = nullptr;
2270
2271 data_flow_info = nullptr;
2272
2273 // Erase this bb from all children's predecessors and kill unreachable children.
2274 ChildBlockIterator iter(this, mir_graph);
2275 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2276 succ_bb->ErasePredecessor(id);
2277 if (succ_bb->predecessors.empty()) {
2278 succ_bb->KillUnreachable(mir_graph);
2279 }
2280 }
2281
2282 // Remove links to children.
2283 fall_through = NullBasicBlockId;
2284 taken = NullBasicBlockId;
2285 successor_block_list_type = kNotUsed;
2286
2287 if (kIsDebugBuild) {
2288 if (catch_entry) {
2289 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2290 mir_graph->catches_.erase(start_offset);
2291 }
2292 }
2293}
2294
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002295bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2296 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2297 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2298 // then it is not live out of this BB.
2299 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2300
2301 int last_ssa_reg = -1;
2302
2303 // Walk through the MIRs backwards.
2304 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2305 // Get ssa rep.
2306 SSARepresentation *ssa_rep = mir->ssa_rep;
2307
2308 // Go through the defines for this MIR.
2309 for (int i = 0; i < ssa_rep->num_defs; i++) {
2310 DCHECK(ssa_rep->defs != nullptr);
2311
2312 // Get the ssa reg.
2313 int def_ssa_reg = ssa_rep->defs[i];
2314
2315 // Get dalvik reg.
2316 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2317
2318 // Compare dalvik regs.
2319 if (dalvik_reg == def_dalvik_reg) {
2320 // We found a def of the register that we are being asked about.
2321 // Remember it.
2322 last_ssa_reg = def_ssa_reg;
2323 }
2324 }
2325 }
2326
2327 if (last_ssa_reg == -1) {
2328 // If we get to this point we couldn't find a define of register user asked about.
2329 // Let's assume the user knows what he's doing so we can be safe and say that if we
2330 // couldn't find a def, it is live out.
2331 return true;
2332 }
2333
2334 // If it is not -1, we found a match, is it ssa_reg?
2335 return (ssa_reg == last_ssa_reg);
2336}
2337
2338bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2339 // We need to check taken, fall_through, and successor_blocks to replace.
2340 bool found = false;
2341 if (taken == old_bb) {
2342 taken = new_bb;
2343 found = true;
2344 }
2345
2346 if (fall_through == old_bb) {
2347 fall_through = new_bb;
2348 found = true;
2349 }
2350
2351 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002352 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002353 if (successor_block_info->block == old_bb) {
2354 successor_block_info->block = new_bb;
2355 found = true;
2356 }
2357 }
2358 }
2359
2360 return found;
2361}
2362
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002363void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2364 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2365 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002366 // It's faster to move the back() to *pos than erase(pos).
2367 *pos = predecessors.back();
2368 predecessors.pop_back();
2369 size_t idx = std::distance(predecessors.begin(), pos);
2370 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2371 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2372 break;
2373 }
2374 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2375 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2376 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2377 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2378 mir->ssa_rep->num_uses = predecessors.size();
2379 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002380}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002381
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002382void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2383 DCHECK_NE(new_pred, NullBasicBlockId);
2384 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002385 DCHECK(pos != predecessors.end());
2386 *pos = new_pred;
2387 size_t idx = std::distance(predecessors.begin(), pos);
2388 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2389 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2390 break;
2391 }
2392 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2393 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002394 }
2395}
2396
2397// Create a new basic block with block_id as num_blocks_ that is
2398// post-incremented.
2399BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002400 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2401 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002402 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002403 return res;
2404}
2405
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002406void MIRGraph::CalculateBasicBlockInformation() {
2407 PassDriverMEPostOpt driver(cu_);
2408 driver.Launch();
2409}
2410
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002411int MIR::DecodedInstruction::FlagsOf() const {
2412 // Calculate new index.
2413 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2414
2415 // Check if it is an extended or not.
2416 if (idx < 0) {
2417 return Instruction::FlagsOf(opcode);
2418 }
2419
2420 // For extended, we use a switch.
2421 switch (static_cast<int>(opcode)) {
2422 case kMirOpPhi:
2423 return Instruction::kContinue;
2424 case kMirOpCopy:
2425 return Instruction::kContinue;
2426 case kMirOpFusedCmplFloat:
2427 return Instruction::kContinue | Instruction::kBranch;
2428 case kMirOpFusedCmpgFloat:
2429 return Instruction::kContinue | Instruction::kBranch;
2430 case kMirOpFusedCmplDouble:
2431 return Instruction::kContinue | Instruction::kBranch;
2432 case kMirOpFusedCmpgDouble:
2433 return Instruction::kContinue | Instruction::kBranch;
2434 case kMirOpFusedCmpLong:
2435 return Instruction::kContinue | Instruction::kBranch;
2436 case kMirOpNop:
2437 return Instruction::kContinue;
2438 case kMirOpNullCheck:
2439 return Instruction::kContinue | Instruction::kThrow;
2440 case kMirOpRangeCheck:
2441 return Instruction::kContinue | Instruction::kThrow;
2442 case kMirOpDivZeroCheck:
2443 return Instruction::kContinue | Instruction::kThrow;
2444 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002445 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002446 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002447 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002448 case kMirOpSelect:
2449 return Instruction::kContinue;
2450 case kMirOpConstVector:
2451 return Instruction::kContinue;
2452 case kMirOpMoveVector:
2453 return Instruction::kContinue;
2454 case kMirOpPackedMultiply:
2455 return Instruction::kContinue;
2456 case kMirOpPackedAddition:
2457 return Instruction::kContinue;
2458 case kMirOpPackedSubtract:
2459 return Instruction::kContinue;
2460 case kMirOpPackedShiftLeft:
2461 return Instruction::kContinue;
2462 case kMirOpPackedSignedShiftRight:
2463 return Instruction::kContinue;
2464 case kMirOpPackedUnsignedShiftRight:
2465 return Instruction::kContinue;
2466 case kMirOpPackedAnd:
2467 return Instruction::kContinue;
2468 case kMirOpPackedOr:
2469 return Instruction::kContinue;
2470 case kMirOpPackedXor:
2471 return Instruction::kContinue;
2472 case kMirOpPackedAddReduce:
2473 return Instruction::kContinue;
2474 case kMirOpPackedReduce:
2475 return Instruction::kContinue;
2476 case kMirOpPackedSet:
2477 return Instruction::kContinue;
2478 case kMirOpReserveVectorRegisters:
2479 return Instruction::kContinue;
2480 case kMirOpReturnVectorRegisters:
2481 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002482 case kMirOpMemBarrier:
2483 return Instruction::kContinue;
2484 case kMirOpPackedArrayGet:
2485 return Instruction::kContinue | Instruction::kThrow;
2486 case kMirOpPackedArrayPut:
2487 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002488 case kMirOpMaddInt:
2489 case kMirOpMsubInt:
2490 case kMirOpMaddLong:
2491 case kMirOpMsubLong:
2492 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002493 default:
2494 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2495 return 0;
2496 }
2497}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002498} // namespace art