blob: 9dbb3417a3b4d6934889a0e89dcde9412818c42f [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
Ian Rogers6282dc12013-04-18 15:54:02 -070017#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080018#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080019#include "dex_file-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070020#include "leb128.h"
21#include "mir_graph.h"
buzbee311ca162013-02-28 15:56:43 -080022
Vladimir Marko5816ed42013-11-27 17:04:20 +000023#include "dex/quick/dex_file_to_method_inliner_map.h"
24#include "dex/quick/dex_file_method_inliner.h"
25
buzbee311ca162013-02-28 15:56:43 -080026namespace art {
27
28#define MAX_PATTERN_LEN 5
29
buzbee1fd33462013-03-25 13:40:45 -070030const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
31 "Phi",
32 "Copy",
33 "FusedCmplFloat",
34 "FusedCmpgFloat",
35 "FusedCmplDouble",
36 "FusedCmpgDouble",
37 "FusedCmpLong",
38 "Nop",
39 "OpNullCheck",
40 "OpRangeCheck",
41 "OpDivZeroCheck",
42 "Check1",
43 "Check2",
44 "Select",
45};
46
buzbee862a7602013-04-05 10:58:54 -070047MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070048 : reg_location_(NULL),
buzbee862a7602013-04-05 10:58:54 -070049 compiler_temps_(arena, 6, kGrowableArrayMisc),
buzbee1fd33462013-03-25 13:40:45 -070050 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080051 ssa_base_vregs_(NULL),
52 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080053 vreg_to_ssa_map_(NULL),
54 ssa_last_defs_(NULL),
55 is_constant_v_(NULL),
56 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070057 use_counts_(arena, 256, kGrowableArrayMisc),
58 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080059 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070060 dfs_order_(NULL),
61 dfs_post_order_(NULL),
62 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080063 i_dom_list_(NULL),
64 def_block_matrix_(NULL),
65 temp_block_v_(NULL),
66 temp_dalvik_register_v_(NULL),
67 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070068 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080069 try_block_addr_(NULL),
70 entry_block_(NULL),
71 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080072 num_blocks_(0),
73 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070074 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080075 current_method_(kInvalidEntry),
76 current_offset_(kInvalidEntry),
77 def_count_(0),
78 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070079 num_ssa_regs_(0),
80 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -070081 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
82 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070083 arena_(arena),
84 backward_branches_(0),
85 forward_branches_(0) {
buzbee862a7602013-04-05 10:58:54 -070086 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -080087}
88
Ian Rogers6282dc12013-04-18 15:54:02 -070089MIRGraph::~MIRGraph() {
90 STLDeleteElements(&m_units_);
91}
92
buzbee311ca162013-02-28 15:56:43 -080093/*
94 * Parse an instruction, return the length of the instruction
95 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070096int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -080097 const Instruction* instruction = Instruction::At(code_ptr);
98 *decoded_instruction = DecodedInstruction(instruction);
99
100 return instruction->SizeInCodeUnits();
101}
102
103
104/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700105BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700106 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700107 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800108 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700109 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800110 while (insn) {
111 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700112 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800113 insn = insn->next;
114 }
115 if (insn == NULL) {
116 LOG(FATAL) << "Break split failed";
117 }
buzbee862a7602013-04-05 10:58:54 -0700118 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
119 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800120
121 bottom_block->start_offset = code_offset;
122 bottom_block->first_mir_insn = insn;
123 bottom_block->last_mir_insn = orig_block->last_mir_insn;
124
125 /* If this block was terminated by a return, the flag needs to go with the bottom block */
126 bottom_block->terminated_by_return = orig_block->terminated_by_return;
127 orig_block->terminated_by_return = false;
128
buzbee311ca162013-02-28 15:56:43 -0800129 /* Handle the taken path */
130 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700131 if (bottom_block->taken != NullBasicBlockId) {
132 orig_block->taken = NullBasicBlockId;
133 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
134 bb_taken->predecessors->Delete(orig_block->id);
135 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800136 }
137
138 /* Handle the fallthrough path */
139 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700140 orig_block->fall_through = bottom_block->id;
141 bottom_block->predecessors->Insert(orig_block->id);
142 if (bottom_block->fall_through != NullBasicBlockId) {
143 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
144 bb_fall_through->predecessors->Delete(orig_block->id);
145 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800146 }
147
148 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700149 if (orig_block->successor_block_list_type != kNotUsed) {
150 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
151 bottom_block->successor_blocks = orig_block->successor_blocks;
152 orig_block->successor_block_list_type = kNotUsed;
153 orig_block->successor_blocks = NULL;
154 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800155 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700156 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800157 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700158 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
159 bb->predecessors->Delete(orig_block->id);
160 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800161 }
162 }
163
buzbee0d829482013-10-11 15:24:55 -0700164 orig_block->last_mir_insn = prev;
165 prev->next = NULL;
buzbee311ca162013-02-28 15:56:43 -0800166
buzbee311ca162013-02-28 15:56:43 -0800167 /*
168 * Update the immediate predecessor block pointer so that outgoing edges
169 * can be applied to the proper block.
170 */
171 if (immed_pred_block_p) {
172 DCHECK_EQ(*immed_pred_block_p, orig_block);
173 *immed_pred_block_p = bottom_block;
174 }
buzbeeb48819d2013-09-14 16:15:25 -0700175
176 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000177 DCHECK(insn != nullptr);
178 DCHECK(insn != orig_block->first_mir_insn);
179 DCHECK(insn == bottom_block->first_mir_insn);
180 DCHECK_EQ(insn->offset, bottom_block->start_offset);
181 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
182 !IsPseudoMirOp(insn->dalvikInsn.opcode));
183 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
184 MIR* p = insn;
185 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
186 while (p != bottom_block->last_mir_insn) {
187 p = p->next;
188 DCHECK(p != nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700189 int opcode = p->dalvikInsn.opcode;
190 /*
191 * Some messiness here to ensure that we only enter real opcodes and only the
192 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000193 * CHECK and work portions. Since the 2nd half of a split operation is always
194 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700195 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000196 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
197 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700198 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
199 }
buzbeeb48819d2013-09-14 16:15:25 -0700200 }
201
buzbee311ca162013-02-28 15:56:43 -0800202 return bottom_block;
203}
204
205/*
206 * Given a code offset, find out the block that starts with it. If the offset
207 * is in the middle of an existing block, split it into two. If immed_pred_block_p
208 * is not non-null and is the block being split, update *immed_pred_block_p to
209 * point to the bottom block so that outgoing edges can be set up properly
210 * (by the caller)
211 * Utilizes a map for fast lookup of the typical cases.
212 */
buzbee0d829482013-10-11 15:24:55 -0700213BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700214 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700215 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800216 return NULL;
217 }
buzbeeb48819d2013-09-14 16:15:25 -0700218
219 int block_id = dex_pc_to_block_map_.Get(code_offset);
220 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
221
222 if ((bb != NULL) && (bb->start_offset == code_offset)) {
223 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700224 return bb;
225 }
buzbee311ca162013-02-28 15:56:43 -0800226
buzbeeb48819d2013-09-14 16:15:25 -0700227 // No direct hit.
228 if (!create) {
229 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800230 }
231
buzbeeb48819d2013-09-14 16:15:25 -0700232 if (bb != NULL) {
233 // The target exists somewhere in an existing block.
234 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
235 }
236
237 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700238 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
239 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800240 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700241 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800242 return bb;
243}
244
buzbeeb48819d2013-09-14 16:15:25 -0700245
buzbee311ca162013-02-28 15:56:43 -0800246/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700247void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800248 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700249 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800250
251 if (tries_size == 0) {
252 return;
253 }
254
255 for (int i = 0; i < tries_size; i++) {
256 const DexFile::TryItem* pTry =
257 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700258 DexOffset start_offset = pTry->start_addr_;
259 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800260 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700261 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800262 }
263 }
264
265 // Iterate over each of the handlers to enqueue the empty Catch blocks
266 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
267 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
268 for (uint32_t idx = 0; idx < handlers_size; idx++) {
269 CatchHandlerIterator iterator(handlers_ptr);
270 for (; iterator.HasNext(); iterator.Next()) {
271 uint32_t address = iterator.GetHandlerAddress();
272 FindBlock(address, false /* split */, true /*create*/,
273 /* immed_pred_block_p */ NULL);
274 }
275 handlers_ptr = iterator.EndDataPointer();
276 }
277}
278
279/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700280BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
281 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700282 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700283 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800284 switch (insn->dalvikInsn.opcode) {
285 case Instruction::GOTO:
286 case Instruction::GOTO_16:
287 case Instruction::GOTO_32:
288 target += insn->dalvikInsn.vA;
289 break;
290 case Instruction::IF_EQ:
291 case Instruction::IF_NE:
292 case Instruction::IF_LT:
293 case Instruction::IF_GE:
294 case Instruction::IF_GT:
295 case Instruction::IF_LE:
296 cur_block->conditional_branch = true;
297 target += insn->dalvikInsn.vC;
298 break;
299 case Instruction::IF_EQZ:
300 case Instruction::IF_NEZ:
301 case Instruction::IF_LTZ:
302 case Instruction::IF_GEZ:
303 case Instruction::IF_GTZ:
304 case Instruction::IF_LEZ:
305 cur_block->conditional_branch = true;
306 target += insn->dalvikInsn.vB;
307 break;
308 default:
309 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
310 }
buzbeeb48819d2013-09-14 16:15:25 -0700311 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800312 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
313 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700314 cur_block->taken = taken_block->id;
315 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800316
317 /* Always terminate the current block for conditional branches */
318 if (flags & Instruction::kContinue) {
319 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
320 /*
321 * If the method is processed
322 * in sequential order from the
323 * beginning, we don't need to
324 * specify split for continue
325 * blocks. However, this
326 * routine can be called by
327 * compileLoop, which starts
328 * parsing the method from an
329 * arbitrary address in the
330 * method body.
331 */
332 true,
333 /* create */
334 true,
335 /* immed_pred_block_p */
336 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700337 cur_block->fall_through = fallthrough_block->id;
338 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800339 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700340 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800341 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800342 }
343 return cur_block;
344}
345
346/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800347BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
348 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800349 const uint16_t* switch_data =
350 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
351 int size;
352 const int* keyTable;
353 const int* target_table;
354 int i;
355 int first_key;
356
357 /*
358 * Packed switch data format:
359 * ushort ident = 0x0100 magic value
360 * ushort size number of entries in the table
361 * int first_key first (and lowest) switch case value
362 * int targets[size] branch targets, relative to switch opcode
363 *
364 * Total size is (4+size*2) 16-bit code units.
365 */
366 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
367 DCHECK_EQ(static_cast<int>(switch_data[0]),
368 static_cast<int>(Instruction::kPackedSwitchSignature));
369 size = switch_data[1];
370 first_key = switch_data[2] | (switch_data[3] << 16);
371 target_table = reinterpret_cast<const int*>(&switch_data[4]);
372 keyTable = NULL; // Make the compiler happy
373 /*
374 * Sparse switch data format:
375 * ushort ident = 0x0200 magic value
376 * ushort size number of entries in the table; > 0
377 * int keys[size] keys, sorted low-to-high; 32-bit aligned
378 * int targets[size] branch targets, relative to switch opcode
379 *
380 * Total size is (2+size*4) 16-bit code units.
381 */
382 } else {
383 DCHECK_EQ(static_cast<int>(switch_data[0]),
384 static_cast<int>(Instruction::kSparseSwitchSignature));
385 size = switch_data[1];
386 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
387 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
388 first_key = 0; // To make the compiler happy
389 }
390
buzbee0d829482013-10-11 15:24:55 -0700391 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800392 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700393 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800394 }
buzbee0d829482013-10-11 15:24:55 -0700395 cur_block->successor_block_list_type =
396 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
397 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700398 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800399
400 for (i = 0; i < size; i++) {
401 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
402 /* create */ true, /* immed_pred_block_p */ &cur_block);
403 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700404 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
405 ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700406 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800407 successor_block_info->key =
408 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
409 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700410 cur_block->successor_blocks->Insert(successor_block_info);
411 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800412 }
413
414 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700415 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
416 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700417 cur_block->fall_through = fallthrough_block->id;
418 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800419 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800420}
421
422/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700423BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
424 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700425 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700426 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800427 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
428 bool build_all_edges =
429 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800430
431 /* In try block */
432 if (in_try_block) {
433 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
434
buzbee0d829482013-10-11 15:24:55 -0700435 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800436 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
437 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700438 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800439 }
440
buzbee0d829482013-10-11 15:24:55 -0700441 cur_block->successor_block_list_type = kCatch;
442 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700443 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800444
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700445 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800446 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
447 false /* creat */, NULL /* immed_pred_block_p */);
448 catch_block->catch_entry = true;
449 if (kIsDebugBuild) {
450 catches_.insert(catch_block->start_offset);
451 }
452 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700453 (arena_->Alloc(sizeof(SuccessorBlockInfo), ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700454 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800455 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700456 cur_block->successor_blocks->Insert(successor_block_info);
457 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800458 }
buzbee17189ac2013-11-08 11:07:02 -0800459 } else if (build_all_edges) {
buzbee862a7602013-04-05 10:58:54 -0700460 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700461 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700462 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800463 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700464 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800465 }
466
buzbee17189ac2013-11-08 11:07:02 -0800467 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800468 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700469 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800470 // Force creation of new block following THROW via side-effect
471 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
472 /* immed_pred_block_p */ NULL);
473 }
474 if (!in_try_block) {
475 // Don't split a THROW that can't rethrow - we're done.
476 return cur_block;
477 }
478 }
479
buzbee17189ac2013-11-08 11:07:02 -0800480 if (!build_all_edges) {
481 /*
482 * Even though there is an exception edge here, control cannot return to this
483 * method. Thus, for the purposes of dataflow analysis and optimization, we can
484 * ignore the edge. Doing this reduces compile time, and increases the scope
485 * of the basic-block level optimization pass.
486 */
487 return cur_block;
488 }
489
buzbee311ca162013-02-28 15:56:43 -0800490 /*
491 * Split the potentially-throwing instruction into two parts.
492 * The first half will be a pseudo-op that captures the exception
493 * edges and terminates the basic block. It always falls through.
494 * Then, create a new basic block that begins with the throwing instruction
495 * (minus exceptions). Note: this new basic block must NOT be entered into
496 * the block_map. If the potentially-throwing instruction is the target of a
497 * future branch, we need to find the check psuedo half. The new
498 * basic block containing the work portion of the instruction should
499 * only be entered via fallthrough from the block containing the
500 * pseudo exception edge MIR. Note also that this new block is
501 * not automatically terminated after the work portion, and may
502 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700503 *
504 * Note also that the dex_pc_to_block_map_ entry for the potentially
505 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800506 */
buzbee862a7602013-04-05 10:58:54 -0700507 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
508 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800509 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700510 cur_block->fall_through = new_block->id;
511 new_block->predecessors->Insert(cur_block->id);
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700512 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800513 *new_insn = *insn;
514 insn->dalvikInsn.opcode =
515 static_cast<Instruction::Code>(kMirOpCheck);
516 // Associate the two halves
517 insn->meta.throw_insn = new_insn;
buzbee311ca162013-02-28 15:56:43 -0800518 AppendMIR(new_block, new_insn);
519 return new_block;
520}
521
522/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
523void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700524 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700525 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800526 current_code_item_ = code_item;
527 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
528 current_method_ = m_units_.size();
529 current_offset_ = 0;
530 // TODO: will need to snapshot stack image and use that as the mir context identification.
531 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000532 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
533 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800534 const uint16_t* code_ptr = current_code_item_->insns_;
535 const uint16_t* code_end =
536 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
537
538 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700539 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700540 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700541 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 -0700542
buzbee311ca162013-02-28 15:56:43 -0800543 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700544 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
545 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800546
547 // If this is the first method, set up default entry and exit blocks.
548 if (current_method_ == 0) {
549 DCHECK(entry_block_ == NULL);
550 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700551 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700552 // Use id 0 to represent a null block.
553 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
554 DCHECK_EQ(null_block->id, NullBasicBlockId);
555 null_block->hidden = true;
556 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700557 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700558 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700559 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700560 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800561 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
562 cu_->dex_file = &dex_file;
563 cu_->class_def_idx = class_def_idx;
564 cu_->method_idx = method_idx;
565 cu_->access_flags = access_flags;
566 cu_->invoke_type = invoke_type;
567 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
568 cu_->num_ins = current_code_item_->ins_size_;
569 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
570 cu_->num_outs = current_code_item_->outs_size_;
571 cu_->num_dalvik_registers = current_code_item_->registers_size_;
572 cu_->insns = current_code_item_->insns_;
573 cu_->code_item = current_code_item_;
574 } else {
575 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
576 /*
577 * Will need to manage storage for ins & outs, push prevous state and update
578 * insert point.
579 */
580 }
581
582 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700583 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700584 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800585 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700586 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700587 // TODO: for inlining support, insert at the insert point rather than entry block.
588 entry_block_->fall_through = cur_block->id;
589 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800590
591 /* Identify code range in try blocks and set up the empty catch blocks */
592 ProcessTryCatchBlocks();
593
buzbee311ca162013-02-28 15:56:43 -0800594 /* Parse all instructions and put them into containing basic blocks */
595 while (code_ptr < code_end) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700596 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800597 insn->offset = current_offset_;
598 insn->m_unit_index = current_method_;
599 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
600 insn->width = width;
601 Instruction::Code opcode = insn->dalvikInsn.opcode;
602 if (opcode_count_ != NULL) {
603 opcode_count_[static_cast<int>(opcode)]++;
604 }
605
buzbee311ca162013-02-28 15:56:43 -0800606 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
607
buzbee1da1e2f2013-11-15 13:37:01 -0800608 uint64_t df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800609
610 if (df_flags & DF_HAS_DEFS) {
611 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
612 }
613
buzbee1da1e2f2013-11-15 13:37:01 -0800614 if (df_flags & DF_LVN) {
615 cur_block->use_lvn = true; // Run local value numbering on this basic block.
616 }
617
buzbee27247762013-07-28 12:03:58 -0700618 // Check for inline data block signatures
619 if (opcode == Instruction::NOP) {
620 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
621 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
622 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
623 uint16_t following_raw_instruction = code_ptr[1];
624 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
625 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
626 (following_raw_instruction == Instruction::kArrayDataSignature)) {
627 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
628 }
629 }
630 if (width == 1) {
631 // It is a simple nop - treat normally.
632 AppendMIR(cur_block, insn);
633 } else {
buzbee0d829482013-10-11 15:24:55 -0700634 DCHECK(cur_block->fall_through == NullBasicBlockId);
635 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700636 // Unreachable instruction, mark for no continuation.
637 flags &= ~Instruction::kContinue;
638 }
639 } else {
640 AppendMIR(cur_block, insn);
641 }
642
buzbeeb48819d2013-09-14 16:15:25 -0700643 // Associate the starting dex_pc for this opcode with its containing basic block.
644 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
645
buzbee27247762013-07-28 12:03:58 -0700646 code_ptr += width;
647
buzbee311ca162013-02-28 15:56:43 -0800648 if (flags & Instruction::kBranch) {
649 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
650 width, flags, code_ptr, code_end);
651 } else if (flags & Instruction::kReturn) {
652 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700653 cur_block->fall_through = exit_block_->id;
654 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800655 /*
656 * Terminate the current block if there are instructions
657 * afterwards.
658 */
659 if (code_ptr < code_end) {
660 /*
661 * Create a fallthrough block for real instructions
662 * (incl. NOP).
663 */
buzbee27247762013-07-28 12:03:58 -0700664 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
665 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800666 }
667 } else if (flags & Instruction::kThrow) {
668 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
669 code_ptr, code_end);
670 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800671 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800672 }
673 current_offset_ += width;
674 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
675 false, /* immed_pred_block_p */ NULL);
676 if (next_block) {
677 /*
678 * The next instruction could be the target of a previously parsed
679 * forward branch so a block is already created. If the current
680 * instruction is not an unconditional branch, connect them through
681 * the fall-through link.
682 */
buzbee0d829482013-10-11 15:24:55 -0700683 DCHECK(cur_block->fall_through == NullBasicBlockId ||
684 GetBasicBlock(cur_block->fall_through) == next_block ||
685 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800686
buzbee0d829482013-10-11 15:24:55 -0700687 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
688 cur_block->fall_through = next_block->id;
689 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800690 }
691 cur_block = next_block;
692 }
693 }
Vladimir Marko5816ed42013-11-27 17:04:20 +0000694
buzbee311ca162013-02-28 15:56:43 -0800695 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
696 DumpCFG("/sdcard/1_post_parse_cfg/", true);
697 }
698
699 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700700 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800701 }
702}
703
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700704void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800705 DCHECK(opcode_count_ != NULL);
706 LOG(INFO) << "Opcode Count";
707 for (int i = 0; i < kNumPackedOpcodes; i++) {
708 if (opcode_count_[i] != 0) {
709 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
710 << " " << opcode_count_[i];
711 }
712 }
713}
714
715// TODO: use a configurable base prefix, and adjust callers to supply pass name.
716/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800717void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800718 FILE* file;
719 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
720 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800721 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
722 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
723 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800724 file = fopen(fname.c_str(), "w");
725 if (file == NULL) {
726 return;
727 }
728 fprintf(file, "digraph G {\n");
729
730 fprintf(file, " rankdir=TB\n");
731
732 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
733 int idx;
734
735 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700736 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800737 BasicBlock *bb = GetBasicBlock(block_idx);
738 if (bb == NULL) break;
739 if (bb->block_type == kDead) continue;
740 if (bb->block_type == kEntryBlock) {
741 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
742 } else if (bb->block_type == kExitBlock) {
743 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
744 } else if (bb->block_type == kDalvikByteCode) {
745 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
746 bb->start_offset, bb->id);
747 const MIR *mir;
748 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
749 bb->first_mir_insn ? " | " : " ");
750 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
751 int opcode = mir->dalvikInsn.opcode;
752 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700753 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800754 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700755 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800756 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
757 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
758 mir->next ? " | " : " ");
759 }
760 fprintf(file, " }\"];\n\n");
761 } else if (bb->block_type == kExceptionHandling) {
762 char block_name[BLOCK_NAME_LEN];
763
764 GetBlockName(bb, block_name);
765 fprintf(file, " %s [shape=invhouse];\n", block_name);
766 }
767
768 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
769
buzbee0d829482013-10-11 15:24:55 -0700770 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800771 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700772 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800773 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
774 block_name1, block_name2);
775 }
buzbee0d829482013-10-11 15:24:55 -0700776 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800777 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700778 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800779 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
780 }
781
buzbee0d829482013-10-11 15:24:55 -0700782 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800783 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
784 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700785 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
786 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700787 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800788
789 int succ_id = 0;
790 while (true) {
791 if (successor_block_info == NULL) break;
792
buzbee0d829482013-10-11 15:24:55 -0700793 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700794 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800795
796 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
797 succ_id++,
798 successor_block_info->key,
799 dest_block->start_offset,
800 (next_successor_block_info != NULL) ? " | " : " ");
801
802 successor_block_info = next_successor_block_info;
803 }
804 fprintf(file, " }\"];\n\n");
805
806 GetBlockName(bb, block_name1);
807 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
808 block_name1, bb->start_offset, bb->id);
809
buzbee0d829482013-10-11 15:24:55 -0700810 if (bb->successor_block_list_type == kPackedSwitch ||
811 bb->successor_block_list_type == kSparseSwitch) {
812 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800813
814 succ_id = 0;
815 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700816 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800817 if (successor_block_info == NULL) break;
818
buzbee0d829482013-10-11 15:24:55 -0700819 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800820
821 GetBlockName(dest_block, block_name2);
822 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
823 bb->id, succ_id++, block_name2);
824 }
825 }
826 }
827 fprintf(file, "\n");
828
829 if (cu_->verbose) {
830 /* Display the dominator tree */
831 GetBlockName(bb, block_name1);
832 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
833 block_name1, block_name1);
834 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700835 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800836 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
837 }
838 }
839 }
840 fprintf(file, "}\n");
841 fclose(file);
842}
843
buzbee1fd33462013-03-25 13:40:45 -0700844/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700845void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700846 if (bb->first_mir_insn == NULL) {
847 DCHECK(bb->last_mir_insn == NULL);
848 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700849 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700850 } else {
851 bb->last_mir_insn->next = mir;
buzbee1fd33462013-03-25 13:40:45 -0700852 mir->next = NULL;
853 bb->last_mir_insn = mir;
854 }
855}
856
857/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700858void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700859 if (bb->first_mir_insn == NULL) {
860 DCHECK(bb->last_mir_insn == NULL);
861 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700862 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700863 } else {
buzbee1fd33462013-03-25 13:40:45 -0700864 mir->next = bb->first_mir_insn;
buzbee1fd33462013-03-25 13:40:45 -0700865 bb->first_mir_insn = mir;
866 }
867}
868
869/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700870void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700871 new_mir->next = current_mir->next;
872 current_mir->next = new_mir;
873
buzbee0d829482013-10-11 15:24:55 -0700874 if (bb->last_mir_insn == current_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700875 /* Is the last MIR in the block */
876 bb->last_mir_insn = new_mir;
877 }
878}
879
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700880char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700881 DecodedInstruction insn = mir->dalvikInsn;
882 std::string str;
883 int flags = 0;
884 int opcode = insn.opcode;
885 char* ret;
886 bool nop = false;
887 SSARepresentation* ssa_rep = mir->ssa_rep;
888 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
889 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
890 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
891
892 // Handle special cases.
893 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
894 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
895 str.append(": ");
896 // Recover the original Dex instruction
897 insn = mir->meta.throw_insn->dalvikInsn;
898 ssa_rep = mir->meta.throw_insn->ssa_rep;
899 defs = ssa_rep->num_defs;
900 uses = ssa_rep->num_uses;
901 opcode = insn.opcode;
902 } else if (opcode == kMirOpNop) {
903 str.append("[");
buzbee0d829482013-10-11 15:24:55 -0700904 // Recover original opcode.
905 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
906 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -0700907 nop = true;
908 }
909
910 if (opcode >= kMirOpFirst) {
911 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
912 } else {
913 dalvik_format = Instruction::FormatOf(insn.opcode);
914 flags = Instruction::FlagsOf(insn.opcode);
915 str.append(Instruction::Name(insn.opcode));
916 }
917
918 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -0700919 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -0700920 str.append(StringPrintf(" %s = (%s",
921 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
922 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700923 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700924 int i;
925 for (i = 1; i < uses; i++) {
926 str.append(StringPrintf(", %s:%d",
927 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
928 incoming[i]));
929 }
930 str.append(")");
931 } else if ((flags & Instruction::kBranch) != 0) {
932 // For branches, decode the instructions to print out the branch targets.
933 int offset = 0;
934 switch (dalvik_format) {
935 case Instruction::k21t:
936 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
937 offset = insn.vB;
938 break;
939 case Instruction::k22t:
940 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
941 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
942 offset = insn.vC;
943 break;
944 case Instruction::k10t:
945 case Instruction::k20t:
946 case Instruction::k30t:
947 offset = insn.vA;
948 break;
949 default:
950 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
951 }
952 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
953 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
954 } else {
955 // For invokes-style formats, treat wide regs as a pair of singles
956 bool show_singles = ((dalvik_format == Instruction::k35c) ||
957 (dalvik_format == Instruction::k3rc));
958 if (defs != 0) {
959 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
960 if (uses != 0) {
961 str.append(", ");
962 }
963 }
964 for (int i = 0; i < uses; i++) {
965 str.append(
966 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
967 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
968 // For the listing, skip the high sreg.
969 i++;
970 }
971 if (i != (uses -1)) {
972 str.append(",");
973 }
974 }
975 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700976 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -0700977 case Instruction::k21s:
978 case Instruction::k31i:
979 case Instruction::k21h:
980 str.append(StringPrintf(", #%d", insn.vB));
981 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700982 case Instruction::k51l: // Add one wide immediate
Ian Rogers23b03b52014-01-24 11:10:03 -0800983 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -0700984 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700985 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -0700986 case Instruction::k31c:
987 str.append(StringPrintf(", index #%d", insn.vB));
988 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700989 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -0700990 str.append(StringPrintf(", index #%d", insn.vC));
991 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700992 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -0700993 case Instruction::k22b:
994 str.append(StringPrintf(", #%d", insn.vC));
995 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700996 default: {
997 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -0700998 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700999 }
buzbee1fd33462013-03-25 13:40:45 -07001000 }
1001 if (nop) {
1002 str.append("]--optimized away");
1003 }
1004 int length = str.length() + 1;
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001005 ret = static_cast<char*>(arena_->Alloc(length, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001006 strncpy(ret, str.c_str(), length);
1007 return ret;
1008}
1009
1010/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001011void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001012 static const struct { const char before; const char after; } match[] = {
1013 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1014 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1015 };
buzbee1fd33462013-03-25 13:40:45 -07001016 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1017 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1018 }
1019}
1020
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001021std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001022 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1023 // the arena. We should be smarter and just place straight into the arena, or compute the
1024 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001025 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1026}
1027
1028// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001029std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001030 if (reg_location_ == NULL) {
1031 // Pre-SSA - just use the standard name
1032 return GetSSAName(ssa_reg);
1033 }
1034 if (IsConst(reg_location_[ssa_reg])) {
1035 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001036 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001037 ConstantValueWide(reg_location_[ssa_reg]));
1038 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001039 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001040 ConstantValue(reg_location_[ssa_reg]));
1041 }
1042 } else {
1043 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1044 }
1045}
1046
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001047void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001048 switch (bb->block_type) {
1049 case kEntryBlock:
1050 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1051 break;
1052 case kExitBlock:
1053 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1054 break;
1055 case kDalvikByteCode:
1056 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1057 break;
1058 case kExceptionHandling:
1059 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1060 bb->id);
1061 break;
1062 default:
1063 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1064 break;
1065 }
1066}
1067
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001068const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001069 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001070 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1071 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1072}
1073
1074/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001075void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001076 BasicBlock* bb;
1077 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001078 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001079 "Entry Block",
1080 "Code Block",
1081 "Exit Block",
1082 "Exception Handling",
1083 "Catch Block"
1084 };
1085
1086 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1087 LOG(INFO) << cu_->insns << " insns";
1088 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001089 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001090
1091 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001092 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001093 if (bb == NULL) break;
1094 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1095 bb->id,
1096 block_type_names[bb->block_type],
1097 bb->start_offset,
1098 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1099 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001100 if (bb->taken != NullBasicBlockId) {
1101 LOG(INFO) << " Taken branch: block " << bb->taken
1102 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001103 }
buzbee0d829482013-10-11 15:24:55 -07001104 if (bb->fall_through != NullBasicBlockId) {
1105 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1106 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001107 }
1108 }
1109}
1110
1111/*
1112 * Build an array of location records for the incoming arguments.
1113 * Note: one location record per word of arguments, with dummy
1114 * high-word loc for wide arguments. Also pull up any following
1115 * MOVE_RESULT and incorporate it into the invoke.
1116 */
1117CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001118 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001119 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
1120 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001121 MIR* move_result_mir = FindMoveResult(bb, mir);
1122 if (move_result_mir == NULL) {
1123 info->result.location = kLocInvalid;
1124 } else {
1125 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001126 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1127 }
1128 info->num_arg_words = mir->ssa_rep->num_uses;
1129 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001130 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001131 for (int i = 0; i < info->num_arg_words; i++) {
1132 info->args[i] = GetRawSrc(mir, i);
1133 }
1134 info->opt_flags = mir->optimization_flags;
1135 info->type = type;
1136 info->is_range = is_range;
1137 info->index = mir->dalvikInsn.vB;
1138 info->offset = mir->offset;
1139 return info;
1140}
1141
buzbee862a7602013-04-05 10:58:54 -07001142// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001143BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001144 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
1145 ArenaAllocator::kAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001146 bb->block_type = block_type;
1147 bb->id = block_id;
1148 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001149 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001150 (block_type == kExitBlock) ? 2048 : 2,
1151 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001152 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001153 block_id_map_.Put(block_id, block_id);
1154 return bb;
1155}
buzbee1fd33462013-03-25 13:40:45 -07001156
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001157void MIRGraph::InitializeConstantPropagation() {
1158 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
1159 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), ArenaAllocator::kAllocDFInfo));
1160}
1161
1162void MIRGraph::InitializeMethodUses() {
1163 // The gate starts by initializing the use counts
1164 int num_ssa_regs = GetNumSSARegs();
1165 use_counts_.Resize(num_ssa_regs + 32);
1166 raw_use_counts_.Resize(num_ssa_regs + 32);
1167 // Initialize list
1168 for (int i = 0; i < num_ssa_regs; i++) {
1169 use_counts_.Insert(0);
1170 raw_use_counts_.Insert(0);
1171 }
1172}
1173
1174void MIRGraph::InitializeSSATransformation() {
1175 /* Compute the DFS order */
1176 ComputeDFSOrders();
1177
1178 /* Compute the dominator info */
1179 ComputeDominators();
1180
1181 /* Allocate data structures in preparation for SSA conversion */
1182 CompilerInitializeSSAConversion();
1183
1184 /* Find out the "Dalvik reg def x block" relation */
1185 ComputeDefBlockMatrix();
1186
1187 /* Insert phi nodes to dominance frontiers for all variables */
1188 InsertPhiNodes();
1189
1190 /* Rename register names by local defs and phi nodes */
1191 ClearAllVisitedFlags();
1192 DoDFSPreOrderSSARename(GetEntryBlock());
1193
1194 /*
1195 * Shared temp bit vector used by each block to count the number of defs
1196 * from all the predecessor blocks.
1197 */
1198 temp_ssa_register_v_ =
1199 new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false, kBitMapTempSSARegisterV);
1200}
1201
1202void MIRGraph::CheckSSARegisterVector() {
1203 DCHECK(temp_ssa_register_v_ != nullptr);
1204}
1205
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001206} // namespace art