blob: 08d1bca9af0af79f35fc70f51d030a3862e163ce [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>
20
Ian Rogers6282dc12013-04-18 15:54:02 -070021#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080022#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070024#include "dex_instruction-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000025#include "dex/quick/dex_file_to_method_inliner_map.h"
26#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000027#include "leb128.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000028
buzbee311ca162013-02-28 15:56:43 -080029namespace art {
30
31#define MAX_PATTERN_LEN 5
32
buzbee1fd33462013-03-25 13:40:45 -070033const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
34 "Phi",
35 "Copy",
36 "FusedCmplFloat",
37 "FusedCmpgFloat",
38 "FusedCmplDouble",
39 "FusedCmpgDouble",
40 "FusedCmpLong",
41 "Nop",
42 "OpNullCheck",
43 "OpRangeCheck",
44 "OpDivZeroCheck",
45 "Check1",
46 "Check2",
47 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040048 "ConstVector",
49 "MoveVector",
50 "PackedMultiply",
51 "PackedAddition",
52 "PackedSubtract",
53 "PackedShiftLeft",
54 "PackedSignedShiftRight",
55 "PackedUnsignedShiftRight",
56 "PackedAnd",
57 "PackedOr",
58 "PackedXor",
59 "PackedAddReduce",
60 "PackedReduce",
61 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070062};
63
buzbee862a7602013-04-05 10:58:54 -070064MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070065 : reg_location_(NULL),
66 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080067 ssa_base_vregs_(NULL),
68 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080069 vreg_to_ssa_map_(NULL),
70 ssa_last_defs_(NULL),
71 is_constant_v_(NULL),
72 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070073 use_counts_(arena, 256, kGrowableArrayMisc),
74 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080075 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070076 dfs_order_(NULL),
77 dfs_post_order_(NULL),
78 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080079 i_dom_list_(NULL),
80 def_block_matrix_(NULL),
buzbee311ca162013-02-28 15:56:43 -080081 temp_dalvik_register_v_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000082 temp_scoped_alloc_(),
83 temp_insn_data_(nullptr),
84 temp_bit_vector_size_(0u),
85 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070086 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080087 try_block_addr_(NULL),
88 entry_block_(NULL),
89 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080090 num_blocks_(0),
91 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070092 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080093 current_method_(kInvalidEntry),
94 current_offset_(kInvalidEntry),
95 def_count_(0),
96 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070097 num_ssa_regs_(0),
98 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -070099 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
100 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700101 arena_(arena),
102 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800103 forward_branches_(0),
104 compiler_temps_(arena, 6, kGrowableArrayMisc),
105 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800106 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000107 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000108 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000109 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000110 sfield_lowering_infos_(arena, 0u),
111 method_lowering_infos_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700112 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800113 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
114 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800115}
116
Ian Rogers6282dc12013-04-18 15:54:02 -0700117MIRGraph::~MIRGraph() {
118 STLDeleteElements(&m_units_);
119}
120
buzbee311ca162013-02-28 15:56:43 -0800121/*
122 * Parse an instruction, return the length of the instruction
123 */
Ian Rogers29a26482014-05-02 15:27:29 -0700124int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
125 const Instruction* inst = Instruction::At(code_ptr);
126 decoded_instruction->opcode = inst->Opcode();
127 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
128 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
129 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
130 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
131 if (inst->HasVarArgs()) {
132 inst->GetVarArgs(decoded_instruction->arg);
133 }
134 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800135}
136
137
138/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700139BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700140 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700141 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800142 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700143 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800144 while (insn) {
145 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700146 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800147 insn = insn->next;
148 }
149 if (insn == NULL) {
150 LOG(FATAL) << "Break split failed";
151 }
buzbee862a7602013-04-05 10:58:54 -0700152 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
153 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800154
155 bottom_block->start_offset = code_offset;
156 bottom_block->first_mir_insn = insn;
157 bottom_block->last_mir_insn = orig_block->last_mir_insn;
158
159 /* If this block was terminated by a return, the flag needs to go with the bottom block */
160 bottom_block->terminated_by_return = orig_block->terminated_by_return;
161 orig_block->terminated_by_return = false;
162
buzbee311ca162013-02-28 15:56:43 -0800163 /* Handle the taken path */
164 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700165 if (bottom_block->taken != NullBasicBlockId) {
166 orig_block->taken = NullBasicBlockId;
167 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
168 bb_taken->predecessors->Delete(orig_block->id);
169 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800170 }
171
172 /* Handle the fallthrough path */
173 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700174 orig_block->fall_through = bottom_block->id;
175 bottom_block->predecessors->Insert(orig_block->id);
176 if (bottom_block->fall_through != NullBasicBlockId) {
177 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
178 bb_fall_through->predecessors->Delete(orig_block->id);
179 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800180 }
181
182 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700183 if (orig_block->successor_block_list_type != kNotUsed) {
184 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
185 bottom_block->successor_blocks = orig_block->successor_blocks;
186 orig_block->successor_block_list_type = kNotUsed;
187 orig_block->successor_blocks = NULL;
188 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800189 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700190 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800191 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700192 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
193 bb->predecessors->Delete(orig_block->id);
194 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800195 }
196 }
197
buzbee0d829482013-10-11 15:24:55 -0700198 orig_block->last_mir_insn = prev;
199 prev->next = NULL;
buzbee311ca162013-02-28 15:56:43 -0800200
buzbee311ca162013-02-28 15:56:43 -0800201 /*
202 * Update the immediate predecessor block pointer so that outgoing edges
203 * can be applied to the proper block.
204 */
205 if (immed_pred_block_p) {
206 DCHECK_EQ(*immed_pred_block_p, orig_block);
207 *immed_pred_block_p = bottom_block;
208 }
buzbeeb48819d2013-09-14 16:15:25 -0700209
210 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000211 DCHECK(insn != nullptr);
212 DCHECK(insn != orig_block->first_mir_insn);
213 DCHECK(insn == bottom_block->first_mir_insn);
214 DCHECK_EQ(insn->offset, bottom_block->start_offset);
215 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
216 !IsPseudoMirOp(insn->dalvikInsn.opcode));
217 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
218 MIR* p = insn;
219 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
220 while (p != bottom_block->last_mir_insn) {
221 p = p->next;
222 DCHECK(p != nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700223 int opcode = p->dalvikInsn.opcode;
224 /*
225 * Some messiness here to ensure that we only enter real opcodes and only the
226 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000227 * CHECK and work portions. Since the 2nd half of a split operation is always
228 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700229 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000230 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
231 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700232 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
233 }
buzbeeb48819d2013-09-14 16:15:25 -0700234 }
235
buzbee311ca162013-02-28 15:56:43 -0800236 return bottom_block;
237}
238
239/*
240 * Given a code offset, find out the block that starts with it. If the offset
241 * is in the middle of an existing block, split it into two. If immed_pred_block_p
242 * is not non-null and is the block being split, update *immed_pred_block_p to
243 * point to the bottom block so that outgoing edges can be set up properly
244 * (by the caller)
245 * Utilizes a map for fast lookup of the typical cases.
246 */
buzbee0d829482013-10-11 15:24:55 -0700247BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700248 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700249 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800250 return NULL;
251 }
buzbeeb48819d2013-09-14 16:15:25 -0700252
253 int block_id = dex_pc_to_block_map_.Get(code_offset);
254 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
255
256 if ((bb != NULL) && (bb->start_offset == code_offset)) {
257 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700258 return bb;
259 }
buzbee311ca162013-02-28 15:56:43 -0800260
buzbeeb48819d2013-09-14 16:15:25 -0700261 // No direct hit.
262 if (!create) {
263 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800264 }
265
buzbeeb48819d2013-09-14 16:15:25 -0700266 if (bb != NULL) {
267 // The target exists somewhere in an existing block.
268 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
269 }
270
271 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700272 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
273 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800274 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700275 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800276 return bb;
277}
278
buzbeeb48819d2013-09-14 16:15:25 -0700279
buzbee311ca162013-02-28 15:56:43 -0800280/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700281void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800282 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700283 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800284
285 if (tries_size == 0) {
286 return;
287 }
288
289 for (int i = 0; i < tries_size; i++) {
290 const DexFile::TryItem* pTry =
291 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700292 DexOffset start_offset = pTry->start_addr_;
293 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800294 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700295 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800296 }
297 }
298
299 // Iterate over each of the handlers to enqueue the empty Catch blocks
300 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
301 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
302 for (uint32_t idx = 0; idx < handlers_size; idx++) {
303 CatchHandlerIterator iterator(handlers_ptr);
304 for (; iterator.HasNext(); iterator.Next()) {
305 uint32_t address = iterator.GetHandlerAddress();
306 FindBlock(address, false /* split */, true /*create*/,
307 /* immed_pred_block_p */ NULL);
308 }
309 handlers_ptr = iterator.EndDataPointer();
310 }
311}
312
313/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700314BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
315 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700316 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700317 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800318 switch (insn->dalvikInsn.opcode) {
319 case Instruction::GOTO:
320 case Instruction::GOTO_16:
321 case Instruction::GOTO_32:
322 target += insn->dalvikInsn.vA;
323 break;
324 case Instruction::IF_EQ:
325 case Instruction::IF_NE:
326 case Instruction::IF_LT:
327 case Instruction::IF_GE:
328 case Instruction::IF_GT:
329 case Instruction::IF_LE:
330 cur_block->conditional_branch = true;
331 target += insn->dalvikInsn.vC;
332 break;
333 case Instruction::IF_EQZ:
334 case Instruction::IF_NEZ:
335 case Instruction::IF_LTZ:
336 case Instruction::IF_GEZ:
337 case Instruction::IF_GTZ:
338 case Instruction::IF_LEZ:
339 cur_block->conditional_branch = true;
340 target += insn->dalvikInsn.vB;
341 break;
342 default:
343 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
344 }
buzbeeb48819d2013-09-14 16:15:25 -0700345 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800346 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
347 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700348 cur_block->taken = taken_block->id;
349 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800350
351 /* Always terminate the current block for conditional branches */
352 if (flags & Instruction::kContinue) {
353 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
354 /*
355 * If the method is processed
356 * in sequential order from the
357 * beginning, we don't need to
358 * specify split for continue
359 * blocks. However, this
360 * routine can be called by
361 * compileLoop, which starts
362 * parsing the method from an
363 * arbitrary address in the
364 * method body.
365 */
366 true,
367 /* create */
368 true,
369 /* immed_pred_block_p */
370 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700371 cur_block->fall_through = fallthrough_block->id;
372 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800373 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700374 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800375 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800376 }
377 return cur_block;
378}
379
380/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800381BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
382 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800383 const uint16_t* switch_data =
384 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
385 int size;
386 const int* keyTable;
387 const int* target_table;
388 int i;
389 int first_key;
390
391 /*
392 * Packed switch data format:
393 * ushort ident = 0x0100 magic value
394 * ushort size number of entries in the table
395 * int first_key first (and lowest) switch case value
396 * int targets[size] branch targets, relative to switch opcode
397 *
398 * Total size is (4+size*2) 16-bit code units.
399 */
400 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
401 DCHECK_EQ(static_cast<int>(switch_data[0]),
402 static_cast<int>(Instruction::kPackedSwitchSignature));
403 size = switch_data[1];
404 first_key = switch_data[2] | (switch_data[3] << 16);
405 target_table = reinterpret_cast<const int*>(&switch_data[4]);
406 keyTable = NULL; // Make the compiler happy
407 /*
408 * Sparse switch data format:
409 * ushort ident = 0x0200 magic value
410 * ushort size number of entries in the table; > 0
411 * int keys[size] keys, sorted low-to-high; 32-bit aligned
412 * int targets[size] branch targets, relative to switch opcode
413 *
414 * Total size is (2+size*4) 16-bit code units.
415 */
416 } else {
417 DCHECK_EQ(static_cast<int>(switch_data[0]),
418 static_cast<int>(Instruction::kSparseSwitchSignature));
419 size = switch_data[1];
420 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
421 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
422 first_key = 0; // To make the compiler happy
423 }
424
buzbee0d829482013-10-11 15:24:55 -0700425 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800426 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700427 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800428 }
buzbee0d829482013-10-11 15:24:55 -0700429 cur_block->successor_block_list_type =
430 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
431 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700432 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800433
434 for (i = 0; i < size; i++) {
435 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
436 /* create */ true, /* immed_pred_block_p */ &cur_block);
437 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700438 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000439 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700440 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800441 successor_block_info->key =
442 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
443 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700444 cur_block->successor_blocks->Insert(successor_block_info);
445 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800446 }
447
448 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700449 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
450 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700451 cur_block->fall_through = fallthrough_block->id;
452 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800453 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800454}
455
456/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700457BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
458 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700459 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700460 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800461 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
462 bool build_all_edges =
463 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800464
465 /* In try block */
466 if (in_try_block) {
467 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
468
buzbee0d829482013-10-11 15:24:55 -0700469 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800470 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
471 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700472 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800473 }
474
buzbee0d829482013-10-11 15:24:55 -0700475 cur_block->successor_block_list_type = kCatch;
476 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700477 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800478
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700479 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800480 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
481 false /* creat */, NULL /* immed_pred_block_p */);
482 catch_block->catch_entry = true;
483 if (kIsDebugBuild) {
484 catches_.insert(catch_block->start_offset);
485 }
486 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000487 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700488 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800489 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700490 cur_block->successor_blocks->Insert(successor_block_info);
491 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800492 }
buzbee17189ac2013-11-08 11:07:02 -0800493 } else if (build_all_edges) {
buzbee862a7602013-04-05 10:58:54 -0700494 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700495 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700496 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800497 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700498 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800499 }
500
buzbee17189ac2013-11-08 11:07:02 -0800501 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800502 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700503 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800504 // Force creation of new block following THROW via side-effect
505 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
506 /* immed_pred_block_p */ NULL);
507 }
508 if (!in_try_block) {
509 // Don't split a THROW that can't rethrow - we're done.
510 return cur_block;
511 }
512 }
513
buzbee17189ac2013-11-08 11:07:02 -0800514 if (!build_all_edges) {
515 /*
516 * Even though there is an exception edge here, control cannot return to this
517 * method. Thus, for the purposes of dataflow analysis and optimization, we can
518 * ignore the edge. Doing this reduces compile time, and increases the scope
519 * of the basic-block level optimization pass.
520 */
521 return cur_block;
522 }
523
buzbee311ca162013-02-28 15:56:43 -0800524 /*
525 * Split the potentially-throwing instruction into two parts.
526 * The first half will be a pseudo-op that captures the exception
527 * edges and terminates the basic block. It always falls through.
528 * Then, create a new basic block that begins with the throwing instruction
529 * (minus exceptions). Note: this new basic block must NOT be entered into
530 * the block_map. If the potentially-throwing instruction is the target of a
531 * future branch, we need to find the check psuedo half. The new
532 * basic block containing the work portion of the instruction should
533 * only be entered via fallthrough from the block containing the
534 * pseudo exception edge MIR. Note also that this new block is
535 * not automatically terminated after the work portion, and may
536 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700537 *
538 * Note also that the dex_pc_to_block_map_ entry for the potentially
539 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800540 */
buzbee862a7602013-04-05 10:58:54 -0700541 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
542 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800543 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700544 cur_block->fall_through = new_block->id;
545 new_block->predecessors->Insert(cur_block->id);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000546 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800547 *new_insn = *insn;
548 insn->dalvikInsn.opcode =
549 static_cast<Instruction::Code>(kMirOpCheck);
550 // Associate the two halves
551 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700552 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800553 return new_block;
554}
555
556/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
557void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700558 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700559 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800560 current_code_item_ = code_item;
561 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
562 current_method_ = m_units_.size();
563 current_offset_ = 0;
564 // TODO: will need to snapshot stack image and use that as the mir context identification.
565 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000566 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
567 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800568 const uint16_t* code_ptr = current_code_item_->insns_;
569 const uint16_t* code_end =
570 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
571
572 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700573 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700574 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700575 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 -0700576
buzbee311ca162013-02-28 15:56:43 -0800577 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700578 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
579 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800580
581 // If this is the first method, set up default entry and exit blocks.
582 if (current_method_ == 0) {
583 DCHECK(entry_block_ == NULL);
584 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700585 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700586 // Use id 0 to represent a null block.
587 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
588 DCHECK_EQ(null_block->id, NullBasicBlockId);
589 null_block->hidden = true;
590 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700591 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700592 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700593 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700594 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800595 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
596 cu_->dex_file = &dex_file;
597 cu_->class_def_idx = class_def_idx;
598 cu_->method_idx = method_idx;
599 cu_->access_flags = access_flags;
600 cu_->invoke_type = invoke_type;
601 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
602 cu_->num_ins = current_code_item_->ins_size_;
603 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
604 cu_->num_outs = current_code_item_->outs_size_;
605 cu_->num_dalvik_registers = current_code_item_->registers_size_;
606 cu_->insns = current_code_item_->insns_;
607 cu_->code_item = current_code_item_;
608 } else {
609 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
610 /*
611 * Will need to manage storage for ins & outs, push prevous state and update
612 * insert point.
613 */
614 }
615
616 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700617 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700618 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800619 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700620 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700621 // TODO: for inlining support, insert at the insert point rather than entry block.
622 entry_block_->fall_through = cur_block->id;
623 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800624
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000625 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800626 ProcessTryCatchBlocks();
627
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000628 uint64_t merged_df_flags = 0u;
629
buzbee311ca162013-02-28 15:56:43 -0800630 /* Parse all instructions and put them into containing basic blocks */
631 while (code_ptr < code_end) {
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000632 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800633 insn->offset = current_offset_;
634 insn->m_unit_index = current_method_;
635 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800636 Instruction::Code opcode = insn->dalvikInsn.opcode;
637 if (opcode_count_ != NULL) {
638 opcode_count_[static_cast<int>(opcode)]++;
639 }
640
buzbee311ca162013-02-28 15:56:43 -0800641 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800642 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800643
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700644 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000645 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800646
647 if (df_flags & DF_HAS_DEFS) {
648 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
649 }
650
buzbee1da1e2f2013-11-15 13:37:01 -0800651 if (df_flags & DF_LVN) {
652 cur_block->use_lvn = true; // Run local value numbering on this basic block.
653 }
654
buzbee27247762013-07-28 12:03:58 -0700655 // Check for inline data block signatures
656 if (opcode == Instruction::NOP) {
657 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
658 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
659 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
660 uint16_t following_raw_instruction = code_ptr[1];
661 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
662 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
663 (following_raw_instruction == Instruction::kArrayDataSignature)) {
664 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
665 }
666 }
667 if (width == 1) {
668 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700669 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700670 } else {
buzbee0d829482013-10-11 15:24:55 -0700671 DCHECK(cur_block->fall_through == NullBasicBlockId);
672 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700673 // Unreachable instruction, mark for no continuation.
674 flags &= ~Instruction::kContinue;
675 }
676 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700677 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700678 }
679
buzbeeb48819d2013-09-14 16:15:25 -0700680 // Associate the starting dex_pc for this opcode with its containing basic block.
681 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
682
buzbee27247762013-07-28 12:03:58 -0700683 code_ptr += width;
684
buzbee311ca162013-02-28 15:56:43 -0800685 if (flags & Instruction::kBranch) {
686 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
687 width, flags, code_ptr, code_end);
688 } else if (flags & Instruction::kReturn) {
689 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700690 cur_block->fall_through = exit_block_->id;
691 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800692 /*
693 * Terminate the current block if there are instructions
694 * afterwards.
695 */
696 if (code_ptr < code_end) {
697 /*
698 * Create a fallthrough block for real instructions
699 * (incl. NOP).
700 */
buzbee27247762013-07-28 12:03:58 -0700701 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
702 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800703 }
704 } else if (flags & Instruction::kThrow) {
705 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
706 code_ptr, code_end);
707 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800708 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800709 }
buzbeeb1f1d642014-02-27 12:55:32 -0800710 if (verify_flags & Instruction::kVerifyVarArgRange) {
711 /*
712 * The Quick backend's runtime model includes a gap between a method's
713 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
714 * which spans the gap is somewhat complicated, and should not happen
715 * in normal usage of dx. Punt to the interpreter.
716 */
717 int first_reg_in_range = insn->dalvikInsn.vC;
718 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
719 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
720 punt_to_interpreter_ = true;
721 }
722 }
buzbee311ca162013-02-28 15:56:43 -0800723 current_offset_ += width;
724 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
725 false, /* immed_pred_block_p */ NULL);
726 if (next_block) {
727 /*
728 * The next instruction could be the target of a previously parsed
729 * forward branch so a block is already created. If the current
730 * instruction is not an unconditional branch, connect them through
731 * the fall-through link.
732 */
buzbee0d829482013-10-11 15:24:55 -0700733 DCHECK(cur_block->fall_through == NullBasicBlockId ||
734 GetBasicBlock(cur_block->fall_through) == next_block ||
735 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800736
buzbee0d829482013-10-11 15:24:55 -0700737 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
738 cur_block->fall_through = next_block->id;
739 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800740 }
741 cur_block = next_block;
742 }
743 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000744 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000745
buzbee311ca162013-02-28 15:56:43 -0800746 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
747 DumpCFG("/sdcard/1_post_parse_cfg/", true);
748 }
749
750 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700751 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800752 }
753}
754
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700755void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800756 DCHECK(opcode_count_ != NULL);
757 LOG(INFO) << "Opcode Count";
758 for (int i = 0; i < kNumPackedOpcodes; i++) {
759 if (opcode_count_[i] != 0) {
760 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
761 << " " << opcode_count_[i];
762 }
763 }
764}
765
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700766uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
767 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
768 return oat_data_flow_attributes_[opcode];
769}
770
771uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
772 DCHECK(mir != nullptr);
773 Instruction::Code opcode = mir->dalvikInsn.opcode;
774 return GetDataFlowAttributes(opcode);
775}
776
buzbee311ca162013-02-28 15:56:43 -0800777// TODO: use a configurable base prefix, and adjust callers to supply pass name.
778/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800779void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800780 FILE* file;
781 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
782 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800783 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
784 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
785 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800786 file = fopen(fname.c_str(), "w");
787 if (file == NULL) {
788 return;
789 }
790 fprintf(file, "digraph G {\n");
791
792 fprintf(file, " rankdir=TB\n");
793
794 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
795 int idx;
796
797 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700798 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800799 BasicBlock *bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700800 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800801 if (bb->block_type == kDead) continue;
802 if (bb->block_type == kEntryBlock) {
803 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
804 } else if (bb->block_type == kExitBlock) {
805 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
806 } else if (bb->block_type == kDalvikByteCode) {
807 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
808 bb->start_offset, bb->id);
809 const MIR *mir;
810 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
811 bb->first_mir_insn ? " | " : " ");
812 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
813 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400814 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
815 if (opcode == kMirOpConstVector) {
816 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
817 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
818 mir->dalvikInsn.vA,
819 mir->dalvikInsn.vB,
820 mir->dalvikInsn.arg[0],
821 mir->dalvikInsn.arg[1],
822 mir->dalvikInsn.arg[2],
823 mir->dalvikInsn.arg[3],
824 mir->next ? " | " : " ");
825 } else {
826 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
827 extended_mir_op_names_[opcode - kMirOpFirst],
828 mir->dalvikInsn.vA,
829 mir->dalvikInsn.vB,
830 mir->dalvikInsn.vC,
831 mir->next ? " | " : " ");
832 }
833 } else {
834 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
835 mir->ssa_rep ? GetDalvikDisassembly(mir) :
836 (opcode < kMirOpFirst) ?
837 Instruction::Name(mir->dalvikInsn.opcode) :
838 extended_mir_op_names_[opcode - kMirOpFirst],
839 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
840 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
841 mir->next ? " | " : " ");
842 }
buzbee311ca162013-02-28 15:56:43 -0800843 }
844 fprintf(file, " }\"];\n\n");
845 } else if (bb->block_type == kExceptionHandling) {
846 char block_name[BLOCK_NAME_LEN];
847
848 GetBlockName(bb, block_name);
849 fprintf(file, " %s [shape=invhouse];\n", block_name);
850 }
851
852 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
853
buzbee0d829482013-10-11 15:24:55 -0700854 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800855 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700856 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800857 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
858 block_name1, block_name2);
859 }
buzbee0d829482013-10-11 15:24:55 -0700860 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800861 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700862 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800863 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
864 }
865
buzbee0d829482013-10-11 15:24:55 -0700866 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800867 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
868 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700869 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
870 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700871 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800872
873 int succ_id = 0;
874 while (true) {
875 if (successor_block_info == NULL) break;
876
buzbee0d829482013-10-11 15:24:55 -0700877 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700878 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800879
880 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
881 succ_id++,
882 successor_block_info->key,
883 dest_block->start_offset,
884 (next_successor_block_info != NULL) ? " | " : " ");
885
886 successor_block_info = next_successor_block_info;
887 }
888 fprintf(file, " }\"];\n\n");
889
890 GetBlockName(bb, block_name1);
891 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
892 block_name1, bb->start_offset, bb->id);
893
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700894 // Link the successor pseudo-block with all of its potential targets.
895 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800896
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700897 succ_id = 0;
898 while (true) {
899 SuccessorBlockInfo *successor_block_info = iter.Next();
900 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800901
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700902 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800903
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700904 GetBlockName(dest_block, block_name2);
905 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
906 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800907 }
908 }
909 fprintf(file, "\n");
910
911 if (cu_->verbose) {
912 /* Display the dominator tree */
913 GetBlockName(bb, block_name1);
914 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
915 block_name1, block_name1);
916 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700917 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800918 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
919 }
920 }
921 }
922 fprintf(file, "}\n");
923 fclose(file);
924}
925
buzbee1fd33462013-03-25 13:40:45 -0700926/* Insert an MIR instruction to the end of a basic block */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700927void BasicBlock::AppendMIR(MIR* mir) {
928 if (first_mir_insn == nullptr) {
929 DCHECK(last_mir_insn == nullptr);
930 last_mir_insn = first_mir_insn = mir;
931 mir->next = nullptr;
buzbee1fd33462013-03-25 13:40:45 -0700932 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700933 last_mir_insn->next = mir;
934 mir->next = nullptr;
935 last_mir_insn = mir;
buzbee1fd33462013-03-25 13:40:45 -0700936 }
937}
938
939/* Insert an MIR instruction to the head of a basic block */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700940void BasicBlock::PrependMIR(MIR* mir) {
941 if (first_mir_insn == nullptr) {
942 DCHECK(last_mir_insn == nullptr);
943 last_mir_insn = first_mir_insn = mir;
944 mir->next = nullptr;
buzbee1fd33462013-03-25 13:40:45 -0700945 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700946 mir->next = first_mir_insn;
947 first_mir_insn = mir;
buzbee1fd33462013-03-25 13:40:45 -0700948 }
949}
950
951/* Insert a MIR instruction after the specified MIR */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700952void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700953 new_mir->next = current_mir->next;
954 current_mir->next = new_mir;
955
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700956 if (last_mir_insn == current_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700957 /* Is the last MIR in the block */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700958 last_mir_insn = new_mir;
buzbee1fd33462013-03-25 13:40:45 -0700959 }
960}
961
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700962MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -0800963 MIR* next_mir = nullptr;
964
965 if (current != nullptr) {
966 next_mir = current->next;
967 }
968
969 if (next_mir == nullptr) {
970 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700971 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
972 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -0800973 }
974 }
975
976 return next_mir;
977}
978
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700979char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -0700980 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -0700981 std::string str;
982 int flags = 0;
983 int opcode = insn.opcode;
984 char* ret;
985 bool nop = false;
986 SSARepresentation* ssa_rep = mir->ssa_rep;
987 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
988 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
989 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
990
991 // Handle special cases.
992 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
993 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
994 str.append(": ");
995 // Recover the original Dex instruction
996 insn = mir->meta.throw_insn->dalvikInsn;
997 ssa_rep = mir->meta.throw_insn->ssa_rep;
998 defs = ssa_rep->num_defs;
999 uses = ssa_rep->num_uses;
1000 opcode = insn.opcode;
1001 } else if (opcode == kMirOpNop) {
1002 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001003 // Recover original opcode.
1004 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1005 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001006 nop = true;
1007 }
1008
1009 if (opcode >= kMirOpFirst) {
1010 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1011 } else {
1012 dalvik_format = Instruction::FormatOf(insn.opcode);
1013 flags = Instruction::FlagsOf(insn.opcode);
1014 str.append(Instruction::Name(insn.opcode));
1015 }
1016
1017 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001018 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001019 str.append(StringPrintf(" %s = (%s",
1020 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1021 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001022 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001023 int i;
1024 for (i = 1; i < uses; i++) {
1025 str.append(StringPrintf(", %s:%d",
1026 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1027 incoming[i]));
1028 }
1029 str.append(")");
1030 } else if ((flags & Instruction::kBranch) != 0) {
1031 // For branches, decode the instructions to print out the branch targets.
1032 int offset = 0;
1033 switch (dalvik_format) {
1034 case Instruction::k21t:
1035 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1036 offset = insn.vB;
1037 break;
1038 case Instruction::k22t:
1039 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1040 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1041 offset = insn.vC;
1042 break;
1043 case Instruction::k10t:
1044 case Instruction::k20t:
1045 case Instruction::k30t:
1046 offset = insn.vA;
1047 break;
1048 default:
1049 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1050 }
1051 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1052 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1053 } else {
1054 // For invokes-style formats, treat wide regs as a pair of singles
1055 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1056 (dalvik_format == Instruction::k3rc));
1057 if (defs != 0) {
1058 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1059 if (uses != 0) {
1060 str.append(", ");
1061 }
1062 }
1063 for (int i = 0; i < uses; i++) {
1064 str.append(
1065 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1066 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1067 // For the listing, skip the high sreg.
1068 i++;
1069 }
1070 if (i != (uses -1)) {
1071 str.append(",");
1072 }
1073 }
1074 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001075 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -07001076 case Instruction::k21s:
1077 case Instruction::k31i:
1078 case Instruction::k21h:
1079 str.append(StringPrintf(", #%d", insn.vB));
1080 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001081 case Instruction::k51l: // Add one wide immediate
Ian Rogers23b03b52014-01-24 11:10:03 -08001082 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001083 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001084 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001085 case Instruction::k31c:
1086 str.append(StringPrintf(", index #%d", insn.vB));
1087 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001088 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001089 str.append(StringPrintf(", index #%d", insn.vC));
1090 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001091 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001092 case Instruction::k22b:
1093 str.append(StringPrintf(", #%d", insn.vC));
1094 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001095 default: {
1096 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001097 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001098 }
buzbee1fd33462013-03-25 13:40:45 -07001099 }
1100 if (nop) {
1101 str.append("]--optimized away");
1102 }
1103 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001104 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001105 strncpy(ret, str.c_str(), length);
1106 return ret;
1107}
1108
1109/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001110void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001111 static const struct { const char before; const char after; } match[] = {
1112 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1113 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1114 };
buzbee1fd33462013-03-25 13:40:45 -07001115 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1116 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1117 }
1118}
1119
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001120std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001121 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1122 // the arena. We should be smarter and just place straight into the arena, or compute the
1123 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001124 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1125}
1126
1127// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001128std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001129 if (reg_location_ == NULL) {
1130 // Pre-SSA - just use the standard name
1131 return GetSSAName(ssa_reg);
1132 }
1133 if (IsConst(reg_location_[ssa_reg])) {
1134 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001135 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001136 ConstantValueWide(reg_location_[ssa_reg]));
1137 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001138 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001139 ConstantValue(reg_location_[ssa_reg]));
1140 }
1141 } else {
1142 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1143 }
1144}
1145
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001146void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001147 switch (bb->block_type) {
1148 case kEntryBlock:
1149 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1150 break;
1151 case kExitBlock:
1152 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1153 break;
1154 case kDalvikByteCode:
1155 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1156 break;
1157 case kExceptionHandling:
1158 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1159 bb->id);
1160 break;
1161 default:
1162 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1163 break;
1164 }
1165}
1166
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001167const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001168 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001169 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1170 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1171}
1172
1173/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001174void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001175 BasicBlock* bb;
1176 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001177 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001178 "Entry Block",
1179 "Code Block",
1180 "Exit Block",
1181 "Exception Handling",
1182 "Catch Block"
1183 };
1184
1185 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1186 LOG(INFO) << cu_->insns << " insns";
1187 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001188 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001189
1190 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001191 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001192 if (bb == NULL) break;
1193 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1194 bb->id,
1195 block_type_names[bb->block_type],
1196 bb->start_offset,
1197 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1198 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001199 if (bb->taken != NullBasicBlockId) {
1200 LOG(INFO) << " Taken branch: block " << bb->taken
1201 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001202 }
buzbee0d829482013-10-11 15:24:55 -07001203 if (bb->fall_through != NullBasicBlockId) {
1204 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1205 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001206 }
1207 }
1208}
1209
1210/*
1211 * Build an array of location records for the incoming arguments.
1212 * Note: one location record per word of arguments, with dummy
1213 * high-word loc for wide arguments. Also pull up any following
1214 * MOVE_RESULT and incorporate it into the invoke.
1215 */
1216CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001217 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001218 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001219 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001220 MIR* move_result_mir = FindMoveResult(bb, mir);
1221 if (move_result_mir == NULL) {
1222 info->result.location = kLocInvalid;
1223 } else {
1224 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001225 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1226 }
1227 info->num_arg_words = mir->ssa_rep->num_uses;
1228 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001229 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001230 for (int i = 0; i < info->num_arg_words; i++) {
1231 info->args[i] = GetRawSrc(mir, i);
1232 }
1233 info->opt_flags = mir->optimization_flags;
1234 info->type = type;
1235 info->is_range = is_range;
1236 info->index = mir->dalvikInsn.vB;
1237 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001238 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001239 return info;
1240}
1241
buzbee862a7602013-04-05 10:58:54 -07001242// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001243BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001244 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001245 kArenaAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001246 bb->block_type = block_type;
1247 bb->id = block_id;
1248 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001249 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001250 (block_type == kExitBlock) ? 2048 : 2,
1251 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001252 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001253 block_id_map_.Put(block_id, block_id);
1254 return bb;
1255}
buzbee1fd33462013-03-25 13:40:45 -07001256
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001257void MIRGraph::InitializeConstantPropagation() {
1258 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001259 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001260}
1261
1262void MIRGraph::InitializeMethodUses() {
1263 // The gate starts by initializing the use counts
1264 int num_ssa_regs = GetNumSSARegs();
1265 use_counts_.Resize(num_ssa_regs + 32);
1266 raw_use_counts_.Resize(num_ssa_regs + 32);
1267 // Initialize list
1268 for (int i = 0; i < num_ssa_regs; i++) {
1269 use_counts_.Insert(0);
1270 raw_use_counts_.Insert(0);
1271 }
1272}
1273
1274void MIRGraph::InitializeSSATransformation() {
1275 /* Compute the DFS order */
1276 ComputeDFSOrders();
1277
1278 /* Compute the dominator info */
1279 ComputeDominators();
1280
1281 /* Allocate data structures in preparation for SSA conversion */
1282 CompilerInitializeSSAConversion();
1283
1284 /* Find out the "Dalvik reg def x block" relation */
1285 ComputeDefBlockMatrix();
1286
1287 /* Insert phi nodes to dominance frontiers for all variables */
1288 InsertPhiNodes();
1289
1290 /* Rename register names by local defs and phi nodes */
1291 ClearAllVisitedFlags();
1292 DoDFSPreOrderSSARename(GetEntryBlock());
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001293}
1294
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001295ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1296 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1297 visited_taken_(false), have_successors_(false) {
1298 // Check if we actually do have successors.
1299 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1300 have_successors_ = true;
1301 successor_iter_.Reset(basic_block_->successor_blocks);
1302 }
1303}
1304
1305BasicBlock* ChildBlockIterator::Next() {
1306 // We check if we have a basic block. If we don't we cannot get next child.
1307 if (basic_block_ == nullptr) {
1308 return nullptr;
1309 }
1310
1311 // If we haven't visited fallthrough, return that.
1312 if (visited_fallthrough_ == false) {
1313 visited_fallthrough_ = true;
1314
1315 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1316 if (result != nullptr) {
1317 return result;
1318 }
1319 }
1320
1321 // If we haven't visited taken, return that.
1322 if (visited_taken_ == false) {
1323 visited_taken_ = true;
1324
1325 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1326 if (result != nullptr) {
1327 return result;
1328 }
1329 }
1330
1331 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1332 if (have_successors_ == true) {
1333 // Get information about next successor block.
1334 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1335
1336 // If we don't have anymore successors, return nullptr.
1337 if (successor_block_info != nullptr) {
1338 return mir_graph_->GetBasicBlock(successor_block_info->block);
1339 }
1340 }
1341
1342 // We do not have anything.
1343 return nullptr;
1344}
1345
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001346} // namespace art