blob: baa46d61bd7f232b6e4bf319547d15967eaa07fa [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 Rogers6282dc12013-04-18 15:54:02 -070022#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070025#include "dex_instruction-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000026#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000028#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070029#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010030#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000031
buzbee311ca162013-02-28 15:56:43 -080032namespace art {
33
34#define MAX_PATTERN_LEN 5
35
buzbee1fd33462013-03-25 13:40:45 -070036const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
37 "Phi",
38 "Copy",
39 "FusedCmplFloat",
40 "FusedCmpgFloat",
41 "FusedCmplDouble",
42 "FusedCmpgDouble",
43 "FusedCmpLong",
44 "Nop",
45 "OpNullCheck",
46 "OpRangeCheck",
47 "OpDivZeroCheck",
48 "Check1",
49 "Check2",
50 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040051 "ConstVector",
52 "MoveVector",
53 "PackedMultiply",
54 "PackedAddition",
55 "PackedSubtract",
56 "PackedShiftLeft",
57 "PackedSignedShiftRight",
58 "PackedUnsignedShiftRight",
59 "PackedAnd",
60 "PackedOr",
61 "PackedXor",
62 "PackedAddReduce",
63 "PackedReduce",
64 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070065};
66
buzbee862a7602013-04-05 10:58:54 -070067MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070068 : reg_location_(NULL),
69 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080070 ssa_base_vregs_(NULL),
71 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080072 vreg_to_ssa_map_(NULL),
73 ssa_last_defs_(NULL),
74 is_constant_v_(NULL),
75 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070076 use_counts_(arena, 256, kGrowableArrayMisc),
77 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080078 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070079 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070080 dfs_order_(NULL),
81 dfs_post_order_(NULL),
82 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070083 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080084 i_dom_list_(NULL),
85 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000086 temp_scoped_alloc_(),
87 temp_insn_data_(nullptr),
88 temp_bit_vector_size_(0u),
89 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070090 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080091 try_block_addr_(NULL),
92 entry_block_(NULL),
93 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080094 num_blocks_(0),
95 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070096 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080097 current_method_(kInvalidEntry),
98 current_offset_(kInvalidEntry),
99 def_count_(0),
100 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700101 num_ssa_regs_(0),
102 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700103 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
104 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700105 arena_(arena),
106 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800107 forward_branches_(0),
108 compiler_temps_(arena, 6, kGrowableArrayMisc),
109 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800110 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000111 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000112 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000113 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000114 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700115 method_lowering_infos_(arena, 0u),
116 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700117 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800118 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
119 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800120}
121
Ian Rogers6282dc12013-04-18 15:54:02 -0700122MIRGraph::~MIRGraph() {
123 STLDeleteElements(&m_units_);
124}
125
buzbee311ca162013-02-28 15:56:43 -0800126/*
127 * Parse an instruction, return the length of the instruction
128 */
Ian Rogers29a26482014-05-02 15:27:29 -0700129int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
130 const Instruction* inst = Instruction::At(code_ptr);
131 decoded_instruction->opcode = inst->Opcode();
132 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
133 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
134 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
135 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
136 if (inst->HasVarArgs()) {
137 inst->GetVarArgs(decoded_instruction->arg);
138 }
139 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800140}
141
142
143/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700144BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700145 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700146 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800147 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700148 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800149 while (insn) {
150 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700151 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800152 insn = insn->next;
153 }
154 if (insn == NULL) {
155 LOG(FATAL) << "Break split failed";
156 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700157 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700158 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800159
160 bottom_block->start_offset = code_offset;
161 bottom_block->first_mir_insn = insn;
162 bottom_block->last_mir_insn = orig_block->last_mir_insn;
163
164 /* If this block was terminated by a return, the flag needs to go with the bottom block */
165 bottom_block->terminated_by_return = orig_block->terminated_by_return;
166 orig_block->terminated_by_return = false;
167
buzbee311ca162013-02-28 15:56:43 -0800168 /* Handle the taken path */
169 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700170 if (bottom_block->taken != NullBasicBlockId) {
171 orig_block->taken = NullBasicBlockId;
172 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
173 bb_taken->predecessors->Delete(orig_block->id);
174 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800175 }
176
177 /* Handle the fallthrough path */
178 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700179 orig_block->fall_through = bottom_block->id;
180 bottom_block->predecessors->Insert(orig_block->id);
181 if (bottom_block->fall_through != NullBasicBlockId) {
182 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
183 bb_fall_through->predecessors->Delete(orig_block->id);
184 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800185 }
186
187 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700188 if (orig_block->successor_block_list_type != kNotUsed) {
189 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
190 bottom_block->successor_blocks = orig_block->successor_blocks;
191 orig_block->successor_block_list_type = kNotUsed;
192 orig_block->successor_blocks = NULL;
193 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800194 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700195 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800196 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700197 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700198 bb->predecessors->Delete(orig_block->id);
199 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800200 }
201 }
202
buzbee0d829482013-10-11 15:24:55 -0700203 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700204 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800205
buzbee311ca162013-02-28 15:56:43 -0800206 /*
207 * Update the immediate predecessor block pointer so that outgoing edges
208 * can be applied to the proper block.
209 */
210 if (immed_pred_block_p) {
211 DCHECK_EQ(*immed_pred_block_p, orig_block);
212 *immed_pred_block_p = bottom_block;
213 }
buzbeeb48819d2013-09-14 16:15:25 -0700214
215 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000216 DCHECK(insn != nullptr);
217 DCHECK(insn != orig_block->first_mir_insn);
218 DCHECK(insn == bottom_block->first_mir_insn);
219 DCHECK_EQ(insn->offset, bottom_block->start_offset);
220 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
221 !IsPseudoMirOp(insn->dalvikInsn.opcode));
222 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
223 MIR* p = insn;
224 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
225 while (p != bottom_block->last_mir_insn) {
226 p = p->next;
227 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700228 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700229 int opcode = p->dalvikInsn.opcode;
230 /*
231 * Some messiness here to ensure that we only enter real opcodes and only the
232 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000233 * CHECK and work portions. Since the 2nd half of a split operation is always
234 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700235 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000236 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
237 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700238 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
239 }
buzbeeb48819d2013-09-14 16:15:25 -0700240 }
241
buzbee311ca162013-02-28 15:56:43 -0800242 return bottom_block;
243}
244
245/*
246 * Given a code offset, find out the block that starts with it. If the offset
247 * is in the middle of an existing block, split it into two. If immed_pred_block_p
248 * is not non-null and is the block being split, update *immed_pred_block_p to
249 * point to the bottom block so that outgoing edges can be set up properly
250 * (by the caller)
251 * Utilizes a map for fast lookup of the typical cases.
252 */
buzbee0d829482013-10-11 15:24:55 -0700253BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700254 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700255 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800256 return NULL;
257 }
buzbeeb48819d2013-09-14 16:15:25 -0700258
259 int block_id = dex_pc_to_block_map_.Get(code_offset);
260 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
261
262 if ((bb != NULL) && (bb->start_offset == code_offset)) {
263 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700264 return bb;
265 }
buzbee311ca162013-02-28 15:56:43 -0800266
buzbeeb48819d2013-09-14 16:15:25 -0700267 // No direct hit.
268 if (!create) {
269 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800270 }
271
buzbeeb48819d2013-09-14 16:15:25 -0700272 if (bb != NULL) {
273 // The target exists somewhere in an existing block.
274 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
275 }
276
277 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700278 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
279 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800280 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700281 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800282 return bb;
283}
284
buzbeeb48819d2013-09-14 16:15:25 -0700285
buzbee311ca162013-02-28 15:56:43 -0800286/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700287void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800288 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700289 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800290
291 if (tries_size == 0) {
292 return;
293 }
294
295 for (int i = 0; i < tries_size; i++) {
296 const DexFile::TryItem* pTry =
297 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700298 DexOffset start_offset = pTry->start_addr_;
299 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800300 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700301 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800302 }
303 }
304
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700305 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800306 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
307 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
308 for (uint32_t idx = 0; idx < handlers_size; idx++) {
309 CatchHandlerIterator iterator(handlers_ptr);
310 for (; iterator.HasNext(); iterator.Next()) {
311 uint32_t address = iterator.GetHandlerAddress();
312 FindBlock(address, false /* split */, true /*create*/,
313 /* immed_pred_block_p */ NULL);
314 }
315 handlers_ptr = iterator.EndDataPointer();
316 }
317}
318
319/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700320BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
321 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700322 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700323 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800324 switch (insn->dalvikInsn.opcode) {
325 case Instruction::GOTO:
326 case Instruction::GOTO_16:
327 case Instruction::GOTO_32:
328 target += insn->dalvikInsn.vA;
329 break;
330 case Instruction::IF_EQ:
331 case Instruction::IF_NE:
332 case Instruction::IF_LT:
333 case Instruction::IF_GE:
334 case Instruction::IF_GT:
335 case Instruction::IF_LE:
336 cur_block->conditional_branch = true;
337 target += insn->dalvikInsn.vC;
338 break;
339 case Instruction::IF_EQZ:
340 case Instruction::IF_NEZ:
341 case Instruction::IF_LTZ:
342 case Instruction::IF_GEZ:
343 case Instruction::IF_GTZ:
344 case Instruction::IF_LEZ:
345 cur_block->conditional_branch = true;
346 target += insn->dalvikInsn.vB;
347 break;
348 default:
349 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
350 }
buzbeeb48819d2013-09-14 16:15:25 -0700351 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700352 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800353 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700354 cur_block->taken = taken_block->id;
355 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800356
357 /* Always terminate the current block for conditional branches */
358 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700359 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800360 /*
361 * If the method is processed
362 * in sequential order from the
363 * beginning, we don't need to
364 * specify split for continue
365 * blocks. However, this
366 * routine can be called by
367 * compileLoop, which starts
368 * parsing the method from an
369 * arbitrary address in the
370 * method body.
371 */
372 true,
373 /* create */
374 true,
375 /* immed_pred_block_p */
376 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700377 cur_block->fall_through = fallthrough_block->id;
378 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800379 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700380 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800381 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800382 }
383 return cur_block;
384}
385
386/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800387BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
388 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800389 const uint16_t* switch_data =
390 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
391 int size;
392 const int* keyTable;
393 const int* target_table;
394 int i;
395 int first_key;
396
397 /*
398 * Packed switch data format:
399 * ushort ident = 0x0100 magic value
400 * ushort size number of entries in the table
401 * int first_key first (and lowest) switch case value
402 * int targets[size] branch targets, relative to switch opcode
403 *
404 * Total size is (4+size*2) 16-bit code units.
405 */
406 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
407 DCHECK_EQ(static_cast<int>(switch_data[0]),
408 static_cast<int>(Instruction::kPackedSwitchSignature));
409 size = switch_data[1];
410 first_key = switch_data[2] | (switch_data[3] << 16);
411 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700412 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800413 /*
414 * Sparse switch data format:
415 * ushort ident = 0x0200 magic value
416 * ushort size number of entries in the table; > 0
417 * int keys[size] keys, sorted low-to-high; 32-bit aligned
418 * int targets[size] branch targets, relative to switch opcode
419 *
420 * Total size is (2+size*4) 16-bit code units.
421 */
422 } else {
423 DCHECK_EQ(static_cast<int>(switch_data[0]),
424 static_cast<int>(Instruction::kSparseSwitchSignature));
425 size = switch_data[1];
426 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
427 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700428 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800429 }
430
buzbee0d829482013-10-11 15:24:55 -0700431 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800432 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700433 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800434 }
buzbee0d829482013-10-11 15:24:55 -0700435 cur_block->successor_block_list_type =
436 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
437 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700438 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800439
440 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700441 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800442 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700443 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700444 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000445 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700446 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800447 successor_block_info->key =
448 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
449 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700450 cur_block->successor_blocks->Insert(successor_block_info);
451 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800452 }
453
454 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700455 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
456 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700457 cur_block->fall_through = fallthrough_block->id;
458 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800459 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800460}
461
462/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700463BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
464 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700465 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700466 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800467 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
468 bool build_all_edges =
469 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800470
471 /* In try block */
472 if (in_try_block) {
473 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
474
buzbee0d829482013-10-11 15:24:55 -0700475 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800476 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
477 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700478 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800479 }
480
buzbee0d829482013-10-11 15:24:55 -0700481 cur_block->successor_block_list_type = kCatch;
482 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700483 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800484
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700485 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700486 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800487 false /* creat */, NULL /* immed_pred_block_p */);
488 catch_block->catch_entry = true;
489 if (kIsDebugBuild) {
490 catches_.insert(catch_block->start_offset);
491 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700492 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000493 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700494 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800495 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700496 cur_block->successor_blocks->Insert(successor_block_info);
497 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800498 }
buzbee17189ac2013-11-08 11:07:02 -0800499 } else if (build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700500 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700501 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700502 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800503 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700504 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800505 }
506
buzbee17189ac2013-11-08 11:07:02 -0800507 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800508 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700509 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700510 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800511 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
512 /* immed_pred_block_p */ NULL);
513 }
514 if (!in_try_block) {
515 // Don't split a THROW that can't rethrow - we're done.
516 return cur_block;
517 }
518 }
519
buzbee17189ac2013-11-08 11:07:02 -0800520 if (!build_all_edges) {
521 /*
522 * Even though there is an exception edge here, control cannot return to this
523 * method. Thus, for the purposes of dataflow analysis and optimization, we can
524 * ignore the edge. Doing this reduces compile time, and increases the scope
525 * of the basic-block level optimization pass.
526 */
527 return cur_block;
528 }
529
buzbee311ca162013-02-28 15:56:43 -0800530 /*
531 * Split the potentially-throwing instruction into two parts.
532 * The first half will be a pseudo-op that captures the exception
533 * edges and terminates the basic block. It always falls through.
534 * Then, create a new basic block that begins with the throwing instruction
535 * (minus exceptions). Note: this new basic block must NOT be entered into
536 * the block_map. If the potentially-throwing instruction is the target of a
537 * future branch, we need to find the check psuedo half. The new
538 * basic block containing the work portion of the instruction should
539 * only be entered via fallthrough from the block containing the
540 * pseudo exception edge MIR. Note also that this new block is
541 * not automatically terminated after the work portion, and may
542 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700543 *
544 * Note also that the dex_pc_to_block_map_ entry for the potentially
545 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800546 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700547 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700548 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800549 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700550 cur_block->fall_through = new_block->id;
551 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700552 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800553 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700554 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700555 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800556 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700557 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800558 return new_block;
559}
560
561/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
562void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700563 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700564 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800565 current_code_item_ = code_item;
566 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
567 current_method_ = m_units_.size();
568 current_offset_ = 0;
569 // TODO: will need to snapshot stack image and use that as the mir context identification.
570 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000571 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
572 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800573 const uint16_t* code_ptr = current_code_item_->insns_;
574 const uint16_t* code_end =
575 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
576
577 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700578 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700579 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700580 dex_pc_to_block_map_.SetSize(dex_pc_to_block_map_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700581
buzbee311ca162013-02-28 15:56:43 -0800582 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700583 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
584 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800585
586 // If this is the first method, set up default entry and exit blocks.
587 if (current_method_ == 0) {
588 DCHECK(entry_block_ == NULL);
589 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700590 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700591 // Use id 0 to represent a null block.
592 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
593 DCHECK_EQ(null_block->id, NullBasicBlockId);
594 null_block->hidden = true;
595 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700596 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700597 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700598 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700599 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800600 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
601 cu_->dex_file = &dex_file;
602 cu_->class_def_idx = class_def_idx;
603 cu_->method_idx = method_idx;
604 cu_->access_flags = access_flags;
605 cu_->invoke_type = invoke_type;
606 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
607 cu_->num_ins = current_code_item_->ins_size_;
608 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
609 cu_->num_outs = current_code_item_->outs_size_;
610 cu_->num_dalvik_registers = current_code_item_->registers_size_;
611 cu_->insns = current_code_item_->insns_;
612 cu_->code_item = current_code_item_;
613 } else {
614 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
615 /*
616 * Will need to manage storage for ins & outs, push prevous state and update
617 * insert point.
618 */
619 }
620
621 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700622 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700623 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800624 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700625 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700626 // TODO: for inlining support, insert at the insert point rather than entry block.
627 entry_block_->fall_through = cur_block->id;
628 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800629
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000630 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800631 ProcessTryCatchBlocks();
632
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000633 uint64_t merged_df_flags = 0u;
634
buzbee311ca162013-02-28 15:56:43 -0800635 /* Parse all instructions and put them into containing basic blocks */
636 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700637 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800638 insn->offset = current_offset_;
639 insn->m_unit_index = current_method_;
640 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800641 Instruction::Code opcode = insn->dalvikInsn.opcode;
642 if (opcode_count_ != NULL) {
643 opcode_count_[static_cast<int>(opcode)]++;
644 }
645
buzbee311ca162013-02-28 15:56:43 -0800646 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800647 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800648
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700649 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000650 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800651
652 if (df_flags & DF_HAS_DEFS) {
653 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
654 }
655
buzbee1da1e2f2013-11-15 13:37:01 -0800656 if (df_flags & DF_LVN) {
657 cur_block->use_lvn = true; // Run local value numbering on this basic block.
658 }
659
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700660 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700661 if (opcode == Instruction::NOP) {
662 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
663 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
664 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
665 uint16_t following_raw_instruction = code_ptr[1];
666 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
667 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
668 (following_raw_instruction == Instruction::kArrayDataSignature)) {
669 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
670 }
671 }
672 if (width == 1) {
673 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700674 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700675 } else {
buzbee0d829482013-10-11 15:24:55 -0700676 DCHECK(cur_block->fall_through == NullBasicBlockId);
677 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700678 // Unreachable instruction, mark for no continuation.
679 flags &= ~Instruction::kContinue;
680 }
681 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700682 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700683 }
684
buzbeeb48819d2013-09-14 16:15:25 -0700685 // Associate the starting dex_pc for this opcode with its containing basic block.
686 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
687
buzbee27247762013-07-28 12:03:58 -0700688 code_ptr += width;
689
buzbee311ca162013-02-28 15:56:43 -0800690 if (flags & Instruction::kBranch) {
691 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
692 width, flags, code_ptr, code_end);
693 } else if (flags & Instruction::kReturn) {
694 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700695 cur_block->fall_through = exit_block_->id;
696 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800697 /*
698 * Terminate the current block if there are instructions
699 * afterwards.
700 */
701 if (code_ptr < code_end) {
702 /*
703 * Create a fallthrough block for real instructions
704 * (incl. NOP).
705 */
buzbee27247762013-07-28 12:03:58 -0700706 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
707 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800708 }
709 } else if (flags & Instruction::kThrow) {
710 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
711 code_ptr, code_end);
712 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800713 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800714 }
buzbeeb1f1d642014-02-27 12:55:32 -0800715 if (verify_flags & Instruction::kVerifyVarArgRange) {
716 /*
717 * The Quick backend's runtime model includes a gap between a method's
718 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
719 * which spans the gap is somewhat complicated, and should not happen
720 * in normal usage of dx. Punt to the interpreter.
721 */
722 int first_reg_in_range = insn->dalvikInsn.vC;
723 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
724 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
725 punt_to_interpreter_ = true;
726 }
727 }
buzbee311ca162013-02-28 15:56:43 -0800728 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700729 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800730 false, /* immed_pred_block_p */ NULL);
731 if (next_block) {
732 /*
733 * The next instruction could be the target of a previously parsed
734 * forward branch so a block is already created. If the current
735 * instruction is not an unconditional branch, connect them through
736 * the fall-through link.
737 */
buzbee0d829482013-10-11 15:24:55 -0700738 DCHECK(cur_block->fall_through == NullBasicBlockId ||
739 GetBasicBlock(cur_block->fall_through) == next_block ||
740 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800741
buzbee0d829482013-10-11 15:24:55 -0700742 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
743 cur_block->fall_through = next_block->id;
744 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800745 }
746 cur_block = next_block;
747 }
748 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000749 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000750
buzbee311ca162013-02-28 15:56:43 -0800751 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
752 DumpCFG("/sdcard/1_post_parse_cfg/", true);
753 }
754
755 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700756 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800757 }
758}
759
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700760void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800761 DCHECK(opcode_count_ != NULL);
762 LOG(INFO) << "Opcode Count";
763 for (int i = 0; i < kNumPackedOpcodes; i++) {
764 if (opcode_count_[i] != 0) {
765 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
766 << " " << opcode_count_[i];
767 }
768 }
769}
770
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700771uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
772 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
773 return oat_data_flow_attributes_[opcode];
774}
775
776uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
777 DCHECK(mir != nullptr);
778 Instruction::Code opcode = mir->dalvikInsn.opcode;
779 return GetDataFlowAttributes(opcode);
780}
781
buzbee311ca162013-02-28 15:56:43 -0800782// TODO: use a configurable base prefix, and adjust callers to supply pass name.
783/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800784void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800785 FILE* file;
786 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
787 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800788 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
789 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
790 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800791 file = fopen(fname.c_str(), "w");
792 if (file == NULL) {
793 return;
794 }
795 fprintf(file, "digraph G {\n");
796
797 fprintf(file, " rankdir=TB\n");
798
799 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
800 int idx;
801
802 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700803 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700804 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700805 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800806 if (bb->block_type == kDead) continue;
807 if (bb->block_type == kEntryBlock) {
808 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
809 } else if (bb->block_type == kExitBlock) {
810 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
811 } else if (bb->block_type == kDalvikByteCode) {
812 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
813 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700814 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800815 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
816 bb->first_mir_insn ? " | " : " ");
817 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
818 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400819 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
820 if (opcode == kMirOpConstVector) {
821 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
822 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
823 mir->dalvikInsn.vA,
824 mir->dalvikInsn.vB,
825 mir->dalvikInsn.arg[0],
826 mir->dalvikInsn.arg[1],
827 mir->dalvikInsn.arg[2],
828 mir->dalvikInsn.arg[3],
829 mir->next ? " | " : " ");
830 } else {
831 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
832 extended_mir_op_names_[opcode - kMirOpFirst],
833 mir->dalvikInsn.vA,
834 mir->dalvikInsn.vB,
835 mir->dalvikInsn.vC,
836 mir->next ? " | " : " ");
837 }
838 } else {
839 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
840 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700841 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400842 extended_mir_op_names_[opcode - kMirOpFirst],
843 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
844 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
845 mir->next ? " | " : " ");
846 }
buzbee311ca162013-02-28 15:56:43 -0800847 }
848 fprintf(file, " }\"];\n\n");
849 } else if (bb->block_type == kExceptionHandling) {
850 char block_name[BLOCK_NAME_LEN];
851
852 GetBlockName(bb, block_name);
853 fprintf(file, " %s [shape=invhouse];\n", block_name);
854 }
855
856 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
857
buzbee0d829482013-10-11 15:24:55 -0700858 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800859 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700860 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800861 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
862 block_name1, block_name2);
863 }
buzbee0d829482013-10-11 15:24:55 -0700864 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800865 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700866 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800867 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
868 }
869
buzbee0d829482013-10-11 15:24:55 -0700870 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800871 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
872 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700873 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
874 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700875 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800876
877 int succ_id = 0;
878 while (true) {
879 if (successor_block_info == NULL) break;
880
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700881 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700882 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800883
884 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
885 succ_id++,
886 successor_block_info->key,
887 dest_block->start_offset,
888 (next_successor_block_info != NULL) ? " | " : " ");
889
890 successor_block_info = next_successor_block_info;
891 }
892 fprintf(file, " }\"];\n\n");
893
894 GetBlockName(bb, block_name1);
895 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
896 block_name1, bb->start_offset, bb->id);
897
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700898 // Link the successor pseudo-block with all of its potential targets.
899 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800900
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700901 succ_id = 0;
902 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700903 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700904 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800905
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700906 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800907
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700908 GetBlockName(dest_block, block_name2);
909 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
910 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800911 }
912 }
913 fprintf(file, "\n");
914
915 if (cu_->verbose) {
916 /* Display the dominator tree */
917 GetBlockName(bb, block_name1);
918 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
919 block_name1, block_name1);
920 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700921 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800922 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
923 }
924 }
925 }
926 fprintf(file, "}\n");
927 fclose(file);
928}
929
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700930/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700931void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700932 // Insert it after the last MIR.
933 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -0700934}
935
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700936void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
937 // Insert it after the last MIR.
938 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
939}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700940
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700941void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
942 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
943 MIR* new_mir = *it;
944
945 // Add a copy of each MIR.
946 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
947 }
buzbee1fd33462013-03-25 13:40:45 -0700948}
949
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700950/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700951void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700952 InsertMIRListAfter(current_mir, new_mir, new_mir);
953}
buzbee1fd33462013-03-25 13:40:45 -0700954
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700955void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
956 // If no MIR, we are done.
957 if (first_list_mir == nullptr || last_list_mir == nullptr) {
958 return;
buzbee1fd33462013-03-25 13:40:45 -0700959 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700960
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700961 // If insert_after is null, assume BB is empty.
962 if (insert_after == nullptr) {
963 first_mir_insn = first_list_mir;
964 last_mir_insn = last_list_mir;
965 last_list_mir->next = nullptr;
966 } else {
967 MIR* after_list = insert_after->next;
968 insert_after->next = first_list_mir;
969 last_list_mir->next = after_list;
970 if (after_list == nullptr) {
971 last_mir_insn = last_list_mir;
972 }
973 }
974
975 // Set this BB to be the basic block of the MIRs.
976 MIR* last = last_list_mir->next;
977 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
978 mir->bb = id;
979 }
980}
981
982/* Insert an MIR instruction to the head of a basic block. */
983void BasicBlock::PrependMIR(MIR* mir) {
984 InsertMIRListBefore(first_mir_insn, mir, mir);
985}
986
987void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
988 // Insert it before the first MIR.
989 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
990}
991
992void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
993 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
994 MIR* mir = *it;
995
996 InsertMIRListBefore(first_mir_insn, mir, mir);
997 }
998}
999
1000/* Insert a MIR instruction before the specified MIR. */
1001void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1002 // Insert as a single element list.
1003 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001004}
1005
1006MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1007 MIR* current = first_mir_insn;
1008
1009 while (current != nullptr) {
1010 MIR* next = current->next;
1011
1012 if (next == mir) {
1013 return current;
1014 }
1015
1016 current = next;
1017 }
1018
1019 return nullptr;
1020}
1021
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001022void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1023 // If no MIR, we are done.
1024 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1025 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001026 }
1027
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001028 // If insert_before is null, assume BB is empty.
1029 if (insert_before == nullptr) {
1030 first_mir_insn = first_list_mir;
1031 last_mir_insn = last_list_mir;
1032 last_list_mir->next = nullptr;
1033 } else {
1034 if (first_mir_insn == insert_before) {
1035 last_list_mir->next = first_mir_insn;
1036 first_mir_insn = first_list_mir;
1037 } else {
1038 // Find the preceding MIR.
1039 MIR* before_list = FindPreviousMIR(insert_before);
1040 DCHECK(before_list != nullptr);
1041 before_list->next = first_list_mir;
1042 last_list_mir->next = insert_before;
1043 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001044 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001045
1046 // Set this BB to be the basic block of the MIRs.
1047 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1048 mir->bb = id;
1049 }
1050}
1051
1052bool BasicBlock::RemoveMIR(MIR* mir) {
1053 // Remove as a single element list.
1054 return RemoveMIRList(mir, mir);
1055}
1056
1057bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1058 if (first_list_mir == nullptr) {
1059 return false;
1060 }
1061
1062 // Try to find the MIR.
1063 MIR* before_list = nullptr;
1064 MIR* after_list = nullptr;
1065
1066 // If we are removing from the beginning of the MIR list.
1067 if (first_mir_insn == first_list_mir) {
1068 before_list = nullptr;
1069 } else {
1070 before_list = FindPreviousMIR(first_list_mir);
1071 if (before_list == nullptr) {
1072 // We did not find the mir.
1073 return false;
1074 }
1075 }
1076
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001077 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001078 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1079 mir->bb = NullBasicBlockId;
1080 }
1081
1082 after_list = last_list_mir->next;
1083
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001084 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001085 if (before_list == nullptr) {
1086 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001087 } else {
1088 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001089 }
1090
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001091 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001092 if (after_list == nullptr) {
1093 last_mir_insn = before_list;
1094 }
1095
1096 return true;
buzbee1fd33462013-03-25 13:40:45 -07001097}
1098
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001099MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001100 MIR* next_mir = nullptr;
1101
1102 if (current != nullptr) {
1103 next_mir = current->next;
1104 }
1105
1106 if (next_mir == nullptr) {
1107 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001108 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1109 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001110 }
1111 }
1112
1113 return next_mir;
1114}
1115
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001116char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001117 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001118 std::string str;
1119 int flags = 0;
1120 int opcode = insn.opcode;
1121 char* ret;
1122 bool nop = false;
1123 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001124 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001125 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1126 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1127
1128 // Handle special cases.
1129 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1130 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1131 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001132 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001133 insn = mir->meta.throw_insn->dalvikInsn;
1134 ssa_rep = mir->meta.throw_insn->ssa_rep;
1135 defs = ssa_rep->num_defs;
1136 uses = ssa_rep->num_uses;
1137 opcode = insn.opcode;
1138 } else if (opcode == kMirOpNop) {
1139 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001140 // Recover original opcode.
1141 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1142 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001143 nop = true;
1144 }
1145
buzbee35ba7f32014-05-31 08:59:01 -07001146 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001147 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1148 } else {
1149 dalvik_format = Instruction::FormatOf(insn.opcode);
1150 flags = Instruction::FlagsOf(insn.opcode);
1151 str.append(Instruction::Name(insn.opcode));
1152 }
1153
1154 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001155 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001156 str.append(StringPrintf(" %s = (%s",
1157 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1158 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001159 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001160 int i;
1161 for (i = 1; i < uses; i++) {
1162 str.append(StringPrintf(", %s:%d",
1163 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1164 incoming[i]));
1165 }
1166 str.append(")");
1167 } else if ((flags & Instruction::kBranch) != 0) {
1168 // For branches, decode the instructions to print out the branch targets.
1169 int offset = 0;
1170 switch (dalvik_format) {
1171 case Instruction::k21t:
1172 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1173 offset = insn.vB;
1174 break;
1175 case Instruction::k22t:
1176 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1177 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1178 offset = insn.vC;
1179 break;
1180 case Instruction::k10t:
1181 case Instruction::k20t:
1182 case Instruction::k30t:
1183 offset = insn.vA;
1184 break;
1185 default:
1186 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1187 }
1188 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1189 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1190 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001191 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001192 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1193 (dalvik_format == Instruction::k3rc));
1194 if (defs != 0) {
1195 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1196 if (uses != 0) {
1197 str.append(", ");
1198 }
1199 }
1200 for (int i = 0; i < uses; i++) {
1201 str.append(
1202 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1203 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1204 // For the listing, skip the high sreg.
1205 i++;
1206 }
1207 if (i != (uses -1)) {
1208 str.append(",");
1209 }
1210 }
1211 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001212 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001213 case Instruction::k21s:
1214 case Instruction::k31i:
1215 case Instruction::k21h:
1216 str.append(StringPrintf(", #%d", insn.vB));
1217 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001218 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001219 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001220 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001221 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001222 case Instruction::k31c:
1223 str.append(StringPrintf(", index #%d", insn.vB));
1224 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001225 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001226 str.append(StringPrintf(", index #%d", insn.vC));
1227 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001228 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001229 case Instruction::k22b:
1230 str.append(StringPrintf(", #%d", insn.vC));
1231 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001232 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001233 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001234 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001235 }
buzbee1fd33462013-03-25 13:40:45 -07001236 }
1237 if (nop) {
1238 str.append("]--optimized away");
1239 }
1240 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001241 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001242 strncpy(ret, str.c_str(), length);
1243 return ret;
1244}
1245
1246/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001247void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001248 static const struct { const char before; const char after; } match[] = {
1249 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1250 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1251 };
buzbee1fd33462013-03-25 13:40:45 -07001252 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1253 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1254 }
1255}
1256
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001257std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001258 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1259 // the arena. We should be smarter and just place straight into the arena, or compute the
1260 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001261 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1262}
1263
1264// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001265std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001266 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001267 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001268 return GetSSAName(ssa_reg);
1269 }
1270 if (IsConst(reg_location_[ssa_reg])) {
1271 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001272 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001273 ConstantValueWide(reg_location_[ssa_reg]));
1274 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001275 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001276 ConstantValue(reg_location_[ssa_reg]));
1277 }
1278 } else {
1279 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1280 }
1281}
1282
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001283void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001284 switch (bb->block_type) {
1285 case kEntryBlock:
1286 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1287 break;
1288 case kExitBlock:
1289 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1290 break;
1291 case kDalvikByteCode:
1292 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1293 break;
1294 case kExceptionHandling:
1295 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1296 bb->id);
1297 break;
1298 default:
1299 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1300 break;
1301 }
1302}
1303
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001304const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001305 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001306 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1307 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1308}
1309
1310/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001311void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001312 BasicBlock* bb;
1313 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001314 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001315 "Entry Block",
1316 "Code Block",
1317 "Exit Block",
1318 "Exception Handling",
1319 "Catch Block"
1320 };
1321
1322 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1323 LOG(INFO) << cu_->insns << " insns";
1324 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001325 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001326
1327 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001328 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001329 if (bb == NULL) break;
1330 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1331 bb->id,
1332 block_type_names[bb->block_type],
1333 bb->start_offset,
1334 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1335 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001336 if (bb->taken != NullBasicBlockId) {
1337 LOG(INFO) << " Taken branch: block " << bb->taken
1338 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001339 }
buzbee0d829482013-10-11 15:24:55 -07001340 if (bb->fall_through != NullBasicBlockId) {
1341 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1342 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001343 }
1344 }
1345}
1346
1347/*
1348 * Build an array of location records for the incoming arguments.
1349 * Note: one location record per word of arguments, with dummy
1350 * high-word loc for wide arguments. Also pull up any following
1351 * MOVE_RESULT and incorporate it into the invoke.
1352 */
1353CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001354 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001355 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001356 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001357 MIR* move_result_mir = FindMoveResult(bb, mir);
1358 if (move_result_mir == NULL) {
1359 info->result.location = kLocInvalid;
1360 } else {
1361 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001362 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1363 }
1364 info->num_arg_words = mir->ssa_rep->num_uses;
1365 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001366 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001367 for (int i = 0; i < info->num_arg_words; i++) {
1368 info->args[i] = GetRawSrc(mir, i);
1369 }
1370 info->opt_flags = mir->optimization_flags;
1371 info->type = type;
1372 info->is_range = is_range;
1373 info->index = mir->dalvikInsn.vB;
1374 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001375 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001376 return info;
1377}
1378
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001379// Allocate a new MIR.
1380MIR* MIRGraph::NewMIR() {
1381 MIR* mir = new (arena_) MIR();
1382 return mir;
1383}
1384
buzbee862a7602013-04-05 10:58:54 -07001385// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001386BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001387 BasicBlock* bb = new (arena_) BasicBlock();
1388
buzbee862a7602013-04-05 10:58:54 -07001389 bb->block_type = block_type;
1390 bb->id = block_id;
1391 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001392 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001393 (block_type == kExitBlock) ? 2048 : 2,
1394 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001395 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001396 block_id_map_.Put(block_id, block_id);
1397 return bb;
1398}
buzbee1fd33462013-03-25 13:40:45 -07001399
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001400void MIRGraph::InitializeConstantPropagation() {
1401 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001402 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001403}
1404
1405void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001406 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001407 int num_ssa_regs = GetNumSSARegs();
1408 use_counts_.Resize(num_ssa_regs + 32);
1409 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001410 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001411 for (int i = 0; i < num_ssa_regs; i++) {
1412 use_counts_.Insert(0);
1413 raw_use_counts_.Insert(0);
1414 }
1415}
1416
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001417void MIRGraph::SSATransformationStart() {
1418 DCHECK(temp_scoped_alloc_.get() == nullptr);
1419 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1420 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1421 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1422 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1423
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001424 // Update the maximum number of reachable blocks.
1425 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001426}
1427
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001428void MIRGraph::SSATransformationEnd() {
1429 // Verify the dataflow information after the pass.
1430 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1431 VerifyDataflow();
1432 }
1433
1434 temp_bit_vector_size_ = 0u;
1435 temp_bit_vector_ = nullptr;
1436 DCHECK(temp_scoped_alloc_.get() != nullptr);
1437 temp_scoped_alloc_.reset();
1438}
1439
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001440void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001441 // Clear the nodes.
1442 ClearAllVisitedFlags();
1443
1444 // Create the topological order if need be.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001445 if (topological_order_ == nullptr) {
1446 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, GetNumBlocks());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001447 }
1448 topological_order_->Reset();
1449
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001450 ScopedArenaAllocator allocator(&cu_->arena_stack);
1451 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1452 ScopedArenaVector<size_t> visited_cnt_values(GetNumBlocks(), 0u, allocator.Adapter());
1453
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001454 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1455 // also fill initial queue.
1456 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1457
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001458 size_t num_blocks = 0u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001459 while (true) {
1460 BasicBlock* bb = iterator.Next();
1461
1462 if (bb == nullptr) {
1463 break;
1464 }
1465
1466 if (bb->hidden == true) {
1467 continue;
1468 }
1469
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001470 num_blocks += 1u;
1471 size_t unvisited_predecessor_count = bb->predecessors->Size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001472
1473 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1474 // To process loops we should not wait for dominators.
1475 while (true) {
1476 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1477
1478 if (pred_bb == nullptr) {
1479 break;
1480 }
1481
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001482 // Skip the backward branch or hidden predecessor.
1483 if (pred_bb->hidden ||
1484 (pred_bb->dominators != nullptr && pred_bb->dominators->IsBitSet(bb->id))) {
1485 unvisited_predecessor_count -= 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001486 }
1487 }
1488
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001489 visited_cnt_values[bb->id] = unvisited_predecessor_count;
1490
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001491 // Add entry block to queue.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001492 if (unvisited_predecessor_count == 0) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001493 q.push(bb);
1494 }
1495 }
1496
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001497 // We can theoretically get a cycle where none of the blocks dominates the other. Therefore
1498 // don't stop when the queue is empty, continue until we've processed all the blocks.
1499 // (In practice, we've seen this for a monitor-exit catch handler that erroneously tries to
1500 // handle its own exceptions being broken into two blocks by a jump to to the monitor-exit
1501 // from another catch hanler. http://b/15745363 .)
1502 AllNodesIterator candidate_iter(this); // For the empty queue case.
1503 while (num_blocks != 0u) {
1504 num_blocks -= 1u;
1505 BasicBlock* bb = nullptr;
1506 if (!q.empty()) {
1507 // Get top.
1508 bb = q.front();
1509 q.pop();
1510 } else {
1511 // Find some block we didn't visit yet that has at least one visited predecessor.
1512 while (bb == nullptr) {
1513 BasicBlock* candidate = candidate_iter.Next();
1514 DCHECK(candidate != nullptr);
1515 if (candidate->visited || candidate->hidden) {
1516 continue;
1517 }
1518 GrowableArray<BasicBlockId>::Iterator iter(candidate->predecessors);
1519 for (BasicBlock* pred_bb = GetBasicBlock(iter.Next()); pred_bb != nullptr;
1520 pred_bb = GetBasicBlock(iter.Next())) {
1521 if (!pred_bb->hidden && pred_bb->visited) {
1522 bb = candidate;
1523 break;
1524 }
1525 }
1526 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001527 }
1528
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001529 DCHECK_EQ(bb->hidden, false);
1530 DCHECK_EQ(bb->visited, false);
1531
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001532 // We've visited all the predecessors. So, we can visit bb.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001533 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001534
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001535 // Now add the basic block.
1536 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001537
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001538 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1539 ChildBlockIterator succIter(bb, this);
1540 BasicBlock* successor = succIter.Next();
1541 for ( ; successor != nullptr; successor = succIter.Next()) {
1542 if (successor->visited || successor->hidden) {
1543 continue;
1544 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001545
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001546 // one more predecessor was visited.
1547 DCHECK_NE(visited_cnt_values[successor->id], 0u);
1548 visited_cnt_values[successor->id] -= 1u;
1549 if (visited_cnt_values[successor->id] == 0u) {
1550 q.push(successor);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001551 }
1552 }
1553 }
1554}
1555
1556bool BasicBlock::IsExceptionBlock() const {
1557 if (block_type == kExceptionHandling) {
1558 return true;
1559 }
1560 return false;
1561}
1562
Wei Jin04f4d8a2014-05-29 18:04:29 -07001563bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1564 BasicBlock* target = GetBasicBlock(target_id);
1565
1566 if (source == nullptr || target == nullptr)
1567 return false;
1568
1569 int idx;
1570 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1571 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1572 if (bb == source)
1573 return true; // The block has been inserted by a suspend check before.
1574 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1575 return true;
1576 }
1577
1578 return false;
1579}
1580
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001581ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1582 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1583 visited_taken_(false), have_successors_(false) {
1584 // Check if we actually do have successors.
1585 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1586 have_successors_ = true;
1587 successor_iter_.Reset(basic_block_->successor_blocks);
1588 }
1589}
1590
1591BasicBlock* ChildBlockIterator::Next() {
1592 // We check if we have a basic block. If we don't we cannot get next child.
1593 if (basic_block_ == nullptr) {
1594 return nullptr;
1595 }
1596
1597 // If we haven't visited fallthrough, return that.
1598 if (visited_fallthrough_ == false) {
1599 visited_fallthrough_ = true;
1600
1601 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1602 if (result != nullptr) {
1603 return result;
1604 }
1605 }
1606
1607 // If we haven't visited taken, return that.
1608 if (visited_taken_ == false) {
1609 visited_taken_ = true;
1610
1611 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1612 if (result != nullptr) {
1613 return result;
1614 }
1615 }
1616
1617 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1618 if (have_successors_ == true) {
1619 // Get information about next successor block.
1620 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1621
1622 // If we don't have anymore successors, return nullptr.
1623 if (successor_block_info != nullptr) {
1624 return mir_graph_->GetBasicBlock(successor_block_info->block);
1625 }
1626 }
1627
1628 // We do not have anything.
1629 return nullptr;
1630}
1631
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001632BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1633 MIRGraph* mir_graph = c_unit->mir_graph.get();
1634 return Copy(mir_graph);
1635}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001636
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001637BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1638 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001639
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001640 // We don't do a memcpy style copy here because it would lead to a lot of things
1641 // to clean up. Let us do it by hand instead.
1642 // Copy in taken and fallthrough.
1643 result_bb->fall_through = fall_through;
1644 result_bb->taken = taken;
1645
1646 // Copy successor links if needed.
1647 ArenaAllocator* arena = mir_graph->GetArena();
1648
1649 result_bb->successor_block_list_type = successor_block_list_type;
1650 if (result_bb->successor_block_list_type != kNotUsed) {
1651 size_t size = successor_blocks->Size();
1652 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1653 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1654 while (true) {
1655 SuccessorBlockInfo* sbi_old = iterator.Next();
1656 if (sbi_old == nullptr) {
1657 break;
1658 }
1659 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1660 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1661 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001662 }
1663 }
1664
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001665 // Copy offset, method.
1666 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001667
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001668 // Now copy instructions.
1669 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1670 // Get a copy first.
1671 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001672
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001673 // Append it.
1674 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001675 }
1676
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001677 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001678}
1679
1680MIR* MIR::Copy(MIRGraph* mir_graph) {
1681 MIR* res = mir_graph->NewMIR();
1682 *res = *this;
1683
1684 // Remove links
1685 res->next = nullptr;
1686 res->bb = NullBasicBlockId;
1687 res->ssa_rep = nullptr;
1688
1689 return res;
1690}
1691
1692MIR* MIR::Copy(CompilationUnit* c_unit) {
1693 return Copy(c_unit->mir_graph.get());
1694}
1695
1696uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1697 // Default result.
1698 int res = 0;
1699
1700 // We are basically setting the iputs to their igets counterparts.
1701 switch (opcode) {
1702 case Instruction::IPUT:
1703 case Instruction::IPUT_OBJECT:
1704 case Instruction::IPUT_BOOLEAN:
1705 case Instruction::IPUT_BYTE:
1706 case Instruction::IPUT_CHAR:
1707 case Instruction::IPUT_SHORT:
1708 case Instruction::IPUT_QUICK:
1709 case Instruction::IPUT_OBJECT_QUICK:
1710 case Instruction::APUT:
1711 case Instruction::APUT_OBJECT:
1712 case Instruction::APUT_BOOLEAN:
1713 case Instruction::APUT_BYTE:
1714 case Instruction::APUT_CHAR:
1715 case Instruction::APUT_SHORT:
1716 case Instruction::SPUT:
1717 case Instruction::SPUT_OBJECT:
1718 case Instruction::SPUT_BOOLEAN:
1719 case Instruction::SPUT_BYTE:
1720 case Instruction::SPUT_CHAR:
1721 case Instruction::SPUT_SHORT:
1722 // Skip the VR containing what to store.
1723 res = 1;
1724 break;
1725 case Instruction::IPUT_WIDE:
1726 case Instruction::IPUT_WIDE_QUICK:
1727 case Instruction::APUT_WIDE:
1728 case Instruction::SPUT_WIDE:
1729 // Skip the two VRs containing what to store.
1730 res = 2;
1731 break;
1732 default:
1733 // Do nothing in the general case.
1734 break;
1735 }
1736
1737 return res;
1738}
1739
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001740/**
1741 * @brief Given a decoded instruction, it checks whether the instruction
1742 * sets a constant and if it does, more information is provided about the
1743 * constant being set.
1744 * @param ptr_value pointer to a 64-bit holder for the constant.
1745 * @param wide Updated by function whether a wide constant is being set by bytecode.
1746 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1747 */
1748bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1749 bool sets_const = true;
1750 int64_t value = vB;
1751
1752 DCHECK(ptr_value != nullptr);
1753 DCHECK(wide != nullptr);
1754
1755 switch (opcode) {
1756 case Instruction::CONST_4:
1757 case Instruction::CONST_16:
1758 case Instruction::CONST:
1759 *wide = false;
1760 value <<= 32; // In order to get the sign extend.
1761 value >>= 32;
1762 break;
1763 case Instruction::CONST_HIGH16:
1764 *wide = false;
1765 value <<= 48; // In order to get the sign extend.
1766 value >>= 32;
1767 break;
1768 case Instruction::CONST_WIDE_16:
1769 case Instruction::CONST_WIDE_32:
1770 *wide = true;
1771 value <<= 32; // In order to get the sign extend.
1772 value >>= 32;
1773 break;
1774 case Instruction::CONST_WIDE:
1775 *wide = true;
1776 value = vB_wide;
1777 break;
1778 case Instruction::CONST_WIDE_HIGH16:
1779 *wide = true;
1780 value <<= 48; // In order to get the sign extend.
1781 break;
1782 default:
1783 sets_const = false;
1784 break;
1785 }
1786
1787 if (sets_const) {
1788 *ptr_value = value;
1789 }
1790
1791 return sets_const;
1792}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001793
1794void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1795 // Reset flags for all MIRs in bb.
1796 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1797 mir->optimization_flags &= (~reset_flags);
1798 }
1799}
1800
1801void BasicBlock::Hide(CompilationUnit* c_unit) {
1802 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1803 block_type = kDalvikByteCode;
1804
1805 // Mark it as hidden.
1806 hidden = true;
1807
1808 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1809 // are updated to know that they no longer have a parent.
1810 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1811 mir->bb = NullBasicBlockId;
1812 }
1813 first_mir_insn = nullptr;
1814 last_mir_insn = nullptr;
1815
1816 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1817
1818 MIRGraph* mir_graph = c_unit->mir_graph.get();
1819 while (true) {
1820 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1821 if (pred_bb == nullptr) {
1822 break;
1823 }
1824
1825 // Sadly we have to go through the children by hand here.
1826 pred_bb->ReplaceChild(id, NullBasicBlockId);
1827 }
1828
1829 // Iterate through children of bb we are hiding.
1830 ChildBlockIterator successorChildIter(this, mir_graph);
1831
1832 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1833 // Replace child with null child.
1834 childPtr->predecessors->Delete(id);
1835 }
1836}
1837
1838bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1839 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1840 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1841 // then it is not live out of this BB.
1842 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1843
1844 int last_ssa_reg = -1;
1845
1846 // Walk through the MIRs backwards.
1847 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1848 // Get ssa rep.
1849 SSARepresentation *ssa_rep = mir->ssa_rep;
1850
1851 // Go through the defines for this MIR.
1852 for (int i = 0; i < ssa_rep->num_defs; i++) {
1853 DCHECK(ssa_rep->defs != nullptr);
1854
1855 // Get the ssa reg.
1856 int def_ssa_reg = ssa_rep->defs[i];
1857
1858 // Get dalvik reg.
1859 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1860
1861 // Compare dalvik regs.
1862 if (dalvik_reg == def_dalvik_reg) {
1863 // We found a def of the register that we are being asked about.
1864 // Remember it.
1865 last_ssa_reg = def_ssa_reg;
1866 }
1867 }
1868 }
1869
1870 if (last_ssa_reg == -1) {
1871 // If we get to this point we couldn't find a define of register user asked about.
1872 // Let's assume the user knows what he's doing so we can be safe and say that if we
1873 // couldn't find a def, it is live out.
1874 return true;
1875 }
1876
1877 // If it is not -1, we found a match, is it ssa_reg?
1878 return (ssa_reg == last_ssa_reg);
1879}
1880
1881bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1882 // We need to check taken, fall_through, and successor_blocks to replace.
1883 bool found = false;
1884 if (taken == old_bb) {
1885 taken = new_bb;
1886 found = true;
1887 }
1888
1889 if (fall_through == old_bb) {
1890 fall_through = new_bb;
1891 found = true;
1892 }
1893
1894 if (successor_block_list_type != kNotUsed) {
1895 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1896 while (true) {
1897 SuccessorBlockInfo* successor_block_info = iterator.Next();
1898 if (successor_block_info == nullptr) {
1899 break;
1900 }
1901 if (successor_block_info->block == old_bb) {
1902 successor_block_info->block = new_bb;
1903 found = true;
1904 }
1905 }
1906 }
1907
1908 return found;
1909}
1910
1911void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1912 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1913 bool found = false;
1914
1915 while (true) {
1916 BasicBlockId pred_bb_id = iterator.Next();
1917
1918 if (pred_bb_id == NullBasicBlockId) {
1919 break;
1920 }
1921
1922 if (pred_bb_id == old_parent) {
1923 size_t idx = iterator.GetIndex() - 1;
1924 predecessors->Put(idx, new_parent);
1925 found = true;
1926 break;
1927 }
1928 }
1929
1930 // If not found, add it.
1931 if (found == false) {
1932 predecessors->Insert(new_parent);
1933 }
1934}
1935
1936// Create a new basic block with block_id as num_blocks_ that is
1937// post-incremented.
1938BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
1939 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
1940 block_list_.Insert(res);
1941 return res;
1942}
1943
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001944void MIRGraph::CalculateBasicBlockInformation() {
1945 PassDriverMEPostOpt driver(cu_);
1946 driver.Launch();
1947}
1948
1949void MIRGraph::InitializeBasicBlockData() {
1950 num_blocks_ = block_list_.Size();
1951}
1952
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001953} // namespace art