blob: fb306de0c1396512b19711f8220f3a2d6aee82a1 [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
23namespace art {
24
25#define MAX_PATTERN_LEN 5
26
27struct CodePattern {
28 const Instruction::Code opcodes[MAX_PATTERN_LEN];
29 const SpecialCaseHandler handler_code;
30};
31
32static const CodePattern special_patterns[] = {
33 {{Instruction::RETURN_VOID}, kNullMethod},
34 {{Instruction::CONST, Instruction::RETURN}, kConstFunction},
35 {{Instruction::CONST_4, Instruction::RETURN}, kConstFunction},
36 {{Instruction::CONST_4, Instruction::RETURN_OBJECT}, kConstFunction},
37 {{Instruction::CONST_16, Instruction::RETURN}, kConstFunction},
38 {{Instruction::IGET, Instruction:: RETURN}, kIGet},
39 {{Instruction::IGET_BOOLEAN, Instruction::RETURN}, kIGetBoolean},
40 {{Instruction::IGET_OBJECT, Instruction::RETURN_OBJECT}, kIGetObject},
41 {{Instruction::IGET_BYTE, Instruction::RETURN}, kIGetByte},
42 {{Instruction::IGET_CHAR, Instruction::RETURN}, kIGetChar},
43 {{Instruction::IGET_SHORT, Instruction::RETURN}, kIGetShort},
44 {{Instruction::IGET_WIDE, Instruction::RETURN_WIDE}, kIGetWide},
45 {{Instruction::IPUT, Instruction::RETURN_VOID}, kIPut},
46 {{Instruction::IPUT_BOOLEAN, Instruction::RETURN_VOID}, kIPutBoolean},
47 {{Instruction::IPUT_OBJECT, Instruction::RETURN_VOID}, kIPutObject},
48 {{Instruction::IPUT_BYTE, Instruction::RETURN_VOID}, kIPutByte},
49 {{Instruction::IPUT_CHAR, Instruction::RETURN_VOID}, kIPutChar},
50 {{Instruction::IPUT_SHORT, Instruction::RETURN_VOID}, kIPutShort},
51 {{Instruction::IPUT_WIDE, Instruction::RETURN_VOID}, kIPutWide},
52 {{Instruction::RETURN}, kIdentity},
53 {{Instruction::RETURN_OBJECT}, kIdentity},
54 {{Instruction::RETURN_WIDE}, kIdentity},
55};
56
buzbee1fd33462013-03-25 13:40:45 -070057const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
58 "Phi",
59 "Copy",
60 "FusedCmplFloat",
61 "FusedCmpgFloat",
62 "FusedCmplDouble",
63 "FusedCmpgDouble",
64 "FusedCmpLong",
65 "Nop",
66 "OpNullCheck",
67 "OpRangeCheck",
68 "OpDivZeroCheck",
69 "Check1",
70 "Check2",
71 "Select",
72};
73
buzbee862a7602013-04-05 10:58:54 -070074MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070075 : reg_location_(NULL),
buzbee862a7602013-04-05 10:58:54 -070076 compiler_temps_(arena, 6, kGrowableArrayMisc),
buzbee1fd33462013-03-25 13:40:45 -070077 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080078 ssa_base_vregs_(NULL),
79 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080080 vreg_to_ssa_map_(NULL),
81 ssa_last_defs_(NULL),
82 is_constant_v_(NULL),
83 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070084 use_counts_(arena, 256, kGrowableArrayMisc),
85 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080086 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070087 dfs_order_(NULL),
88 dfs_post_order_(NULL),
89 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080090 i_dom_list_(NULL),
91 def_block_matrix_(NULL),
92 temp_block_v_(NULL),
93 temp_dalvik_register_v_(NULL),
94 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070095 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080096 try_block_addr_(NULL),
97 entry_block_(NULL),
98 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080099 num_blocks_(0),
100 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700101 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -0800102 current_method_(kInvalidEntry),
103 current_offset_(kInvalidEntry),
104 def_count_(0),
105 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700106 num_ssa_regs_(0),
107 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700108 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
109 checkstats_(NULL),
buzbee479f83c2013-07-19 10:58:21 -0700110 special_case_(kNoHandler),
buzbeeb48819d2013-09-14 16:15:25 -0700111 arena_(arena),
112 backward_branches_(0),
113 forward_branches_(0) {
buzbee862a7602013-04-05 10:58:54 -0700114 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
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 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700124int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -0800125 const Instruction* instruction = Instruction::At(code_ptr);
126 *decoded_instruction = DecodedInstruction(instruction);
127
128 return instruction->SizeInCodeUnits();
129}
130
131
132/* Split an existing block from the specified code offset into two */
133BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700134 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee311ca162013-02-28 15:56:43 -0800135 MIR* insn = orig_block->first_mir_insn;
136 while (insn) {
137 if (insn->offset == code_offset) break;
138 insn = insn->next;
139 }
140 if (insn == NULL) {
141 LOG(FATAL) << "Break split failed";
142 }
buzbee862a7602013-04-05 10:58:54 -0700143 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
144 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800145
146 bottom_block->start_offset = code_offset;
147 bottom_block->first_mir_insn = insn;
148 bottom_block->last_mir_insn = orig_block->last_mir_insn;
149
150 /* If this block was terminated by a return, the flag needs to go with the bottom block */
151 bottom_block->terminated_by_return = orig_block->terminated_by_return;
152 orig_block->terminated_by_return = false;
153
154 /* Add it to the quick lookup cache */
buzbeeb48819d2013-09-14 16:15:25 -0700155 dex_pc_to_block_map_.Put(bottom_block->start_offset, bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800156
157 /* Handle the taken path */
158 bottom_block->taken = orig_block->taken;
159 if (bottom_block->taken) {
160 orig_block->taken = NULL;
buzbee862a7602013-04-05 10:58:54 -0700161 bottom_block->taken->predecessors->Delete(orig_block);
162 bottom_block->taken->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800163 }
164
165 /* Handle the fallthrough path */
166 bottom_block->fall_through = orig_block->fall_through;
167 orig_block->fall_through = bottom_block;
buzbee862a7602013-04-05 10:58:54 -0700168 bottom_block->predecessors->Insert(orig_block);
buzbee311ca162013-02-28 15:56:43 -0800169 if (bottom_block->fall_through) {
buzbee862a7602013-04-05 10:58:54 -0700170 bottom_block->fall_through->predecessors->Delete(orig_block);
171 bottom_block->fall_through->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800172 }
173
174 /* Handle the successor list */
175 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
176 bottom_block->successor_block_list = orig_block->successor_block_list;
177 orig_block->successor_block_list.block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -0700178 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800179 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700180 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800181 if (successor_block_info == NULL) break;
182 BasicBlock *bb = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700183 bb->predecessors->Delete(orig_block);
184 bb->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800185 }
186 }
187
188 orig_block->last_mir_insn = insn->prev;
189
190 insn->prev->next = NULL;
191 insn->prev = NULL;
192 /*
193 * Update the immediate predecessor block pointer so that outgoing edges
194 * can be applied to the proper block.
195 */
196 if (immed_pred_block_p) {
197 DCHECK_EQ(*immed_pred_block_p, orig_block);
198 *immed_pred_block_p = bottom_block;
199 }
buzbeeb48819d2013-09-14 16:15:25 -0700200
201 // Associate dex instructions in the bottom block with the new container.
202 MIR* p = bottom_block->first_mir_insn;
203 while (p != NULL) {
204 int opcode = p->dalvikInsn.opcode;
205 /*
206 * Some messiness here to ensure that we only enter real opcodes and only the
207 * first half of a potentially throwing instruction that has been split into
208 * CHECK and work portions. The 2nd half of a split operation will have a non-null
209 * throw_insn pointer that refers to the 1st half.
210 */
211 if ((opcode == kMirOpCheck) || (!IsPseudoMirOp(opcode) && (p->meta.throw_insn == NULL))) {
212 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
213 }
214 p = (p == bottom_block->last_mir_insn) ? NULL : p->next;
215 }
216
buzbee311ca162013-02-28 15:56:43 -0800217 return bottom_block;
218}
219
220/*
221 * Given a code offset, find out the block that starts with it. If the offset
222 * is in the middle of an existing block, split it into two. If immed_pred_block_p
223 * is not non-null and is the block being split, update *immed_pred_block_p to
224 * point to the bottom block so that outgoing edges can be set up properly
225 * (by the caller)
226 * Utilizes a map for fast lookup of the typical cases.
227 */
228BasicBlock* MIRGraph::FindBlock(unsigned int code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700229 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700230 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800231 return NULL;
232 }
buzbeeb48819d2013-09-14 16:15:25 -0700233
234 int block_id = dex_pc_to_block_map_.Get(code_offset);
235 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
236
237 if ((bb != NULL) && (bb->start_offset == code_offset)) {
238 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700239 return bb;
240 }
buzbee311ca162013-02-28 15:56:43 -0800241
buzbeeb48819d2013-09-14 16:15:25 -0700242 // No direct hit.
243 if (!create) {
244 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800245 }
246
buzbeeb48819d2013-09-14 16:15:25 -0700247 if (bb != NULL) {
248 // The target exists somewhere in an existing block.
249 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
250 }
251
252 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700253 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
254 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800255 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700256 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800257 return bb;
258}
259
buzbeeb48819d2013-09-14 16:15:25 -0700260
buzbee311ca162013-02-28 15:56:43 -0800261/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700262void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800263 int tries_size = current_code_item_->tries_size_;
264 int offset;
265
266 if (tries_size == 0) {
267 return;
268 }
269
270 for (int i = 0; i < tries_size; i++) {
271 const DexFile::TryItem* pTry =
272 DexFile::GetTryItems(*current_code_item_, i);
273 int start_offset = pTry->start_addr_;
274 int end_offset = start_offset + pTry->insn_count_;
275 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700276 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800277 }
278 }
279
280 // Iterate over each of the handlers to enqueue the empty Catch blocks
281 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
282 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
283 for (uint32_t idx = 0; idx < handlers_size; idx++) {
284 CatchHandlerIterator iterator(handlers_ptr);
285 for (; iterator.HasNext(); iterator.Next()) {
286 uint32_t address = iterator.GetHandlerAddress();
287 FindBlock(address, false /* split */, true /*create*/,
288 /* immed_pred_block_p */ NULL);
289 }
290 handlers_ptr = iterator.EndDataPointer();
291 }
292}
293
294/* Process instructions with the kBranch flag */
295BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
296 int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700297 const uint16_t* code_end) {
buzbee311ca162013-02-28 15:56:43 -0800298 int target = cur_offset;
299 switch (insn->dalvikInsn.opcode) {
300 case Instruction::GOTO:
301 case Instruction::GOTO_16:
302 case Instruction::GOTO_32:
303 target += insn->dalvikInsn.vA;
304 break;
305 case Instruction::IF_EQ:
306 case Instruction::IF_NE:
307 case Instruction::IF_LT:
308 case Instruction::IF_GE:
309 case Instruction::IF_GT:
310 case Instruction::IF_LE:
311 cur_block->conditional_branch = true;
312 target += insn->dalvikInsn.vC;
313 break;
314 case Instruction::IF_EQZ:
315 case Instruction::IF_NEZ:
316 case Instruction::IF_LTZ:
317 case Instruction::IF_GEZ:
318 case Instruction::IF_GTZ:
319 case Instruction::IF_LEZ:
320 cur_block->conditional_branch = true;
321 target += insn->dalvikInsn.vB;
322 break;
323 default:
324 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
325 }
buzbeeb48819d2013-09-14 16:15:25 -0700326 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800327 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
328 /* immed_pred_block_p */ &cur_block);
329 cur_block->taken = taken_block;
buzbee862a7602013-04-05 10:58:54 -0700330 taken_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800331
332 /* Always terminate the current block for conditional branches */
333 if (flags & Instruction::kContinue) {
334 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
335 /*
336 * If the method is processed
337 * in sequential order from the
338 * beginning, we don't need to
339 * specify split for continue
340 * blocks. However, this
341 * routine can be called by
342 * compileLoop, which starts
343 * parsing the method from an
344 * arbitrary address in the
345 * method body.
346 */
347 true,
348 /* create */
349 true,
350 /* immed_pred_block_p */
351 &cur_block);
352 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700353 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800354 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700355 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800356 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800357 }
358 return cur_block;
359}
360
361/* Process instructions with the kSwitch flag */
362void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700363 int flags) {
buzbee311ca162013-02-28 15:56:43 -0800364 const uint16_t* switch_data =
365 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
366 int size;
367 const int* keyTable;
368 const int* target_table;
369 int i;
370 int first_key;
371
372 /*
373 * Packed switch data format:
374 * ushort ident = 0x0100 magic value
375 * ushort size number of entries in the table
376 * int first_key first (and lowest) switch case value
377 * int targets[size] branch targets, relative to switch opcode
378 *
379 * Total size is (4+size*2) 16-bit code units.
380 */
381 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
382 DCHECK_EQ(static_cast<int>(switch_data[0]),
383 static_cast<int>(Instruction::kPackedSwitchSignature));
384 size = switch_data[1];
385 first_key = switch_data[2] | (switch_data[3] << 16);
386 target_table = reinterpret_cast<const int*>(&switch_data[4]);
387 keyTable = NULL; // Make the compiler happy
388 /*
389 * Sparse switch data format:
390 * ushort ident = 0x0200 magic value
391 * ushort size number of entries in the table; > 0
392 * int keys[size] keys, sorted low-to-high; 32-bit aligned
393 * int targets[size] branch targets, relative to switch opcode
394 *
395 * Total size is (2+size*4) 16-bit code units.
396 */
397 } else {
398 DCHECK_EQ(static_cast<int>(switch_data[0]),
399 static_cast<int>(Instruction::kSparseSwitchSignature));
400 size = switch_data[1];
401 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
402 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
403 first_key = 0; // To make the compiler happy
404 }
405
406 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
407 LOG(FATAL) << "Successor block list already in use: "
408 << static_cast<int>(cur_block->successor_block_list.block_list_type);
409 }
410 cur_block->successor_block_list.block_list_type =
411 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
412 kPackedSwitch : kSparseSwitch;
buzbee862a7602013-04-05 10:58:54 -0700413 cur_block->successor_block_list.blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700414 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800415
416 for (i = 0; i < size; i++) {
417 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
418 /* create */ true, /* immed_pred_block_p */ &cur_block);
419 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700420 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
421 ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800422 successor_block_info->block = case_block;
423 successor_block_info->key =
424 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
425 first_key + i : keyTable[i];
buzbee862a7602013-04-05 10:58:54 -0700426 cur_block->successor_block_list.blocks->Insert(successor_block_info);
427 case_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800428 }
429
430 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700431 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
432 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800433 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700434 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800435}
436
437/* Process instructions with the kThrow flag */
438BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
439 int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700440 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700441 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee311ca162013-02-28 15:56:43 -0800442
443 /* In try block */
444 if (in_try_block) {
445 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
446
447 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
448 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
449 LOG(FATAL) << "Successor block list already in use: "
450 << static_cast<int>(cur_block->successor_block_list.block_list_type);
451 }
452
453 cur_block->successor_block_list.block_list_type = kCatch;
buzbee862a7602013-04-05 10:58:54 -0700454 cur_block->successor_block_list.blocks =
455 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800456
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700457 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800458 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
459 false /* creat */, NULL /* immed_pred_block_p */);
460 catch_block->catch_entry = true;
461 if (kIsDebugBuild) {
462 catches_.insert(catch_block->start_offset);
463 }
464 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700465 (arena_->Alloc(sizeof(SuccessorBlockInfo), ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800466 successor_block_info->block = catch_block;
467 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee862a7602013-04-05 10:58:54 -0700468 cur_block->successor_block_list.blocks->Insert(successor_block_info);
469 catch_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800470 }
471 } else {
buzbee862a7602013-04-05 10:58:54 -0700472 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800473 cur_block->taken = eh_block;
buzbee862a7602013-04-05 10:58:54 -0700474 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800475 eh_block->start_offset = cur_offset;
buzbee862a7602013-04-05 10:58:54 -0700476 eh_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800477 }
478
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700479 if (insn->dalvikInsn.opcode == Instruction::THROW) {
buzbee311ca162013-02-28 15:56:43 -0800480 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700481 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800482 // Force creation of new block following THROW via side-effect
483 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
484 /* immed_pred_block_p */ NULL);
485 }
486 if (!in_try_block) {
487 // Don't split a THROW that can't rethrow - we're done.
488 return cur_block;
489 }
490 }
491
492 /*
493 * Split the potentially-throwing instruction into two parts.
494 * The first half will be a pseudo-op that captures the exception
495 * edges and terminates the basic block. It always falls through.
496 * Then, create a new basic block that begins with the throwing instruction
497 * (minus exceptions). Note: this new basic block must NOT be entered into
498 * the block_map. If the potentially-throwing instruction is the target of a
499 * future branch, we need to find the check psuedo half. The new
500 * basic block containing the work portion of the instruction should
501 * only be entered via fallthrough from the block containing the
502 * pseudo exception edge MIR. Note also that this new block is
503 * not automatically terminated after the work portion, and may
504 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700505 *
506 * Note also that the dex_pc_to_block_map_ entry for the potentially
507 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800508 */
buzbee862a7602013-04-05 10:58:54 -0700509 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
510 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800511 new_block->start_offset = insn->offset;
512 cur_block->fall_through = new_block;
buzbee862a7602013-04-05 10:58:54 -0700513 new_block->predecessors->Insert(cur_block);
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700514 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800515 *new_insn = *insn;
516 insn->dalvikInsn.opcode =
517 static_cast<Instruction::Code>(kMirOpCheck);
518 // Associate the two halves
519 insn->meta.throw_insn = new_insn;
520 new_insn->meta.throw_insn = insn;
521 AppendMIR(new_block, new_insn);
522 return new_block;
523}
524
525/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
526void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700527 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700528 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800529 current_code_item_ = code_item;
530 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
531 current_method_ = m_units_.size();
532 current_offset_ = 0;
533 // TODO: will need to snapshot stack image and use that as the mir context identification.
534 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
535 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
536 const uint16_t* code_ptr = current_code_item_->insns_;
537 const uint16_t* code_end =
538 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
539
540 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700541 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700542 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700543 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 -0700544
buzbee311ca162013-02-28 15:56:43 -0800545 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700546 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
547 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800548
549 // If this is the first method, set up default entry and exit blocks.
550 if (current_method_ == 0) {
551 DCHECK(entry_block_ == NULL);
552 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700553 DCHECK_EQ(num_blocks_, 0);
buzbee862a7602013-04-05 10:58:54 -0700554 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
555 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
556 block_list_.Insert(entry_block_);
557 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800558 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
559 cu_->dex_file = &dex_file;
560 cu_->class_def_idx = class_def_idx;
561 cu_->method_idx = method_idx;
562 cu_->access_flags = access_flags;
563 cu_->invoke_type = invoke_type;
564 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
565 cu_->num_ins = current_code_item_->ins_size_;
566 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
567 cu_->num_outs = current_code_item_->outs_size_;
568 cu_->num_dalvik_registers = current_code_item_->registers_size_;
569 cu_->insns = current_code_item_->insns_;
570 cu_->code_item = current_code_item_;
571 } else {
572 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
573 /*
574 * Will need to manage storage for ins & outs, push prevous state and update
575 * insert point.
576 */
577 }
578
579 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700580 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800581 DCHECK_EQ(current_offset_, 0);
582 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700583 block_list_.Insert(cur_block);
buzbeeb48819d2013-09-14 16:15:25 -0700584 // FIXME: this needs to insert at the insert point rather than entry block.
buzbee311ca162013-02-28 15:56:43 -0800585 entry_block_->fall_through = cur_block;
buzbee862a7602013-04-05 10:58:54 -0700586 cur_block->predecessors->Insert(entry_block_);
buzbee311ca162013-02-28 15:56:43 -0800587
588 /* Identify code range in try blocks and set up the empty catch blocks */
589 ProcessTryCatchBlocks();
590
591 /* Set up for simple method detection */
592 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
593 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
594 bool* dead_pattern =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700595 static_cast<bool*>(arena_->Alloc(sizeof(bool) * num_patterns, ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800596 int pattern_pos = 0;
597
598 /* Parse all instructions and put them into containing basic blocks */
599 while (code_ptr < code_end) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700600 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800601 insn->offset = current_offset_;
602 insn->m_unit_index = current_method_;
603 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
604 insn->width = width;
605 Instruction::Code opcode = insn->dalvikInsn.opcode;
606 if (opcode_count_ != NULL) {
607 opcode_count_[static_cast<int>(opcode)]++;
608 }
609
buzbee311ca162013-02-28 15:56:43 -0800610 /* Possible simple method? */
611 if (live_pattern) {
612 live_pattern = false;
buzbee479f83c2013-07-19 10:58:21 -0700613 special_case_ = kNoHandler;
buzbee311ca162013-02-28 15:56:43 -0800614 for (int i = 0; i < num_patterns; i++) {
615 if (!dead_pattern[i]) {
616 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
617 live_pattern = true;
buzbee479f83c2013-07-19 10:58:21 -0700618 special_case_ = special_patterns[i].handler_code;
buzbee311ca162013-02-28 15:56:43 -0800619 } else {
620 dead_pattern[i] = true;
621 }
622 }
623 }
624 pattern_pos++;
625 }
626
buzbee311ca162013-02-28 15:56:43 -0800627 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
628
buzbee1fd33462013-03-25 13:40:45 -0700629 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800630
631 if (df_flags & DF_HAS_DEFS) {
632 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
633 }
634
buzbee27247762013-07-28 12:03:58 -0700635 // Check for inline data block signatures
636 if (opcode == Instruction::NOP) {
637 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
638 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
639 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
640 uint16_t following_raw_instruction = code_ptr[1];
641 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
642 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
643 (following_raw_instruction == Instruction::kArrayDataSignature)) {
644 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
645 }
646 }
647 if (width == 1) {
648 // It is a simple nop - treat normally.
649 AppendMIR(cur_block, insn);
650 } else {
651 DCHECK(cur_block->fall_through == NULL);
652 DCHECK(cur_block->taken == NULL);
653 // Unreachable instruction, mark for no continuation.
654 flags &= ~Instruction::kContinue;
655 }
656 } else {
657 AppendMIR(cur_block, insn);
658 }
659
buzbeeb48819d2013-09-14 16:15:25 -0700660 // Associate the starting dex_pc for this opcode with its containing basic block.
661 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
662
buzbee27247762013-07-28 12:03:58 -0700663 code_ptr += width;
664
buzbee311ca162013-02-28 15:56:43 -0800665 if (flags & Instruction::kBranch) {
666 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
667 width, flags, code_ptr, code_end);
668 } else if (flags & Instruction::kReturn) {
669 cur_block->terminated_by_return = true;
670 cur_block->fall_through = exit_block_;
buzbee862a7602013-04-05 10:58:54 -0700671 exit_block_->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800672 /*
673 * Terminate the current block if there are instructions
674 * afterwards.
675 */
676 if (code_ptr < code_end) {
677 /*
678 * Create a fallthrough block for real instructions
679 * (incl. NOP).
680 */
buzbee27247762013-07-28 12:03:58 -0700681 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
682 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800683 }
684 } else if (flags & Instruction::kThrow) {
685 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
686 code_ptr, code_end);
687 } else if (flags & Instruction::kSwitch) {
688 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
689 }
690 current_offset_ += width;
691 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
692 false, /* immed_pred_block_p */ NULL);
693 if (next_block) {
694 /*
695 * The next instruction could be the target of a previously parsed
696 * forward branch so a block is already created. If the current
697 * instruction is not an unconditional branch, connect them through
698 * the fall-through link.
699 */
700 DCHECK(cur_block->fall_through == NULL ||
701 cur_block->fall_through == next_block ||
702 cur_block->fall_through == exit_block_);
703
704 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
705 cur_block->fall_through = next_block;
buzbee862a7602013-04-05 10:58:54 -0700706 next_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800707 }
708 cur_block = next_block;
709 }
710 }
711 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
712 DumpCFG("/sdcard/1_post_parse_cfg/", true);
713 }
714
715 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700716 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800717 }
718}
719
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700720void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800721 DCHECK(opcode_count_ != NULL);
722 LOG(INFO) << "Opcode Count";
723 for (int i = 0; i < kNumPackedOpcodes; i++) {
724 if (opcode_count_[i] != 0) {
725 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
726 << " " << opcode_count_[i];
727 }
728 }
729}
730
731// TODO: use a configurable base prefix, and adjust callers to supply pass name.
732/* Dump the CFG into a DOT graph */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700733void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks) {
buzbee311ca162013-02-28 15:56:43 -0800734 FILE* file;
735 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
736 ReplaceSpecialChars(fname);
737 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
738 GetEntryBlock()->fall_through->start_offset);
739 file = fopen(fname.c_str(), "w");
740 if (file == NULL) {
741 return;
742 }
743 fprintf(file, "digraph G {\n");
744
745 fprintf(file, " rankdir=TB\n");
746
747 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
748 int idx;
749
750 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700751 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800752 BasicBlock *bb = GetBasicBlock(block_idx);
753 if (bb == NULL) break;
754 if (bb->block_type == kDead) continue;
755 if (bb->block_type == kEntryBlock) {
756 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
757 } else if (bb->block_type == kExitBlock) {
758 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
759 } else if (bb->block_type == kDalvikByteCode) {
760 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
761 bb->start_offset, bb->id);
762 const MIR *mir;
763 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
764 bb->first_mir_insn ? " | " : " ");
765 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
766 int opcode = mir->dalvikInsn.opcode;
767 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700768 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800769 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700770 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800771 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
772 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
773 mir->next ? " | " : " ");
774 }
775 fprintf(file, " }\"];\n\n");
776 } else if (bb->block_type == kExceptionHandling) {
777 char block_name[BLOCK_NAME_LEN];
778
779 GetBlockName(bb, block_name);
780 fprintf(file, " %s [shape=invhouse];\n", block_name);
781 }
782
783 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
784
785 if (bb->taken) {
786 GetBlockName(bb, block_name1);
787 GetBlockName(bb->taken, block_name2);
788 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
789 block_name1, block_name2);
790 }
791 if (bb->fall_through) {
792 GetBlockName(bb, block_name1);
793 GetBlockName(bb->fall_through, block_name2);
794 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
795 }
796
797 if (bb->successor_block_list.block_list_type != kNotUsed) {
798 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
799 bb->start_offset, bb->id,
800 (bb->successor_block_list.block_list_type == kCatch) ?
801 "Mrecord" : "record");
buzbee862a7602013-04-05 10:58:54 -0700802 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_block_list.blocks);
803 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800804
805 int succ_id = 0;
806 while (true) {
807 if (successor_block_info == NULL) break;
808
809 BasicBlock *dest_block = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700810 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800811
812 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
813 succ_id++,
814 successor_block_info->key,
815 dest_block->start_offset,
816 (next_successor_block_info != NULL) ? " | " : " ");
817
818 successor_block_info = next_successor_block_info;
819 }
820 fprintf(file, " }\"];\n\n");
821
822 GetBlockName(bb, block_name1);
823 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
824 block_name1, bb->start_offset, bb->id);
825
826 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
827 bb->successor_block_list.block_list_type == kSparseSwitch) {
buzbee862a7602013-04-05 10:58:54 -0700828 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800829
830 succ_id = 0;
831 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700832 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800833 if (successor_block_info == NULL) break;
834
835 BasicBlock *dest_block = successor_block_info->block;
836
837 GetBlockName(dest_block, block_name2);
838 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
839 bb->id, succ_id++, block_name2);
840 }
841 }
842 }
843 fprintf(file, "\n");
844
845 if (cu_->verbose) {
846 /* Display the dominator tree */
847 GetBlockName(bb, block_name1);
848 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
849 block_name1, block_name1);
850 if (bb->i_dom) {
851 GetBlockName(bb->i_dom, block_name2);
852 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
853 }
854 }
855 }
856 fprintf(file, "}\n");
857 fclose(file);
858}
859
buzbee1fd33462013-03-25 13:40:45 -0700860/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700861void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700862 if (bb->first_mir_insn == NULL) {
863 DCHECK(bb->last_mir_insn == NULL);
864 bb->last_mir_insn = bb->first_mir_insn = mir;
865 mir->prev = mir->next = NULL;
866 } else {
867 bb->last_mir_insn->next = mir;
868 mir->prev = bb->last_mir_insn;
869 mir->next = NULL;
870 bb->last_mir_insn = mir;
871 }
872}
873
874/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700875void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700876 if (bb->first_mir_insn == NULL) {
877 DCHECK(bb->last_mir_insn == NULL);
878 bb->last_mir_insn = bb->first_mir_insn = mir;
879 mir->prev = mir->next = NULL;
880 } else {
881 bb->first_mir_insn->prev = mir;
882 mir->next = bb->first_mir_insn;
883 mir->prev = NULL;
884 bb->first_mir_insn = mir;
885 }
886}
887
888/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700889void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700890 new_mir->prev = current_mir;
891 new_mir->next = current_mir->next;
892 current_mir->next = new_mir;
893
894 if (new_mir->next) {
895 /* Is not the last MIR in the block */
896 new_mir->next->prev = new_mir;
897 } else {
898 /* Is the last MIR in the block */
899 bb->last_mir_insn = new_mir;
900 }
901}
902
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700903char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700904 DecodedInstruction insn = mir->dalvikInsn;
905 std::string str;
906 int flags = 0;
907 int opcode = insn.opcode;
908 char* ret;
909 bool nop = false;
910 SSARepresentation* ssa_rep = mir->ssa_rep;
911 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
912 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
913 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
914
915 // Handle special cases.
916 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
917 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
918 str.append(": ");
919 // Recover the original Dex instruction
920 insn = mir->meta.throw_insn->dalvikInsn;
921 ssa_rep = mir->meta.throw_insn->ssa_rep;
922 defs = ssa_rep->num_defs;
923 uses = ssa_rep->num_uses;
924 opcode = insn.opcode;
925 } else if (opcode == kMirOpNop) {
926 str.append("[");
927 insn.opcode = mir->meta.original_opcode;
928 opcode = mir->meta.original_opcode;
929 nop = true;
930 }
931
932 if (opcode >= kMirOpFirst) {
933 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
934 } else {
935 dalvik_format = Instruction::FormatOf(insn.opcode);
936 flags = Instruction::FlagsOf(insn.opcode);
937 str.append(Instruction::Name(insn.opcode));
938 }
939
940 if (opcode == kMirOpPhi) {
941 int* incoming = reinterpret_cast<int*>(insn.vB);
942 str.append(StringPrintf(" %s = (%s",
943 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
944 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700945 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700946 int i;
947 for (i = 1; i < uses; i++) {
948 str.append(StringPrintf(", %s:%d",
949 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
950 incoming[i]));
951 }
952 str.append(")");
953 } else if ((flags & Instruction::kBranch) != 0) {
954 // For branches, decode the instructions to print out the branch targets.
955 int offset = 0;
956 switch (dalvik_format) {
957 case Instruction::k21t:
958 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
959 offset = insn.vB;
960 break;
961 case Instruction::k22t:
962 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
963 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
964 offset = insn.vC;
965 break;
966 case Instruction::k10t:
967 case Instruction::k20t:
968 case Instruction::k30t:
969 offset = insn.vA;
970 break;
971 default:
972 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
973 }
974 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
975 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
976 } else {
977 // For invokes-style formats, treat wide regs as a pair of singles
978 bool show_singles = ((dalvik_format == Instruction::k35c) ||
979 (dalvik_format == Instruction::k3rc));
980 if (defs != 0) {
981 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
982 if (uses != 0) {
983 str.append(", ");
984 }
985 }
986 for (int i = 0; i < uses; i++) {
987 str.append(
988 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
989 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
990 // For the listing, skip the high sreg.
991 i++;
992 }
993 if (i != (uses -1)) {
994 str.append(",");
995 }
996 }
997 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700998 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -0700999 case Instruction::k21s:
1000 case Instruction::k31i:
1001 case Instruction::k21h:
1002 str.append(StringPrintf(", #%d", insn.vB));
1003 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001004 case Instruction::k51l: // Add one wide immediate
buzbee1fd33462013-03-25 13:40:45 -07001005 str.append(StringPrintf(", #%lld", insn.vB_wide));
1006 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001007 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001008 case Instruction::k31c:
1009 str.append(StringPrintf(", index #%d", insn.vB));
1010 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001011 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001012 str.append(StringPrintf(", index #%d", insn.vC));
1013 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001014 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001015 case Instruction::k22b:
1016 str.append(StringPrintf(", #%d", insn.vC));
1017 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001018 default: {
1019 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001020 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001021 }
buzbee1fd33462013-03-25 13:40:45 -07001022 }
1023 if (nop) {
1024 str.append("]--optimized away");
1025 }
1026 int length = str.length() + 1;
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001027 ret = static_cast<char*>(arena_->Alloc(length, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001028 strncpy(ret, str.c_str(), length);
1029 return ret;
1030}
1031
1032/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001033void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001034 static const struct { const char before; const char after; } match[] = {
1035 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1036 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1037 };
buzbee1fd33462013-03-25 13:40:45 -07001038 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1039 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1040 }
1041}
1042
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001043std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001044 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1045 // the arena. We should be smarter and just place straight into the arena, or compute the
1046 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001047 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1048}
1049
1050// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001051std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001052 if (reg_location_ == NULL) {
1053 // Pre-SSA - just use the standard name
1054 return GetSSAName(ssa_reg);
1055 }
1056 if (IsConst(reg_location_[ssa_reg])) {
1057 if (!singles_only && reg_location_[ssa_reg].wide) {
1058 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1059 ConstantValueWide(reg_location_[ssa_reg]));
1060 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001061 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001062 ConstantValue(reg_location_[ssa_reg]));
1063 }
1064 } else {
1065 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1066 }
1067}
1068
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001069void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001070 switch (bb->block_type) {
1071 case kEntryBlock:
1072 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1073 break;
1074 case kExitBlock:
1075 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1076 break;
1077 case kDalvikByteCode:
1078 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1079 break;
1080 case kExceptionHandling:
1081 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1082 bb->id);
1083 break;
1084 default:
1085 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1086 break;
1087 }
1088}
1089
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001090const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee1fd33462013-03-25 13:40:45 -07001091 // FIXME: use current code unit for inline support.
1092 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1093 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1094}
1095
1096/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001097void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001098 BasicBlock* bb;
1099 const char* block_type_names[] = {
1100 "Entry Block",
1101 "Code Block",
1102 "Exit Block",
1103 "Exception Handling",
1104 "Catch Block"
1105 };
1106
1107 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1108 LOG(INFO) << cu_->insns << " insns";
1109 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001110 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001111
1112 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001113 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001114 if (bb == NULL) break;
1115 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1116 bb->id,
1117 block_type_names[bb->block_type],
1118 bb->start_offset,
1119 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1120 bb->last_mir_insn ? "" : " empty");
1121 if (bb->taken) {
1122 LOG(INFO) << " Taken branch: block " << bb->taken->id
1123 << "(0x" << std::hex << bb->taken->start_offset << ")";
1124 }
1125 if (bb->fall_through) {
1126 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1127 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1128 }
1129 }
1130}
1131
1132/*
1133 * Build an array of location records for the incoming arguments.
1134 * Note: one location record per word of arguments, with dummy
1135 * high-word loc for wide arguments. Also pull up any following
1136 * MOVE_RESULT and incorporate it into the invoke.
1137 */
1138CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001139 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001140 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
1141 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001142 MIR* move_result_mir = FindMoveResult(bb, mir);
1143 if (move_result_mir == NULL) {
1144 info->result.location = kLocInvalid;
1145 } else {
1146 info->result = GetRawDest(move_result_mir);
1147 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1148 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1149 }
1150 info->num_arg_words = mir->ssa_rep->num_uses;
1151 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001152 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001153 for (int i = 0; i < info->num_arg_words; i++) {
1154 info->args[i] = GetRawSrc(mir, i);
1155 }
1156 info->opt_flags = mir->optimization_flags;
1157 info->type = type;
1158 info->is_range = is_range;
1159 info->index = mir->dalvikInsn.vB;
1160 info->offset = mir->offset;
1161 return info;
1162}
1163
buzbee862a7602013-04-05 10:58:54 -07001164// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001165BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001166 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
1167 ArenaAllocator::kAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001168 bb->block_type = block_type;
1169 bb->id = block_id;
1170 // TUNING: better estimate of the exit block predecessors?
Brian Carlstromdf629502013-07-17 22:39:56 -07001171 bb->predecessors = new (arena_) GrowableArray<BasicBlock*>(arena_,
1172 (block_type == kExitBlock) ? 2048 : 2,
1173 kGrowableArrayPredecessors);
buzbee862a7602013-04-05 10:58:54 -07001174 bb->successor_block_list.block_list_type = kNotUsed;
1175 block_id_map_.Put(block_id, block_id);
1176 return bb;
1177}
buzbee1fd33462013-03-25 13:40:45 -07001178
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001179} // namespace art