blob: 63a55707e565cde08963c9d0b6ebe4189f12879e [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 Marko5816ed42013-11-27 17:04:20 +000030
buzbee311ca162013-02-28 15:56:43 -080031namespace art {
32
33#define MAX_PATTERN_LEN 5
34
buzbee1fd33462013-03-25 13:40:45 -070035const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
36 "Phi",
37 "Copy",
38 "FusedCmplFloat",
39 "FusedCmpgFloat",
40 "FusedCmplDouble",
41 "FusedCmpgDouble",
42 "FusedCmpLong",
43 "Nop",
44 "OpNullCheck",
45 "OpRangeCheck",
46 "OpDivZeroCheck",
47 "Check1",
48 "Check2",
49 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040050 "ConstVector",
51 "MoveVector",
52 "PackedMultiply",
53 "PackedAddition",
54 "PackedSubtract",
55 "PackedShiftLeft",
56 "PackedSignedShiftRight",
57 "PackedUnsignedShiftRight",
58 "PackedAnd",
59 "PackedOr",
60 "PackedXor",
61 "PackedAddReduce",
62 "PackedReduce",
63 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070064};
65
buzbee862a7602013-04-05 10:58:54 -070066MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070067 : reg_location_(NULL),
68 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080069 ssa_base_vregs_(NULL),
70 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080071 vreg_to_ssa_map_(NULL),
72 ssa_last_defs_(NULL),
73 is_constant_v_(NULL),
74 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070075 use_counts_(arena, 256, kGrowableArrayMisc),
76 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080077 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070078 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070079 dfs_order_(NULL),
80 dfs_post_order_(NULL),
81 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070082 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080083 i_dom_list_(NULL),
84 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000085 temp_scoped_alloc_(),
86 temp_insn_data_(nullptr),
87 temp_bit_vector_size_(0u),
88 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070089 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080090 try_block_addr_(NULL),
91 entry_block_(NULL),
92 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080093 num_blocks_(0),
94 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070095 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080096 current_method_(kInvalidEntry),
97 current_offset_(kInvalidEntry),
98 def_count_(0),
99 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700100 num_ssa_regs_(0),
101 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700102 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
103 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700104 arena_(arena),
105 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800106 forward_branches_(0),
107 compiler_temps_(arena, 6, kGrowableArrayMisc),
108 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800109 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000110 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000111 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000112 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000113 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700114 method_lowering_infos_(arena, 0u),
115 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700116 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800117 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
118 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800119}
120
Ian Rogers6282dc12013-04-18 15:54:02 -0700121MIRGraph::~MIRGraph() {
122 STLDeleteElements(&m_units_);
123}
124
buzbee311ca162013-02-28 15:56:43 -0800125/*
126 * Parse an instruction, return the length of the instruction
127 */
Ian Rogers29a26482014-05-02 15:27:29 -0700128int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
129 const Instruction* inst = Instruction::At(code_ptr);
130 decoded_instruction->opcode = inst->Opcode();
131 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
132 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
133 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
134 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
135 if (inst->HasVarArgs()) {
136 inst->GetVarArgs(decoded_instruction->arg);
137 }
138 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800139}
140
141
142/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700143BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700144 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700145 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800146 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700147 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800148 while (insn) {
149 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700150 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800151 insn = insn->next;
152 }
153 if (insn == NULL) {
154 LOG(FATAL) << "Break split failed";
155 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700156 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700157 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800158
159 bottom_block->start_offset = code_offset;
160 bottom_block->first_mir_insn = insn;
161 bottom_block->last_mir_insn = orig_block->last_mir_insn;
162
163 /* If this block was terminated by a return, the flag needs to go with the bottom block */
164 bottom_block->terminated_by_return = orig_block->terminated_by_return;
165 orig_block->terminated_by_return = false;
166
buzbee311ca162013-02-28 15:56:43 -0800167 /* Handle the taken path */
168 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700169 if (bottom_block->taken != NullBasicBlockId) {
170 orig_block->taken = NullBasicBlockId;
171 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
172 bb_taken->predecessors->Delete(orig_block->id);
173 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800174 }
175
176 /* Handle the fallthrough path */
177 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700178 orig_block->fall_through = bottom_block->id;
179 bottom_block->predecessors->Insert(orig_block->id);
180 if (bottom_block->fall_through != NullBasicBlockId) {
181 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
182 bb_fall_through->predecessors->Delete(orig_block->id);
183 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800184 }
185
186 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700187 if (orig_block->successor_block_list_type != kNotUsed) {
188 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
189 bottom_block->successor_blocks = orig_block->successor_blocks;
190 orig_block->successor_block_list_type = kNotUsed;
191 orig_block->successor_blocks = NULL;
192 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800193 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700194 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800195 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700196 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700197 bb->predecessors->Delete(orig_block->id);
198 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800199 }
200 }
201
buzbee0d829482013-10-11 15:24:55 -0700202 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700203 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800204
buzbee311ca162013-02-28 15:56:43 -0800205 /*
206 * Update the immediate predecessor block pointer so that outgoing edges
207 * can be applied to the proper block.
208 */
209 if (immed_pred_block_p) {
210 DCHECK_EQ(*immed_pred_block_p, orig_block);
211 *immed_pred_block_p = bottom_block;
212 }
buzbeeb48819d2013-09-14 16:15:25 -0700213
214 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000215 DCHECK(insn != nullptr);
216 DCHECK(insn != orig_block->first_mir_insn);
217 DCHECK(insn == bottom_block->first_mir_insn);
218 DCHECK_EQ(insn->offset, bottom_block->start_offset);
219 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
220 !IsPseudoMirOp(insn->dalvikInsn.opcode));
221 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
222 MIR* p = insn;
223 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
224 while (p != bottom_block->last_mir_insn) {
225 p = p->next;
226 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700227 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700228 int opcode = p->dalvikInsn.opcode;
229 /*
230 * Some messiness here to ensure that we only enter real opcodes and only the
231 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000232 * CHECK and work portions. Since the 2nd half of a split operation is always
233 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700234 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000235 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
236 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700237 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
238 }
buzbeeb48819d2013-09-14 16:15:25 -0700239 }
240
buzbee311ca162013-02-28 15:56:43 -0800241 return bottom_block;
242}
243
244/*
245 * Given a code offset, find out the block that starts with it. If the offset
246 * is in the middle of an existing block, split it into two. If immed_pred_block_p
247 * is not non-null and is the block being split, update *immed_pred_block_p to
248 * point to the bottom block so that outgoing edges can be set up properly
249 * (by the caller)
250 * Utilizes a map for fast lookup of the typical cases.
251 */
buzbee0d829482013-10-11 15:24:55 -0700252BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700253 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700254 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800255 return NULL;
256 }
buzbeeb48819d2013-09-14 16:15:25 -0700257
258 int block_id = dex_pc_to_block_map_.Get(code_offset);
259 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
260
261 if ((bb != NULL) && (bb->start_offset == code_offset)) {
262 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700263 return bb;
264 }
buzbee311ca162013-02-28 15:56:43 -0800265
buzbeeb48819d2013-09-14 16:15:25 -0700266 // No direct hit.
267 if (!create) {
268 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800269 }
270
buzbeeb48819d2013-09-14 16:15:25 -0700271 if (bb != NULL) {
272 // The target exists somewhere in an existing block.
273 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
274 }
275
276 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700277 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
278 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800279 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700280 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800281 return bb;
282}
283
buzbeeb48819d2013-09-14 16:15:25 -0700284
buzbee311ca162013-02-28 15:56:43 -0800285/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700286void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800287 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700288 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800289
290 if (tries_size == 0) {
291 return;
292 }
293
294 for (int i = 0; i < tries_size; i++) {
295 const DexFile::TryItem* pTry =
296 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700297 DexOffset start_offset = pTry->start_addr_;
298 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800299 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700300 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800301 }
302 }
303
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700304 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800305 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
306 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
307 for (uint32_t idx = 0; idx < handlers_size; idx++) {
308 CatchHandlerIterator iterator(handlers_ptr);
309 for (; iterator.HasNext(); iterator.Next()) {
310 uint32_t address = iterator.GetHandlerAddress();
311 FindBlock(address, false /* split */, true /*create*/,
312 /* immed_pred_block_p */ NULL);
313 }
314 handlers_ptr = iterator.EndDataPointer();
315 }
316}
317
318/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700319BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
320 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700321 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700322 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800323 switch (insn->dalvikInsn.opcode) {
324 case Instruction::GOTO:
325 case Instruction::GOTO_16:
326 case Instruction::GOTO_32:
327 target += insn->dalvikInsn.vA;
328 break;
329 case Instruction::IF_EQ:
330 case Instruction::IF_NE:
331 case Instruction::IF_LT:
332 case Instruction::IF_GE:
333 case Instruction::IF_GT:
334 case Instruction::IF_LE:
335 cur_block->conditional_branch = true;
336 target += insn->dalvikInsn.vC;
337 break;
338 case Instruction::IF_EQZ:
339 case Instruction::IF_NEZ:
340 case Instruction::IF_LTZ:
341 case Instruction::IF_GEZ:
342 case Instruction::IF_GTZ:
343 case Instruction::IF_LEZ:
344 cur_block->conditional_branch = true;
345 target += insn->dalvikInsn.vB;
346 break;
347 default:
348 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
349 }
buzbeeb48819d2013-09-14 16:15:25 -0700350 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700351 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800352 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700353 cur_block->taken = taken_block->id;
354 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800355
356 /* Always terminate the current block for conditional branches */
357 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700358 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800359 /*
360 * If the method is processed
361 * in sequential order from the
362 * beginning, we don't need to
363 * specify split for continue
364 * blocks. However, this
365 * routine can be called by
366 * compileLoop, which starts
367 * parsing the method from an
368 * arbitrary address in the
369 * method body.
370 */
371 true,
372 /* create */
373 true,
374 /* immed_pred_block_p */
375 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700376 cur_block->fall_through = fallthrough_block->id;
377 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800378 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700379 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800380 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800381 }
382 return cur_block;
383}
384
385/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800386BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
387 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800388 const uint16_t* switch_data =
389 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
390 int size;
391 const int* keyTable;
392 const int* target_table;
393 int i;
394 int first_key;
395
396 /*
397 * Packed switch data format:
398 * ushort ident = 0x0100 magic value
399 * ushort size number of entries in the table
400 * int first_key first (and lowest) switch case value
401 * int targets[size] branch targets, relative to switch opcode
402 *
403 * Total size is (4+size*2) 16-bit code units.
404 */
405 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
406 DCHECK_EQ(static_cast<int>(switch_data[0]),
407 static_cast<int>(Instruction::kPackedSwitchSignature));
408 size = switch_data[1];
409 first_key = switch_data[2] | (switch_data[3] << 16);
410 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700411 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800412 /*
413 * Sparse switch data format:
414 * ushort ident = 0x0200 magic value
415 * ushort size number of entries in the table; > 0
416 * int keys[size] keys, sorted low-to-high; 32-bit aligned
417 * int targets[size] branch targets, relative to switch opcode
418 *
419 * Total size is (2+size*4) 16-bit code units.
420 */
421 } else {
422 DCHECK_EQ(static_cast<int>(switch_data[0]),
423 static_cast<int>(Instruction::kSparseSwitchSignature));
424 size = switch_data[1];
425 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
426 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700427 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800428 }
429
buzbee0d829482013-10-11 15:24:55 -0700430 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800431 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700432 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800433 }
buzbee0d829482013-10-11 15:24:55 -0700434 cur_block->successor_block_list_type =
435 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
436 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700437 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800438
439 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700440 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800441 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700442 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700443 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000444 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700445 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800446 successor_block_info->key =
447 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
448 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700449 cur_block->successor_blocks->Insert(successor_block_info);
450 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800451 }
452
453 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700454 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
455 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700456 cur_block->fall_through = fallthrough_block->id;
457 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800458 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800459}
460
461/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700462BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
463 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700464 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700465 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800466 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
467 bool build_all_edges =
468 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800469
470 /* In try block */
471 if (in_try_block) {
472 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
473
buzbee0d829482013-10-11 15:24:55 -0700474 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800475 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
476 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700477 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800478 }
479
buzbee0d829482013-10-11 15:24:55 -0700480 cur_block->successor_block_list_type = kCatch;
481 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700482 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800483
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700484 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700485 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800486 false /* creat */, NULL /* immed_pred_block_p */);
487 catch_block->catch_entry = true;
488 if (kIsDebugBuild) {
489 catches_.insert(catch_block->start_offset);
490 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700491 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000492 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700493 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800494 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700495 cur_block->successor_blocks->Insert(successor_block_info);
496 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800497 }
buzbee17189ac2013-11-08 11:07:02 -0800498 } else if (build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700499 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700500 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700501 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800502 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700503 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800504 }
505
buzbee17189ac2013-11-08 11:07:02 -0800506 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800507 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700508 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700509 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800510 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
511 /* immed_pred_block_p */ NULL);
512 }
513 if (!in_try_block) {
514 // Don't split a THROW that can't rethrow - we're done.
515 return cur_block;
516 }
517 }
518
buzbee17189ac2013-11-08 11:07:02 -0800519 if (!build_all_edges) {
520 /*
521 * Even though there is an exception edge here, control cannot return to this
522 * method. Thus, for the purposes of dataflow analysis and optimization, we can
523 * ignore the edge. Doing this reduces compile time, and increases the scope
524 * of the basic-block level optimization pass.
525 */
526 return cur_block;
527 }
528
buzbee311ca162013-02-28 15:56:43 -0800529 /*
530 * Split the potentially-throwing instruction into two parts.
531 * The first half will be a pseudo-op that captures the exception
532 * edges and terminates the basic block. It always falls through.
533 * Then, create a new basic block that begins with the throwing instruction
534 * (minus exceptions). Note: this new basic block must NOT be entered into
535 * the block_map. If the potentially-throwing instruction is the target of a
536 * future branch, we need to find the check psuedo half. The new
537 * basic block containing the work portion of the instruction should
538 * only be entered via fallthrough from the block containing the
539 * pseudo exception edge MIR. Note also that this new block is
540 * not automatically terminated after the work portion, and may
541 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700542 *
543 * Note also that the dex_pc_to_block_map_ entry for the potentially
544 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800545 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700546 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700547 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800548 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700549 cur_block->fall_through = new_block->id;
550 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700551 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800552 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700553 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700554 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800555 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700556 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800557 return new_block;
558}
559
560/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
561void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700562 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700563 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800564 current_code_item_ = code_item;
565 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
566 current_method_ = m_units_.size();
567 current_offset_ = 0;
568 // TODO: will need to snapshot stack image and use that as the mir context identification.
569 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000570 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
571 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800572 const uint16_t* code_ptr = current_code_item_->insns_;
573 const uint16_t* code_end =
574 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
575
576 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700577 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700578 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700579 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 -0700580
buzbee311ca162013-02-28 15:56:43 -0800581 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700582 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
583 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800584
585 // If this is the first method, set up default entry and exit blocks.
586 if (current_method_ == 0) {
587 DCHECK(entry_block_ == NULL);
588 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700589 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700590 // Use id 0 to represent a null block.
591 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
592 DCHECK_EQ(null_block->id, NullBasicBlockId);
593 null_block->hidden = true;
594 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700595 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700596 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700597 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700598 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800599 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
600 cu_->dex_file = &dex_file;
601 cu_->class_def_idx = class_def_idx;
602 cu_->method_idx = method_idx;
603 cu_->access_flags = access_flags;
604 cu_->invoke_type = invoke_type;
605 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
606 cu_->num_ins = current_code_item_->ins_size_;
607 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
608 cu_->num_outs = current_code_item_->outs_size_;
609 cu_->num_dalvik_registers = current_code_item_->registers_size_;
610 cu_->insns = current_code_item_->insns_;
611 cu_->code_item = current_code_item_;
612 } else {
613 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
614 /*
615 * Will need to manage storage for ins & outs, push prevous state and update
616 * insert point.
617 */
618 }
619
620 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700621 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700622 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800623 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700624 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700625 // TODO: for inlining support, insert at the insert point rather than entry block.
626 entry_block_->fall_through = cur_block->id;
627 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800628
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000629 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800630 ProcessTryCatchBlocks();
631
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000632 uint64_t merged_df_flags = 0u;
633
buzbee311ca162013-02-28 15:56:43 -0800634 /* Parse all instructions and put them into containing basic blocks */
635 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700636 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800637 insn->offset = current_offset_;
638 insn->m_unit_index = current_method_;
639 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800640 Instruction::Code opcode = insn->dalvikInsn.opcode;
641 if (opcode_count_ != NULL) {
642 opcode_count_[static_cast<int>(opcode)]++;
643 }
644
buzbee311ca162013-02-28 15:56:43 -0800645 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800646 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800647
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700648 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000649 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800650
651 if (df_flags & DF_HAS_DEFS) {
652 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
653 }
654
buzbee1da1e2f2013-11-15 13:37:01 -0800655 if (df_flags & DF_LVN) {
656 cur_block->use_lvn = true; // Run local value numbering on this basic block.
657 }
658
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700659 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700660 if (opcode == Instruction::NOP) {
661 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
662 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
663 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
664 uint16_t following_raw_instruction = code_ptr[1];
665 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
666 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
667 (following_raw_instruction == Instruction::kArrayDataSignature)) {
668 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
669 }
670 }
671 if (width == 1) {
672 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700673 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700674 } else {
buzbee0d829482013-10-11 15:24:55 -0700675 DCHECK(cur_block->fall_through == NullBasicBlockId);
676 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700677 // Unreachable instruction, mark for no continuation.
678 flags &= ~Instruction::kContinue;
679 }
680 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700681 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700682 }
683
buzbeeb48819d2013-09-14 16:15:25 -0700684 // Associate the starting dex_pc for this opcode with its containing basic block.
685 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
686
buzbee27247762013-07-28 12:03:58 -0700687 code_ptr += width;
688
buzbee311ca162013-02-28 15:56:43 -0800689 if (flags & Instruction::kBranch) {
690 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
691 width, flags, code_ptr, code_end);
692 } else if (flags & Instruction::kReturn) {
693 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700694 cur_block->fall_through = exit_block_->id;
695 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800696 /*
697 * Terminate the current block if there are instructions
698 * afterwards.
699 */
700 if (code_ptr < code_end) {
701 /*
702 * Create a fallthrough block for real instructions
703 * (incl. NOP).
704 */
buzbee27247762013-07-28 12:03:58 -0700705 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
706 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800707 }
708 } else if (flags & Instruction::kThrow) {
709 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
710 code_ptr, code_end);
711 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800712 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800713 }
buzbeeb1f1d642014-02-27 12:55:32 -0800714 if (verify_flags & Instruction::kVerifyVarArgRange) {
715 /*
716 * The Quick backend's runtime model includes a gap between a method's
717 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
718 * which spans the gap is somewhat complicated, and should not happen
719 * in normal usage of dx. Punt to the interpreter.
720 */
721 int first_reg_in_range = insn->dalvikInsn.vC;
722 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
723 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
724 punt_to_interpreter_ = true;
725 }
726 }
buzbee311ca162013-02-28 15:56:43 -0800727 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700728 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800729 false, /* immed_pred_block_p */ NULL);
730 if (next_block) {
731 /*
732 * The next instruction could be the target of a previously parsed
733 * forward branch so a block is already created. If the current
734 * instruction is not an unconditional branch, connect them through
735 * the fall-through link.
736 */
buzbee0d829482013-10-11 15:24:55 -0700737 DCHECK(cur_block->fall_through == NullBasicBlockId ||
738 GetBasicBlock(cur_block->fall_through) == next_block ||
739 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800740
buzbee0d829482013-10-11 15:24:55 -0700741 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
742 cur_block->fall_through = next_block->id;
743 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800744 }
745 cur_block = next_block;
746 }
747 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000748 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000749
buzbee311ca162013-02-28 15:56:43 -0800750 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
751 DumpCFG("/sdcard/1_post_parse_cfg/", true);
752 }
753
754 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700755 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800756 }
757}
758
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700759void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800760 DCHECK(opcode_count_ != NULL);
761 LOG(INFO) << "Opcode Count";
762 for (int i = 0; i < kNumPackedOpcodes; i++) {
763 if (opcode_count_[i] != 0) {
764 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
765 << " " << opcode_count_[i];
766 }
767 }
768}
769
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700770uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
771 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
772 return oat_data_flow_attributes_[opcode];
773}
774
775uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
776 DCHECK(mir != nullptr);
777 Instruction::Code opcode = mir->dalvikInsn.opcode;
778 return GetDataFlowAttributes(opcode);
779}
780
buzbee311ca162013-02-28 15:56:43 -0800781// TODO: use a configurable base prefix, and adjust callers to supply pass name.
782/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800783void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800784 FILE* file;
785 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
786 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800787 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
788 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
789 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800790 file = fopen(fname.c_str(), "w");
791 if (file == NULL) {
792 return;
793 }
794 fprintf(file, "digraph G {\n");
795
796 fprintf(file, " rankdir=TB\n");
797
798 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
799 int idx;
800
801 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700802 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700803 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700804 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800805 if (bb->block_type == kDead) continue;
806 if (bb->block_type == kEntryBlock) {
807 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
808 } else if (bb->block_type == kExitBlock) {
809 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
810 } else if (bb->block_type == kDalvikByteCode) {
811 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
812 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700813 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800814 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
815 bb->first_mir_insn ? " | " : " ");
816 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
817 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400818 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
819 if (opcode == kMirOpConstVector) {
820 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
821 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
822 mir->dalvikInsn.vA,
823 mir->dalvikInsn.vB,
824 mir->dalvikInsn.arg[0],
825 mir->dalvikInsn.arg[1],
826 mir->dalvikInsn.arg[2],
827 mir->dalvikInsn.arg[3],
828 mir->next ? " | " : " ");
829 } else {
830 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
831 extended_mir_op_names_[opcode - kMirOpFirst],
832 mir->dalvikInsn.vA,
833 mir->dalvikInsn.vB,
834 mir->dalvikInsn.vC,
835 mir->next ? " | " : " ");
836 }
837 } else {
838 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
839 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700840 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400841 extended_mir_op_names_[opcode - kMirOpFirst],
842 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
843 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
844 mir->next ? " | " : " ");
845 }
buzbee311ca162013-02-28 15:56:43 -0800846 }
847 fprintf(file, " }\"];\n\n");
848 } else if (bb->block_type == kExceptionHandling) {
849 char block_name[BLOCK_NAME_LEN];
850
851 GetBlockName(bb, block_name);
852 fprintf(file, " %s [shape=invhouse];\n", block_name);
853 }
854
855 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
856
buzbee0d829482013-10-11 15:24:55 -0700857 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800858 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700859 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800860 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
861 block_name1, block_name2);
862 }
buzbee0d829482013-10-11 15:24:55 -0700863 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800864 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700865 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800866 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
867 }
868
buzbee0d829482013-10-11 15:24:55 -0700869 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800870 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
871 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700872 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
873 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700874 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800875
876 int succ_id = 0;
877 while (true) {
878 if (successor_block_info == NULL) break;
879
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700880 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700881 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800882
883 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
884 succ_id++,
885 successor_block_info->key,
886 dest_block->start_offset,
887 (next_successor_block_info != NULL) ? " | " : " ");
888
889 successor_block_info = next_successor_block_info;
890 }
891 fprintf(file, " }\"];\n\n");
892
893 GetBlockName(bb, block_name1);
894 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
895 block_name1, bb->start_offset, bb->id);
896
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700897 // Link the successor pseudo-block with all of its potential targets.
898 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800899
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700900 succ_id = 0;
901 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700902 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700903 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800904
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700905 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800906
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700907 GetBlockName(dest_block, block_name2);
908 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
909 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800910 }
911 }
912 fprintf(file, "\n");
913
914 if (cu_->verbose) {
915 /* Display the dominator tree */
916 GetBlockName(bb, block_name1);
917 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
918 block_name1, block_name1);
919 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700920 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800921 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
922 }
923 }
924 }
925 fprintf(file, "}\n");
926 fclose(file);
927}
928
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700929/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700930void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700931 // Insert it after the last MIR.
932 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -0700933}
934
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700935void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
936 // Insert it after the last MIR.
937 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
938}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700939
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700940void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
941 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
942 MIR* new_mir = *it;
943
944 // Add a copy of each MIR.
945 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
946 }
buzbee1fd33462013-03-25 13:40:45 -0700947}
948
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700949/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700950void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700951 InsertMIRListAfter(current_mir, new_mir, new_mir);
952}
buzbee1fd33462013-03-25 13:40:45 -0700953
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700954void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
955 // If no MIR, we are done.
956 if (first_list_mir == nullptr || last_list_mir == nullptr) {
957 return;
buzbee1fd33462013-03-25 13:40:45 -0700958 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700959
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700960 // If insert_after is null, assume BB is empty.
961 if (insert_after == nullptr) {
962 first_mir_insn = first_list_mir;
963 last_mir_insn = last_list_mir;
964 last_list_mir->next = nullptr;
965 } else {
966 MIR* after_list = insert_after->next;
967 insert_after->next = first_list_mir;
968 last_list_mir->next = after_list;
969 if (after_list == nullptr) {
970 last_mir_insn = last_list_mir;
971 }
972 }
973
974 // Set this BB to be the basic block of the MIRs.
975 MIR* last = last_list_mir->next;
976 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
977 mir->bb = id;
978 }
979}
980
981/* Insert an MIR instruction to the head of a basic block. */
982void BasicBlock::PrependMIR(MIR* mir) {
983 InsertMIRListBefore(first_mir_insn, mir, mir);
984}
985
986void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
987 // Insert it before the first MIR.
988 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
989}
990
991void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
992 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
993 MIR* mir = *it;
994
995 InsertMIRListBefore(first_mir_insn, mir, mir);
996 }
997}
998
999/* Insert a MIR instruction before the specified MIR. */
1000void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1001 // Insert as a single element list.
1002 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001003}
1004
1005MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1006 MIR* current = first_mir_insn;
1007
1008 while (current != nullptr) {
1009 MIR* next = current->next;
1010
1011 if (next == mir) {
1012 return current;
1013 }
1014
1015 current = next;
1016 }
1017
1018 return nullptr;
1019}
1020
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001021void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1022 // If no MIR, we are done.
1023 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1024 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001025 }
1026
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001027 // If insert_before is null, assume BB is empty.
1028 if (insert_before == nullptr) {
1029 first_mir_insn = first_list_mir;
1030 last_mir_insn = last_list_mir;
1031 last_list_mir->next = nullptr;
1032 } else {
1033 if (first_mir_insn == insert_before) {
1034 last_list_mir->next = first_mir_insn;
1035 first_mir_insn = first_list_mir;
1036 } else {
1037 // Find the preceding MIR.
1038 MIR* before_list = FindPreviousMIR(insert_before);
1039 DCHECK(before_list != nullptr);
1040 before_list->next = first_list_mir;
1041 last_list_mir->next = insert_before;
1042 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001043 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001044
1045 // Set this BB to be the basic block of the MIRs.
1046 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1047 mir->bb = id;
1048 }
1049}
1050
1051bool BasicBlock::RemoveMIR(MIR* mir) {
1052 // Remove as a single element list.
1053 return RemoveMIRList(mir, mir);
1054}
1055
1056bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1057 if (first_list_mir == nullptr) {
1058 return false;
1059 }
1060
1061 // Try to find the MIR.
1062 MIR* before_list = nullptr;
1063 MIR* after_list = nullptr;
1064
1065 // If we are removing from the beginning of the MIR list.
1066 if (first_mir_insn == first_list_mir) {
1067 before_list = nullptr;
1068 } else {
1069 before_list = FindPreviousMIR(first_list_mir);
1070 if (before_list == nullptr) {
1071 // We did not find the mir.
1072 return false;
1073 }
1074 }
1075
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001076 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001077 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1078 mir->bb = NullBasicBlockId;
1079 }
1080
1081 after_list = last_list_mir->next;
1082
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001083 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001084 if (before_list == nullptr) {
1085 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001086 } else {
1087 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001088 }
1089
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001090 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001091 if (after_list == nullptr) {
1092 last_mir_insn = before_list;
1093 }
1094
1095 return true;
buzbee1fd33462013-03-25 13:40:45 -07001096}
1097
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001098MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001099 MIR* next_mir = nullptr;
1100
1101 if (current != nullptr) {
1102 next_mir = current->next;
1103 }
1104
1105 if (next_mir == nullptr) {
1106 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001107 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1108 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001109 }
1110 }
1111
1112 return next_mir;
1113}
1114
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001115char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001116 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001117 std::string str;
1118 int flags = 0;
1119 int opcode = insn.opcode;
1120 char* ret;
1121 bool nop = false;
1122 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001123 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001124 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1125 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1126
1127 // Handle special cases.
1128 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1129 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1130 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001131 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001132 insn = mir->meta.throw_insn->dalvikInsn;
1133 ssa_rep = mir->meta.throw_insn->ssa_rep;
1134 defs = ssa_rep->num_defs;
1135 uses = ssa_rep->num_uses;
1136 opcode = insn.opcode;
1137 } else if (opcode == kMirOpNop) {
1138 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001139 // Recover original opcode.
1140 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1141 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001142 nop = true;
1143 }
1144
buzbee35ba7f32014-05-31 08:59:01 -07001145 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001146 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1147 } else {
1148 dalvik_format = Instruction::FormatOf(insn.opcode);
1149 flags = Instruction::FlagsOf(insn.opcode);
1150 str.append(Instruction::Name(insn.opcode));
1151 }
1152
1153 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001154 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001155 str.append(StringPrintf(" %s = (%s",
1156 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1157 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001158 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001159 int i;
1160 for (i = 1; i < uses; i++) {
1161 str.append(StringPrintf(", %s:%d",
1162 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1163 incoming[i]));
1164 }
1165 str.append(")");
1166 } else if ((flags & Instruction::kBranch) != 0) {
1167 // For branches, decode the instructions to print out the branch targets.
1168 int offset = 0;
1169 switch (dalvik_format) {
1170 case Instruction::k21t:
1171 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1172 offset = insn.vB;
1173 break;
1174 case Instruction::k22t:
1175 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1176 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1177 offset = insn.vC;
1178 break;
1179 case Instruction::k10t:
1180 case Instruction::k20t:
1181 case Instruction::k30t:
1182 offset = insn.vA;
1183 break;
1184 default:
1185 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1186 }
1187 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1188 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1189 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001190 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001191 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1192 (dalvik_format == Instruction::k3rc));
1193 if (defs != 0) {
1194 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1195 if (uses != 0) {
1196 str.append(", ");
1197 }
1198 }
1199 for (int i = 0; i < uses; i++) {
1200 str.append(
1201 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1202 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1203 // For the listing, skip the high sreg.
1204 i++;
1205 }
1206 if (i != (uses -1)) {
1207 str.append(",");
1208 }
1209 }
1210 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001211 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001212 case Instruction::k21s:
1213 case Instruction::k31i:
1214 case Instruction::k21h:
1215 str.append(StringPrintf(", #%d", insn.vB));
1216 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001217 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001218 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001219 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001220 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001221 case Instruction::k31c:
1222 str.append(StringPrintf(", index #%d", insn.vB));
1223 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001224 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001225 str.append(StringPrintf(", index #%d", insn.vC));
1226 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001227 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001228 case Instruction::k22b:
1229 str.append(StringPrintf(", #%d", insn.vC));
1230 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001231 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001232 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001233 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001234 }
buzbee1fd33462013-03-25 13:40:45 -07001235 }
1236 if (nop) {
1237 str.append("]--optimized away");
1238 }
1239 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001240 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001241 strncpy(ret, str.c_str(), length);
1242 return ret;
1243}
1244
1245/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001246void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001247 static const struct { const char before; const char after; } match[] = {
1248 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1249 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1250 };
buzbee1fd33462013-03-25 13:40:45 -07001251 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1252 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1253 }
1254}
1255
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001256std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001257 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1258 // the arena. We should be smarter and just place straight into the arena, or compute the
1259 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001260 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1261}
1262
1263// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001264std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001265 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001266 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001267 return GetSSAName(ssa_reg);
1268 }
1269 if (IsConst(reg_location_[ssa_reg])) {
1270 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001271 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001272 ConstantValueWide(reg_location_[ssa_reg]));
1273 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001274 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001275 ConstantValue(reg_location_[ssa_reg]));
1276 }
1277 } else {
1278 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1279 }
1280}
1281
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001282void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001283 switch (bb->block_type) {
1284 case kEntryBlock:
1285 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1286 break;
1287 case kExitBlock:
1288 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1289 break;
1290 case kDalvikByteCode:
1291 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1292 break;
1293 case kExceptionHandling:
1294 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1295 bb->id);
1296 break;
1297 default:
1298 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1299 break;
1300 }
1301}
1302
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001303const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001304 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001305 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1306 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1307}
1308
1309/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001310void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001311 BasicBlock* bb;
1312 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001313 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001314 "Entry Block",
1315 "Code Block",
1316 "Exit Block",
1317 "Exception Handling",
1318 "Catch Block"
1319 };
1320
1321 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1322 LOG(INFO) << cu_->insns << " insns";
1323 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001324 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001325
1326 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001327 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001328 if (bb == NULL) break;
1329 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1330 bb->id,
1331 block_type_names[bb->block_type],
1332 bb->start_offset,
1333 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1334 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001335 if (bb->taken != NullBasicBlockId) {
1336 LOG(INFO) << " Taken branch: block " << bb->taken
1337 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001338 }
buzbee0d829482013-10-11 15:24:55 -07001339 if (bb->fall_through != NullBasicBlockId) {
1340 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1341 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001342 }
1343 }
1344}
1345
1346/*
1347 * Build an array of location records for the incoming arguments.
1348 * Note: one location record per word of arguments, with dummy
1349 * high-word loc for wide arguments. Also pull up any following
1350 * MOVE_RESULT and incorporate it into the invoke.
1351 */
1352CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001353 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001354 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001355 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001356 MIR* move_result_mir = FindMoveResult(bb, mir);
1357 if (move_result_mir == NULL) {
1358 info->result.location = kLocInvalid;
1359 } else {
1360 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001361 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1362 }
1363 info->num_arg_words = mir->ssa_rep->num_uses;
1364 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001365 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001366 for (int i = 0; i < info->num_arg_words; i++) {
1367 info->args[i] = GetRawSrc(mir, i);
1368 }
1369 info->opt_flags = mir->optimization_flags;
1370 info->type = type;
1371 info->is_range = is_range;
1372 info->index = mir->dalvikInsn.vB;
1373 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001374 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001375 return info;
1376}
1377
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001378// Allocate a new MIR.
1379MIR* MIRGraph::NewMIR() {
1380 MIR* mir = new (arena_) MIR();
1381 return mir;
1382}
1383
buzbee862a7602013-04-05 10:58:54 -07001384// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001385BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001386 BasicBlock* bb = new (arena_) BasicBlock();
1387
buzbee862a7602013-04-05 10:58:54 -07001388 bb->block_type = block_type;
1389 bb->id = block_id;
1390 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001391 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001392 (block_type == kExitBlock) ? 2048 : 2,
1393 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001394 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001395 block_id_map_.Put(block_id, block_id);
1396 return bb;
1397}
buzbee1fd33462013-03-25 13:40:45 -07001398
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001399void MIRGraph::InitializeConstantPropagation() {
1400 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001401 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001402}
1403
1404void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001405 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001406 int num_ssa_regs = GetNumSSARegs();
1407 use_counts_.Resize(num_ssa_regs + 32);
1408 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001409 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001410 for (int i = 0; i < num_ssa_regs; i++) {
1411 use_counts_.Insert(0);
1412 raw_use_counts_.Insert(0);
1413 }
1414}
1415
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001416void MIRGraph::SSATransformationStart() {
1417 DCHECK(temp_scoped_alloc_.get() == nullptr);
1418 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1419 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1420 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1421 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1422
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001423 // Update the maximum number of reachable blocks.
1424 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001425}
1426
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001427void MIRGraph::SSATransformationEnd() {
1428 // Verify the dataflow information after the pass.
1429 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1430 VerifyDataflow();
1431 }
1432
1433 temp_bit_vector_size_ = 0u;
1434 temp_bit_vector_ = nullptr;
1435 DCHECK(temp_scoped_alloc_.get() != nullptr);
1436 temp_scoped_alloc_.reset();
1437}
1438
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001439void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001440 std::queue<BasicBlock*> q;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001441 std::map<int, int> visited_cnt_values;
1442
1443 // Clear the nodes.
1444 ClearAllVisitedFlags();
1445
1446 // Create the topological order if need be.
1447 if (topological_order_ != nullptr) {
1448 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, 0);
1449 }
1450 topological_order_->Reset();
1451
1452 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1453 // also fill initial queue.
1454 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1455
1456 while (true) {
1457 BasicBlock* bb = iterator.Next();
1458
1459 if (bb == nullptr) {
1460 break;
1461 }
1462
1463 if (bb->hidden == true) {
1464 continue;
1465 }
1466
1467 visited_cnt_values[bb->id] = bb->predecessors->Size();
1468
1469 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1470 // To process loops we should not wait for dominators.
1471 while (true) {
1472 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1473
1474 if (pred_bb == nullptr) {
1475 break;
1476 }
1477
1478 if (pred_bb->dominators == nullptr || pred_bb->hidden == true) {
1479 continue;
1480 }
1481
1482 // Skip the backward branch.
1483 if (pred_bb->dominators->IsBitSet(bb->id) != 0) {
1484 visited_cnt_values[bb->id]--;
1485 }
1486 }
1487
1488 // Add entry block to queue.
1489 if (visited_cnt_values[bb->id] == 0) {
1490 q.push(bb);
1491 }
1492 }
1493
1494 while (q.size() > 0) {
1495 // Get top.
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001496 BasicBlock* bb = q.front();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001497 q.pop();
1498
1499 DCHECK_EQ(bb->hidden, false);
1500
1501 if (bb->IsExceptionBlock() == true) {
1502 continue;
1503 }
1504
1505 // We've visited all the predecessors. So, we can visit bb.
1506 if (bb->visited == false) {
1507 bb->visited = true;
1508
1509 // Now add the basic block.
1510 topological_order_->Insert(bb->id);
1511
1512 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1513 ChildBlockIterator succIter(bb, this);
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001514 BasicBlock* successor = succIter.Next();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001515 while (successor != nullptr) {
1516 // one more predecessor was visited.
1517 visited_cnt_values[successor->id]--;
1518
1519 if (visited_cnt_values[successor->id] <= 0 && successor->visited == false && successor->hidden == false) {
1520 q.push(successor);
1521 }
1522
1523 // Take next successor.
1524 successor = succIter.Next();
1525 }
1526 }
1527 }
1528}
1529
1530bool BasicBlock::IsExceptionBlock() const {
1531 if (block_type == kExceptionHandling) {
1532 return true;
1533 }
1534 return false;
1535}
1536
Wei Jin04f4d8a2014-05-29 18:04:29 -07001537bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1538 BasicBlock* target = GetBasicBlock(target_id);
1539
1540 if (source == nullptr || target == nullptr)
1541 return false;
1542
1543 int idx;
1544 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1545 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1546 if (bb == source)
1547 return true; // The block has been inserted by a suspend check before.
1548 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1549 return true;
1550 }
1551
1552 return false;
1553}
1554
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001555ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1556 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1557 visited_taken_(false), have_successors_(false) {
1558 // Check if we actually do have successors.
1559 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1560 have_successors_ = true;
1561 successor_iter_.Reset(basic_block_->successor_blocks);
1562 }
1563}
1564
1565BasicBlock* ChildBlockIterator::Next() {
1566 // We check if we have a basic block. If we don't we cannot get next child.
1567 if (basic_block_ == nullptr) {
1568 return nullptr;
1569 }
1570
1571 // If we haven't visited fallthrough, return that.
1572 if (visited_fallthrough_ == false) {
1573 visited_fallthrough_ = true;
1574
1575 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1576 if (result != nullptr) {
1577 return result;
1578 }
1579 }
1580
1581 // If we haven't visited taken, return that.
1582 if (visited_taken_ == false) {
1583 visited_taken_ = true;
1584
1585 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1586 if (result != nullptr) {
1587 return result;
1588 }
1589 }
1590
1591 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1592 if (have_successors_ == true) {
1593 // Get information about next successor block.
1594 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1595
1596 // If we don't have anymore successors, return nullptr.
1597 if (successor_block_info != nullptr) {
1598 return mir_graph_->GetBasicBlock(successor_block_info->block);
1599 }
1600 }
1601
1602 // We do not have anything.
1603 return nullptr;
1604}
1605
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001606BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1607 MIRGraph* mir_graph = c_unit->mir_graph.get();
1608 return Copy(mir_graph);
1609}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001610
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001611BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1612 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001613
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001614 // We don't do a memcpy style copy here because it would lead to a lot of things
1615 // to clean up. Let us do it by hand instead.
1616 // Copy in taken and fallthrough.
1617 result_bb->fall_through = fall_through;
1618 result_bb->taken = taken;
1619
1620 // Copy successor links if needed.
1621 ArenaAllocator* arena = mir_graph->GetArena();
1622
1623 result_bb->successor_block_list_type = successor_block_list_type;
1624 if (result_bb->successor_block_list_type != kNotUsed) {
1625 size_t size = successor_blocks->Size();
1626 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1627 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1628 while (true) {
1629 SuccessorBlockInfo* sbi_old = iterator.Next();
1630 if (sbi_old == nullptr) {
1631 break;
1632 }
1633 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1634 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1635 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001636 }
1637 }
1638
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001639 // Copy offset, method.
1640 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001641
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001642 // Now copy instructions.
1643 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1644 // Get a copy first.
1645 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001646
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001647 // Append it.
1648 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001649 }
1650
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001651 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001652}
1653
1654MIR* MIR::Copy(MIRGraph* mir_graph) {
1655 MIR* res = mir_graph->NewMIR();
1656 *res = *this;
1657
1658 // Remove links
1659 res->next = nullptr;
1660 res->bb = NullBasicBlockId;
1661 res->ssa_rep = nullptr;
1662
1663 return res;
1664}
1665
1666MIR* MIR::Copy(CompilationUnit* c_unit) {
1667 return Copy(c_unit->mir_graph.get());
1668}
1669
1670uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1671 // Default result.
1672 int res = 0;
1673
1674 // We are basically setting the iputs to their igets counterparts.
1675 switch (opcode) {
1676 case Instruction::IPUT:
1677 case Instruction::IPUT_OBJECT:
1678 case Instruction::IPUT_BOOLEAN:
1679 case Instruction::IPUT_BYTE:
1680 case Instruction::IPUT_CHAR:
1681 case Instruction::IPUT_SHORT:
1682 case Instruction::IPUT_QUICK:
1683 case Instruction::IPUT_OBJECT_QUICK:
1684 case Instruction::APUT:
1685 case Instruction::APUT_OBJECT:
1686 case Instruction::APUT_BOOLEAN:
1687 case Instruction::APUT_BYTE:
1688 case Instruction::APUT_CHAR:
1689 case Instruction::APUT_SHORT:
1690 case Instruction::SPUT:
1691 case Instruction::SPUT_OBJECT:
1692 case Instruction::SPUT_BOOLEAN:
1693 case Instruction::SPUT_BYTE:
1694 case Instruction::SPUT_CHAR:
1695 case Instruction::SPUT_SHORT:
1696 // Skip the VR containing what to store.
1697 res = 1;
1698 break;
1699 case Instruction::IPUT_WIDE:
1700 case Instruction::IPUT_WIDE_QUICK:
1701 case Instruction::APUT_WIDE:
1702 case Instruction::SPUT_WIDE:
1703 // Skip the two VRs containing what to store.
1704 res = 2;
1705 break;
1706 default:
1707 // Do nothing in the general case.
1708 break;
1709 }
1710
1711 return res;
1712}
1713
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001714/**
1715 * @brief Given a decoded instruction, it checks whether the instruction
1716 * sets a constant and if it does, more information is provided about the
1717 * constant being set.
1718 * @param ptr_value pointer to a 64-bit holder for the constant.
1719 * @param wide Updated by function whether a wide constant is being set by bytecode.
1720 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1721 */
1722bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1723 bool sets_const = true;
1724 int64_t value = vB;
1725
1726 DCHECK(ptr_value != nullptr);
1727 DCHECK(wide != nullptr);
1728
1729 switch (opcode) {
1730 case Instruction::CONST_4:
1731 case Instruction::CONST_16:
1732 case Instruction::CONST:
1733 *wide = false;
1734 value <<= 32; // In order to get the sign extend.
1735 value >>= 32;
1736 break;
1737 case Instruction::CONST_HIGH16:
1738 *wide = false;
1739 value <<= 48; // In order to get the sign extend.
1740 value >>= 32;
1741 break;
1742 case Instruction::CONST_WIDE_16:
1743 case Instruction::CONST_WIDE_32:
1744 *wide = true;
1745 value <<= 32; // In order to get the sign extend.
1746 value >>= 32;
1747 break;
1748 case Instruction::CONST_WIDE:
1749 *wide = true;
1750 value = vB_wide;
1751 break;
1752 case Instruction::CONST_WIDE_HIGH16:
1753 *wide = true;
1754 value <<= 48; // In order to get the sign extend.
1755 break;
1756 default:
1757 sets_const = false;
1758 break;
1759 }
1760
1761 if (sets_const) {
1762 *ptr_value = value;
1763 }
1764
1765 return sets_const;
1766}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001767
1768void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1769 // Reset flags for all MIRs in bb.
1770 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1771 mir->optimization_flags &= (~reset_flags);
1772 }
1773}
1774
1775void BasicBlock::Hide(CompilationUnit* c_unit) {
1776 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1777 block_type = kDalvikByteCode;
1778
1779 // Mark it as hidden.
1780 hidden = true;
1781
1782 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1783 // are updated to know that they no longer have a parent.
1784 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1785 mir->bb = NullBasicBlockId;
1786 }
1787 first_mir_insn = nullptr;
1788 last_mir_insn = nullptr;
1789
1790 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1791
1792 MIRGraph* mir_graph = c_unit->mir_graph.get();
1793 while (true) {
1794 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1795 if (pred_bb == nullptr) {
1796 break;
1797 }
1798
1799 // Sadly we have to go through the children by hand here.
1800 pred_bb->ReplaceChild(id, NullBasicBlockId);
1801 }
1802
1803 // Iterate through children of bb we are hiding.
1804 ChildBlockIterator successorChildIter(this, mir_graph);
1805
1806 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1807 // Replace child with null child.
1808 childPtr->predecessors->Delete(id);
1809 }
1810}
1811
1812bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1813 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1814 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1815 // then it is not live out of this BB.
1816 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1817
1818 int last_ssa_reg = -1;
1819
1820 // Walk through the MIRs backwards.
1821 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1822 // Get ssa rep.
1823 SSARepresentation *ssa_rep = mir->ssa_rep;
1824
1825 // Go through the defines for this MIR.
1826 for (int i = 0; i < ssa_rep->num_defs; i++) {
1827 DCHECK(ssa_rep->defs != nullptr);
1828
1829 // Get the ssa reg.
1830 int def_ssa_reg = ssa_rep->defs[i];
1831
1832 // Get dalvik reg.
1833 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1834
1835 // Compare dalvik regs.
1836 if (dalvik_reg == def_dalvik_reg) {
1837 // We found a def of the register that we are being asked about.
1838 // Remember it.
1839 last_ssa_reg = def_ssa_reg;
1840 }
1841 }
1842 }
1843
1844 if (last_ssa_reg == -1) {
1845 // If we get to this point we couldn't find a define of register user asked about.
1846 // Let's assume the user knows what he's doing so we can be safe and say that if we
1847 // couldn't find a def, it is live out.
1848 return true;
1849 }
1850
1851 // If it is not -1, we found a match, is it ssa_reg?
1852 return (ssa_reg == last_ssa_reg);
1853}
1854
1855bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1856 // We need to check taken, fall_through, and successor_blocks to replace.
1857 bool found = false;
1858 if (taken == old_bb) {
1859 taken = new_bb;
1860 found = true;
1861 }
1862
1863 if (fall_through == old_bb) {
1864 fall_through = new_bb;
1865 found = true;
1866 }
1867
1868 if (successor_block_list_type != kNotUsed) {
1869 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1870 while (true) {
1871 SuccessorBlockInfo* successor_block_info = iterator.Next();
1872 if (successor_block_info == nullptr) {
1873 break;
1874 }
1875 if (successor_block_info->block == old_bb) {
1876 successor_block_info->block = new_bb;
1877 found = true;
1878 }
1879 }
1880 }
1881
1882 return found;
1883}
1884
1885void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1886 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1887 bool found = false;
1888
1889 while (true) {
1890 BasicBlockId pred_bb_id = iterator.Next();
1891
1892 if (pred_bb_id == NullBasicBlockId) {
1893 break;
1894 }
1895
1896 if (pred_bb_id == old_parent) {
1897 size_t idx = iterator.GetIndex() - 1;
1898 predecessors->Put(idx, new_parent);
1899 found = true;
1900 break;
1901 }
1902 }
1903
1904 // If not found, add it.
1905 if (found == false) {
1906 predecessors->Insert(new_parent);
1907 }
1908}
1909
1910// Create a new basic block with block_id as num_blocks_ that is
1911// post-incremented.
1912BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
1913 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
1914 block_list_.Insert(res);
1915 return res;
1916}
1917
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001918void MIRGraph::CalculateBasicBlockInformation() {
1919 PassDriverMEPostOpt driver(cu_);
1920 driver.Launch();
1921}
1922
1923void MIRGraph::InitializeBasicBlockData() {
1924 num_blocks_ = block_list_.Size();
1925}
1926
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001927} // namespace art