blob: 5732dce561a50276cf76b6531a7cea90d6c47344 [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),
99 cur_block_(NULL),
100 num_blocks_(0),
101 current_code_item_(NULL),
102 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),
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700111 arena_(arena) {
buzbee862a7602013-04-05 10:58:54 -0700112 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -0800113}
114
Ian Rogers6282dc12013-04-18 15:54:02 -0700115MIRGraph::~MIRGraph() {
116 STLDeleteElements(&m_units_);
117}
118
buzbee311ca162013-02-28 15:56:43 -0800119/*
120 * Parse an instruction, return the length of the instruction
121 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700122int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -0800123 const Instruction* instruction = Instruction::At(code_ptr);
124 *decoded_instruction = DecodedInstruction(instruction);
125
126 return instruction->SizeInCodeUnits();
127}
128
129
130/* Split an existing block from the specified code offset into two */
131BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700132 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee311ca162013-02-28 15:56:43 -0800133 MIR* insn = orig_block->first_mir_insn;
134 while (insn) {
135 if (insn->offset == code_offset) break;
136 insn = insn->next;
137 }
138 if (insn == NULL) {
139 LOG(FATAL) << "Break split failed";
140 }
buzbee862a7602013-04-05 10:58:54 -0700141 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
142 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800143
144 bottom_block->start_offset = code_offset;
145 bottom_block->first_mir_insn = insn;
146 bottom_block->last_mir_insn = orig_block->last_mir_insn;
147
148 /* If this block was terminated by a return, the flag needs to go with the bottom block */
149 bottom_block->terminated_by_return = orig_block->terminated_by_return;
150 orig_block->terminated_by_return = false;
151
152 /* Add it to the quick lookup cache */
153 block_map_.Put(bottom_block->start_offset, bottom_block);
154
155 /* Handle the taken path */
156 bottom_block->taken = orig_block->taken;
157 if (bottom_block->taken) {
158 orig_block->taken = NULL;
buzbee862a7602013-04-05 10:58:54 -0700159 bottom_block->taken->predecessors->Delete(orig_block);
160 bottom_block->taken->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800161 }
162
163 /* Handle the fallthrough path */
164 bottom_block->fall_through = orig_block->fall_through;
165 orig_block->fall_through = bottom_block;
buzbee862a7602013-04-05 10:58:54 -0700166 bottom_block->predecessors->Insert(orig_block);
buzbee311ca162013-02-28 15:56:43 -0800167 if (bottom_block->fall_through) {
buzbee862a7602013-04-05 10:58:54 -0700168 bottom_block->fall_through->predecessors->Delete(orig_block);
169 bottom_block->fall_through->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800170 }
171
172 /* Handle the successor list */
173 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
174 bottom_block->successor_block_list = orig_block->successor_block_list;
175 orig_block->successor_block_list.block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -0700176 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800177 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700178 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800179 if (successor_block_info == NULL) break;
180 BasicBlock *bb = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700181 bb->predecessors->Delete(orig_block);
182 bb->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800183 }
184 }
185
186 orig_block->last_mir_insn = insn->prev;
187
188 insn->prev->next = NULL;
189 insn->prev = NULL;
190 /*
191 * Update the immediate predecessor block pointer so that outgoing edges
192 * can be applied to the proper block.
193 */
194 if (immed_pred_block_p) {
195 DCHECK_EQ(*immed_pred_block_p, orig_block);
196 *immed_pred_block_p = bottom_block;
197 }
198 return bottom_block;
199}
200
201/*
202 * Given a code offset, find out the block that starts with it. If the offset
203 * is in the middle of an existing block, split it into two. If immed_pred_block_p
204 * is not non-null and is the block being split, update *immed_pred_block_p to
205 * point to the bottom block so that outgoing edges can be set up properly
206 * (by the caller)
207 * Utilizes a map for fast lookup of the typical cases.
208 */
209BasicBlock* MIRGraph::FindBlock(unsigned int code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700210 BasicBlock** immed_pred_block_p) {
buzbee311ca162013-02-28 15:56:43 -0800211 BasicBlock* bb;
212 unsigned int i;
213 SafeMap<unsigned int, BasicBlock*>::iterator it;
214
215 it = block_map_.find(code_offset);
216 if (it != block_map_.end()) {
217 return it->second;
218 } else if (!create) {
219 return NULL;
220 }
221
222 if (split) {
buzbee862a7602013-04-05 10:58:54 -0700223 for (i = 0; i < block_list_.Size(); i++) {
224 bb = block_list_.Get(i);
buzbee311ca162013-02-28 15:56:43 -0800225 if (bb->block_type != kDalvikByteCode) continue;
226 /* Check if a branch jumps into the middle of an existing block */
227 if ((code_offset > bb->start_offset) && (bb->last_mir_insn != NULL) &&
228 (code_offset <= bb->last_mir_insn->offset)) {
229 BasicBlock *new_bb = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ?
230 immed_pred_block_p : NULL);
231 return new_bb;
232 }
233 }
234 }
235
236 /* Create a new one */
buzbee862a7602013-04-05 10:58:54 -0700237 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
238 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800239 bb->start_offset = code_offset;
240 block_map_.Put(bb->start_offset, bb);
241 return bb;
242}
243
244/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700245void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800246 int tries_size = current_code_item_->tries_size_;
247 int offset;
248
249 if (tries_size == 0) {
250 return;
251 }
252
253 for (int i = 0; i < tries_size; i++) {
254 const DexFile::TryItem* pTry =
255 DexFile::GetTryItems(*current_code_item_, i);
256 int start_offset = pTry->start_addr_;
257 int end_offset = start_offset + pTry->insn_count_;
258 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700259 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800260 }
261 }
262
263 // Iterate over each of the handlers to enqueue the empty Catch blocks
264 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
265 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
266 for (uint32_t idx = 0; idx < handlers_size; idx++) {
267 CatchHandlerIterator iterator(handlers_ptr);
268 for (; iterator.HasNext(); iterator.Next()) {
269 uint32_t address = iterator.GetHandlerAddress();
270 FindBlock(address, false /* split */, true /*create*/,
271 /* immed_pred_block_p */ NULL);
272 }
273 handlers_ptr = iterator.EndDataPointer();
274 }
275}
276
277/* Process instructions with the kBranch flag */
278BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
279 int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700280 const uint16_t* code_end) {
buzbee311ca162013-02-28 15:56:43 -0800281 int target = cur_offset;
282 switch (insn->dalvikInsn.opcode) {
283 case Instruction::GOTO:
284 case Instruction::GOTO_16:
285 case Instruction::GOTO_32:
286 target += insn->dalvikInsn.vA;
287 break;
288 case Instruction::IF_EQ:
289 case Instruction::IF_NE:
290 case Instruction::IF_LT:
291 case Instruction::IF_GE:
292 case Instruction::IF_GT:
293 case Instruction::IF_LE:
294 cur_block->conditional_branch = true;
295 target += insn->dalvikInsn.vC;
296 break;
297 case Instruction::IF_EQZ:
298 case Instruction::IF_NEZ:
299 case Instruction::IF_LTZ:
300 case Instruction::IF_GEZ:
301 case Instruction::IF_GTZ:
302 case Instruction::IF_LEZ:
303 cur_block->conditional_branch = true;
304 target += insn->dalvikInsn.vB;
305 break;
306 default:
307 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
308 }
buzbeecbcfaf32013-08-19 07:37:40 -0700309 if (target <= cur_offset) {
310 insn->backwards_branch = true;
311 }
buzbee311ca162013-02-28 15:56:43 -0800312 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
313 /* immed_pred_block_p */ &cur_block);
314 cur_block->taken = taken_block;
buzbee862a7602013-04-05 10:58:54 -0700315 taken_block->predecessors->Insert(cur_block);
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);
337 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700338 fallthrough_block->predecessors->Insert(cur_block);
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 */
347void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700348 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
391 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
392 LOG(FATAL) << "Successor block list already in use: "
393 << static_cast<int>(cur_block->successor_block_list.block_list_type);
394 }
395 cur_block->successor_block_list.block_list_type =
396 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
397 kPackedSwitch : kSparseSwitch;
buzbee862a7602013-04-05 10:58:54 -0700398 cur_block->successor_block_list.blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700399 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800400
401 for (i = 0; i < size; i++) {
402 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
403 /* create */ true, /* immed_pred_block_p */ &cur_block);
404 SuccessorBlockInfo *successor_block_info =
buzbee862a7602013-04-05 10:58:54 -0700405 static_cast<SuccessorBlockInfo*>(arena_->NewMem(sizeof(SuccessorBlockInfo), false,
406 ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800407 successor_block_info->block = case_block;
408 successor_block_info->key =
409 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
410 first_key + i : keyTable[i];
buzbee862a7602013-04-05 10:58:54 -0700411 cur_block->successor_block_list.blocks->Insert(successor_block_info);
412 case_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800413 }
414
415 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700416 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
417 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800418 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700419 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800420}
421
422/* Process instructions with the kThrow flag */
423BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
424 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);
buzbee311ca162013-02-28 15:56:43 -0800427
428 /* In try block */
429 if (in_try_block) {
430 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
431
432 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
433 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
434 LOG(FATAL) << "Successor block list already in use: "
435 << static_cast<int>(cur_block->successor_block_list.block_list_type);
436 }
437
438 cur_block->successor_block_list.block_list_type = kCatch;
buzbee862a7602013-04-05 10:58:54 -0700439 cur_block->successor_block_list.blocks =
440 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800441
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700442 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800443 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
444 false /* creat */, NULL /* immed_pred_block_p */);
445 catch_block->catch_entry = true;
446 if (kIsDebugBuild) {
447 catches_.insert(catch_block->start_offset);
448 }
449 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
buzbee862a7602013-04-05 10:58:54 -0700450 (arena_->NewMem(sizeof(SuccessorBlockInfo), false, ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800451 successor_block_info->block = catch_block;
452 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee862a7602013-04-05 10:58:54 -0700453 cur_block->successor_block_list.blocks->Insert(successor_block_info);
454 catch_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800455 }
456 } else {
buzbee862a7602013-04-05 10:58:54 -0700457 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800458 cur_block->taken = eh_block;
buzbee862a7602013-04-05 10:58:54 -0700459 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800460 eh_block->start_offset = cur_offset;
buzbee862a7602013-04-05 10:58:54 -0700461 eh_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800462 }
463
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700464 if (insn->dalvikInsn.opcode == Instruction::THROW) {
buzbee311ca162013-02-28 15:56:43 -0800465 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700466 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800467 // Force creation of new block following THROW via side-effect
468 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
469 /* immed_pred_block_p */ NULL);
470 }
471 if (!in_try_block) {
472 // Don't split a THROW that can't rethrow - we're done.
473 return cur_block;
474 }
475 }
476
477 /*
478 * Split the potentially-throwing instruction into two parts.
479 * The first half will be a pseudo-op that captures the exception
480 * edges and terminates the basic block. It always falls through.
481 * Then, create a new basic block that begins with the throwing instruction
482 * (minus exceptions). Note: this new basic block must NOT be entered into
483 * the block_map. If the potentially-throwing instruction is the target of a
484 * future branch, we need to find the check psuedo half. The new
485 * basic block containing the work portion of the instruction should
486 * only be entered via fallthrough from the block containing the
487 * pseudo exception edge MIR. Note also that this new block is
488 * not automatically terminated after the work portion, and may
489 * contain following instructions.
490 */
buzbee862a7602013-04-05 10:58:54 -0700491 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
492 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800493 new_block->start_offset = insn->offset;
494 cur_block->fall_through = new_block;
buzbee862a7602013-04-05 10:58:54 -0700495 new_block->predecessors->Insert(cur_block);
496 MIR* new_insn = static_cast<MIR*>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800497 *new_insn = *insn;
498 insn->dalvikInsn.opcode =
499 static_cast<Instruction::Code>(kMirOpCheck);
500 // Associate the two halves
501 insn->meta.throw_insn = new_insn;
502 new_insn->meta.throw_insn = insn;
503 AppendMIR(new_block, new_insn);
504 return new_block;
505}
506
507/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
508void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
509 InvokeType invoke_type, uint32_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700510 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800511 current_code_item_ = code_item;
512 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
513 current_method_ = m_units_.size();
514 current_offset_ = 0;
515 // TODO: will need to snapshot stack image and use that as the mir context identification.
516 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
517 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
518 const uint16_t* code_ptr = current_code_item_->insns_;
519 const uint16_t* code_end =
520 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
521
522 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbee862a7602013-04-05 10:58:54 -0700523 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800524 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700525 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
526 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800527
528 // If this is the first method, set up default entry and exit blocks.
529 if (current_method_ == 0) {
530 DCHECK(entry_block_ == NULL);
531 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700532 DCHECK_EQ(num_blocks_, 0);
buzbee862a7602013-04-05 10:58:54 -0700533 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
534 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
535 block_list_.Insert(entry_block_);
536 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800537 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
538 cu_->dex_file = &dex_file;
539 cu_->class_def_idx = class_def_idx;
540 cu_->method_idx = method_idx;
541 cu_->access_flags = access_flags;
542 cu_->invoke_type = invoke_type;
543 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
544 cu_->num_ins = current_code_item_->ins_size_;
545 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
546 cu_->num_outs = current_code_item_->outs_size_;
547 cu_->num_dalvik_registers = current_code_item_->registers_size_;
548 cu_->insns = current_code_item_->insns_;
549 cu_->code_item = current_code_item_;
550 } else {
551 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
552 /*
553 * Will need to manage storage for ins & outs, push prevous state and update
554 * insert point.
555 */
556 }
557
558 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700559 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800560 DCHECK_EQ(current_offset_, 0);
561 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700562 block_list_.Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800563 /* Add first block to the fast lookup cache */
564// FIXME: block map needs association with offset/method pair rather than just offset
565 block_map_.Put(cur_block->start_offset, cur_block);
566// FIXME: this needs to insert at the insert point rather than entry block.
567 entry_block_->fall_through = cur_block;
buzbee862a7602013-04-05 10:58:54 -0700568 cur_block->predecessors->Insert(entry_block_);
buzbee311ca162013-02-28 15:56:43 -0800569
570 /* Identify code range in try blocks and set up the empty catch blocks */
571 ProcessTryCatchBlocks();
572
573 /* Set up for simple method detection */
574 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
575 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
576 bool* dead_pattern =
buzbee862a7602013-04-05 10:58:54 -0700577 static_cast<bool*>(arena_->NewMem(sizeof(bool) * num_patterns, true,
578 ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800579 int pattern_pos = 0;
580
581 /* Parse all instructions and put them into containing basic blocks */
582 while (code_ptr < code_end) {
buzbee862a7602013-04-05 10:58:54 -0700583 MIR *insn = static_cast<MIR *>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800584 insn->offset = current_offset_;
585 insn->m_unit_index = current_method_;
586 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
587 insn->width = width;
588 Instruction::Code opcode = insn->dalvikInsn.opcode;
589 if (opcode_count_ != NULL) {
590 opcode_count_[static_cast<int>(opcode)]++;
591 }
592
buzbee311ca162013-02-28 15:56:43 -0800593
594 /* Possible simple method? */
595 if (live_pattern) {
596 live_pattern = false;
buzbee479f83c2013-07-19 10:58:21 -0700597 special_case_ = kNoHandler;
buzbee311ca162013-02-28 15:56:43 -0800598 for (int i = 0; i < num_patterns; i++) {
599 if (!dead_pattern[i]) {
600 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
601 live_pattern = true;
buzbee479f83c2013-07-19 10:58:21 -0700602 special_case_ = special_patterns[i].handler_code;
buzbee311ca162013-02-28 15:56:43 -0800603 } else {
604 dead_pattern[i] = true;
605 }
606 }
607 }
608 pattern_pos++;
609 }
610
buzbee311ca162013-02-28 15:56:43 -0800611 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
612
buzbee1fd33462013-03-25 13:40:45 -0700613 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800614
615 if (df_flags & DF_HAS_DEFS) {
616 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
617 }
618
buzbee27247762013-07-28 12:03:58 -0700619 // Check for inline data block signatures
620 if (opcode == Instruction::NOP) {
621 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
622 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
623 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
624 uint16_t following_raw_instruction = code_ptr[1];
625 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
626 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
627 (following_raw_instruction == Instruction::kArrayDataSignature)) {
628 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
629 }
630 }
631 if (width == 1) {
632 // It is a simple nop - treat normally.
633 AppendMIR(cur_block, insn);
634 } else {
635 DCHECK(cur_block->fall_through == NULL);
636 DCHECK(cur_block->taken == NULL);
637 // Unreachable instruction, mark for no continuation.
638 flags &= ~Instruction::kContinue;
639 }
640 } else {
641 AppendMIR(cur_block, insn);
642 }
643
644 code_ptr += width;
645
buzbee311ca162013-02-28 15:56:43 -0800646 if (flags & Instruction::kBranch) {
647 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
648 width, flags, code_ptr, code_end);
649 } else if (flags & Instruction::kReturn) {
650 cur_block->terminated_by_return = true;
651 cur_block->fall_through = exit_block_;
buzbee862a7602013-04-05 10:58:54 -0700652 exit_block_->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800653 /*
654 * Terminate the current block if there are instructions
655 * afterwards.
656 */
657 if (code_ptr < code_end) {
658 /*
659 * Create a fallthrough block for real instructions
660 * (incl. NOP).
661 */
buzbee27247762013-07-28 12:03:58 -0700662 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
663 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800664 }
665 } else if (flags & Instruction::kThrow) {
666 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
667 code_ptr, code_end);
668 } else if (flags & Instruction::kSwitch) {
669 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
670 }
671 current_offset_ += width;
672 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
673 false, /* immed_pred_block_p */ NULL);
674 if (next_block) {
675 /*
676 * The next instruction could be the target of a previously parsed
677 * forward branch so a block is already created. If the current
678 * instruction is not an unconditional branch, connect them through
679 * the fall-through link.
680 */
681 DCHECK(cur_block->fall_through == NULL ||
682 cur_block->fall_through == next_block ||
683 cur_block->fall_through == exit_block_);
684
685 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
686 cur_block->fall_through = next_block;
buzbee862a7602013-04-05 10:58:54 -0700687 next_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800688 }
689 cur_block = next_block;
690 }
691 }
692 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
693 DumpCFG("/sdcard/1_post_parse_cfg/", true);
694 }
695
696 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700697 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800698 }
699}
700
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700701void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800702 DCHECK(opcode_count_ != NULL);
703 LOG(INFO) << "Opcode Count";
704 for (int i = 0; i < kNumPackedOpcodes; i++) {
705 if (opcode_count_[i] != 0) {
706 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
707 << " " << opcode_count_[i];
708 }
709 }
710}
711
712// TODO: use a configurable base prefix, and adjust callers to supply pass name.
713/* Dump the CFG into a DOT graph */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700714void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks) {
buzbee311ca162013-02-28 15:56:43 -0800715 FILE* file;
716 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
717 ReplaceSpecialChars(fname);
718 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
719 GetEntryBlock()->fall_through->start_offset);
720 file = fopen(fname.c_str(), "w");
721 if (file == NULL) {
722 return;
723 }
724 fprintf(file, "digraph G {\n");
725
726 fprintf(file, " rankdir=TB\n");
727
728 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
729 int idx;
730
731 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700732 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800733 BasicBlock *bb = GetBasicBlock(block_idx);
734 if (bb == NULL) break;
735 if (bb->block_type == kDead) continue;
736 if (bb->block_type == kEntryBlock) {
737 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
738 } else if (bb->block_type == kExitBlock) {
739 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
740 } else if (bb->block_type == kDalvikByteCode) {
741 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
742 bb->start_offset, bb->id);
743 const MIR *mir;
744 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
745 bb->first_mir_insn ? " | " : " ");
746 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
747 int opcode = mir->dalvikInsn.opcode;
748 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700749 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800750 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700751 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800752 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
753 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
754 mir->next ? " | " : " ");
755 }
756 fprintf(file, " }\"];\n\n");
757 } else if (bb->block_type == kExceptionHandling) {
758 char block_name[BLOCK_NAME_LEN];
759
760 GetBlockName(bb, block_name);
761 fprintf(file, " %s [shape=invhouse];\n", block_name);
762 }
763
764 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
765
766 if (bb->taken) {
767 GetBlockName(bb, block_name1);
768 GetBlockName(bb->taken, block_name2);
769 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
770 block_name1, block_name2);
771 }
772 if (bb->fall_through) {
773 GetBlockName(bb, block_name1);
774 GetBlockName(bb->fall_through, block_name2);
775 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
776 }
777
778 if (bb->successor_block_list.block_list_type != kNotUsed) {
779 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
780 bb->start_offset, bb->id,
781 (bb->successor_block_list.block_list_type == kCatch) ?
782 "Mrecord" : "record");
buzbee862a7602013-04-05 10:58:54 -0700783 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_block_list.blocks);
784 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800785
786 int succ_id = 0;
787 while (true) {
788 if (successor_block_info == NULL) break;
789
790 BasicBlock *dest_block = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700791 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800792
793 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
794 succ_id++,
795 successor_block_info->key,
796 dest_block->start_offset,
797 (next_successor_block_info != NULL) ? " | " : " ");
798
799 successor_block_info = next_successor_block_info;
800 }
801 fprintf(file, " }\"];\n\n");
802
803 GetBlockName(bb, block_name1);
804 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
805 block_name1, bb->start_offset, bb->id);
806
807 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
808 bb->successor_block_list.block_list_type == kSparseSwitch) {
buzbee862a7602013-04-05 10:58:54 -0700809 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800810
811 succ_id = 0;
812 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700813 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800814 if (successor_block_info == NULL) break;
815
816 BasicBlock *dest_block = successor_block_info->block;
817
818 GetBlockName(dest_block, block_name2);
819 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
820 bb->id, succ_id++, block_name2);
821 }
822 }
823 }
824 fprintf(file, "\n");
825
826 if (cu_->verbose) {
827 /* Display the dominator tree */
828 GetBlockName(bb, block_name1);
829 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
830 block_name1, block_name1);
831 if (bb->i_dom) {
832 GetBlockName(bb->i_dom, block_name2);
833 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
834 }
835 }
836 }
837 fprintf(file, "}\n");
838 fclose(file);
839}
840
buzbee1fd33462013-03-25 13:40:45 -0700841/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700842void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700843 if (bb->first_mir_insn == NULL) {
844 DCHECK(bb->last_mir_insn == NULL);
845 bb->last_mir_insn = bb->first_mir_insn = mir;
846 mir->prev = mir->next = NULL;
847 } else {
848 bb->last_mir_insn->next = mir;
849 mir->prev = bb->last_mir_insn;
850 mir->next = NULL;
851 bb->last_mir_insn = mir;
852 }
853}
854
855/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700856void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700857 if (bb->first_mir_insn == NULL) {
858 DCHECK(bb->last_mir_insn == NULL);
859 bb->last_mir_insn = bb->first_mir_insn = mir;
860 mir->prev = mir->next = NULL;
861 } else {
862 bb->first_mir_insn->prev = mir;
863 mir->next = bb->first_mir_insn;
864 mir->prev = NULL;
865 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->prev = current_mir;
872 new_mir->next = current_mir->next;
873 current_mir->next = new_mir;
874
875 if (new_mir->next) {
876 /* Is not the last MIR in the block */
877 new_mir->next->prev = new_mir;
878 } else {
879 /* Is the last MIR in the block */
880 bb->last_mir_insn = new_mir;
881 }
882}
883
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700884char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700885 DecodedInstruction insn = mir->dalvikInsn;
886 std::string str;
887 int flags = 0;
888 int opcode = insn.opcode;
889 char* ret;
890 bool nop = false;
891 SSARepresentation* ssa_rep = mir->ssa_rep;
892 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
893 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
894 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
895
896 // Handle special cases.
897 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
898 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
899 str.append(": ");
900 // Recover the original Dex instruction
901 insn = mir->meta.throw_insn->dalvikInsn;
902 ssa_rep = mir->meta.throw_insn->ssa_rep;
903 defs = ssa_rep->num_defs;
904 uses = ssa_rep->num_uses;
905 opcode = insn.opcode;
906 } else if (opcode == kMirOpNop) {
907 str.append("[");
908 insn.opcode = mir->meta.original_opcode;
909 opcode = mir->meta.original_opcode;
910 nop = true;
911 }
912
913 if (opcode >= kMirOpFirst) {
914 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
915 } else {
916 dalvik_format = Instruction::FormatOf(insn.opcode);
917 flags = Instruction::FlagsOf(insn.opcode);
918 str.append(Instruction::Name(insn.opcode));
919 }
920
921 if (opcode == kMirOpPhi) {
922 int* incoming = reinterpret_cast<int*>(insn.vB);
923 str.append(StringPrintf(" %s = (%s",
924 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
925 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700926 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700927 int i;
928 for (i = 1; i < uses; i++) {
929 str.append(StringPrintf(", %s:%d",
930 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
931 incoming[i]));
932 }
933 str.append(")");
934 } else if ((flags & Instruction::kBranch) != 0) {
935 // For branches, decode the instructions to print out the branch targets.
936 int offset = 0;
937 switch (dalvik_format) {
938 case Instruction::k21t:
939 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
940 offset = insn.vB;
941 break;
942 case Instruction::k22t:
943 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
944 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
945 offset = insn.vC;
946 break;
947 case Instruction::k10t:
948 case Instruction::k20t:
949 case Instruction::k30t:
950 offset = insn.vA;
951 break;
952 default:
953 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
954 }
955 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
956 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
957 } else {
958 // For invokes-style formats, treat wide regs as a pair of singles
959 bool show_singles = ((dalvik_format == Instruction::k35c) ||
960 (dalvik_format == Instruction::k3rc));
961 if (defs != 0) {
962 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
963 if (uses != 0) {
964 str.append(", ");
965 }
966 }
967 for (int i = 0; i < uses; i++) {
968 str.append(
969 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
970 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
971 // For the listing, skip the high sreg.
972 i++;
973 }
974 if (i != (uses -1)) {
975 str.append(",");
976 }
977 }
978 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700979 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -0700980 case Instruction::k21s:
981 case Instruction::k31i:
982 case Instruction::k21h:
983 str.append(StringPrintf(", #%d", insn.vB));
984 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700985 case Instruction::k51l: // Add one wide immediate
buzbee1fd33462013-03-25 13:40:45 -0700986 str.append(StringPrintf(", #%lld", insn.vB_wide));
987 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700988 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -0700989 case Instruction::k31c:
990 str.append(StringPrintf(", index #%d", insn.vB));
991 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700992 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -0700993 str.append(StringPrintf(", index #%d", insn.vC));
994 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700995 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -0700996 case Instruction::k22b:
997 str.append(StringPrintf(", #%d", insn.vC));
998 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700999 default: {
1000 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001001 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001002 }
buzbee1fd33462013-03-25 13:40:45 -07001003 }
1004 if (nop) {
1005 str.append("]--optimized away");
1006 }
1007 int length = str.length() + 1;
buzbee862a7602013-04-05 10:58:54 -07001008 ret = static_cast<char*>(arena_->NewMem(length, false, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001009 strncpy(ret, str.c_str(), length);
1010 return ret;
1011}
1012
1013/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001014void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001015 static const struct { const char before; const char after; } match[] = {
1016 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1017 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1018 };
buzbee1fd33462013-03-25 13:40:45 -07001019 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1020 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1021 }
1022}
1023
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001024std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001025 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1026 // the arena. We should be smarter and just place straight into the arena, or compute the
1027 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001028 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1029}
1030
1031// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001032std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001033 if (reg_location_ == NULL) {
1034 // Pre-SSA - just use the standard name
1035 return GetSSAName(ssa_reg);
1036 }
1037 if (IsConst(reg_location_[ssa_reg])) {
1038 if (!singles_only && reg_location_[ssa_reg].wide) {
1039 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1040 ConstantValueWide(reg_location_[ssa_reg]));
1041 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001042 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001043 ConstantValue(reg_location_[ssa_reg]));
1044 }
1045 } else {
1046 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1047 }
1048}
1049
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001050void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001051 switch (bb->block_type) {
1052 case kEntryBlock:
1053 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1054 break;
1055 case kExitBlock:
1056 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1057 break;
1058 case kDalvikByteCode:
1059 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1060 break;
1061 case kExceptionHandling:
1062 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1063 bb->id);
1064 break;
1065 default:
1066 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1067 break;
1068 }
1069}
1070
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001071const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee1fd33462013-03-25 13:40:45 -07001072 // FIXME: use current code unit for inline support.
1073 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1074 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1075}
1076
1077/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001078void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001079 BasicBlock* bb;
1080 const char* block_type_names[] = {
1081 "Entry Block",
1082 "Code Block",
1083 "Exit Block",
1084 "Exception Handling",
1085 "Catch Block"
1086 };
1087
1088 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1089 LOG(INFO) << cu_->insns << " insns";
1090 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001091 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001092
1093 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001094 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001095 if (bb == NULL) break;
1096 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1097 bb->id,
1098 block_type_names[bb->block_type],
1099 bb->start_offset,
1100 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1101 bb->last_mir_insn ? "" : " empty");
1102 if (bb->taken) {
1103 LOG(INFO) << " Taken branch: block " << bb->taken->id
1104 << "(0x" << std::hex << bb->taken->start_offset << ")";
1105 }
1106 if (bb->fall_through) {
1107 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1108 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1109 }
1110 }
1111}
1112
1113/*
1114 * Build an array of location records for the incoming arguments.
1115 * Note: one location record per word of arguments, with dummy
1116 * high-word loc for wide arguments. Also pull up any following
1117 * MOVE_RESULT and incorporate it into the invoke.
1118 */
1119CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001120 bool is_range) {
buzbee862a7602013-04-05 10:58:54 -07001121 CallInfo* info = static_cast<CallInfo*>(arena_->NewMem(sizeof(CallInfo), true,
1122 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001123 MIR* move_result_mir = FindMoveResult(bb, mir);
1124 if (move_result_mir == NULL) {
1125 info->result.location = kLocInvalid;
1126 } else {
1127 info->result = GetRawDest(move_result_mir);
1128 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1129 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1130 }
1131 info->num_arg_words = mir->ssa_rep->num_uses;
1132 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
buzbee862a7602013-04-05 10:58:54 -07001133 (arena_->NewMem(sizeof(RegLocation) * info->num_arg_words, false,
1134 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001135 for (int i = 0; i < info->num_arg_words; i++) {
1136 info->args[i] = GetRawSrc(mir, i);
1137 }
1138 info->opt_flags = mir->optimization_flags;
1139 info->type = type;
1140 info->is_range = is_range;
1141 info->index = mir->dalvikInsn.vB;
1142 info->offset = mir->offset;
1143 return info;
1144}
1145
buzbee862a7602013-04-05 10:58:54 -07001146// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001147BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
buzbee862a7602013-04-05 10:58:54 -07001148 BasicBlock* bb = static_cast<BasicBlock*>(arena_->NewMem(sizeof(BasicBlock), true,
1149 ArenaAllocator::kAllocBB));
1150 bb->block_type = block_type;
1151 bb->id = block_id;
1152 // TUNING: better estimate of the exit block predecessors?
Brian Carlstromdf629502013-07-17 22:39:56 -07001153 bb->predecessors = new (arena_) GrowableArray<BasicBlock*>(arena_,
1154 (block_type == kExitBlock) ? 2048 : 2,
1155 kGrowableArrayPredecessors);
buzbee862a7602013-04-05 10:58:54 -07001156 bb->successor_block_list.block_list_type = kNotUsed;
1157 block_id_map_.Put(block_id, block_id);
1158 return bb;
1159}
buzbee1fd33462013-03-25 13:40:45 -07001160
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001161} // namespace art