blob: 9af14a47a8b9b9d79cd26de0c46b55c7cb4c0c03 [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 -0800119bool MIRGraph::ContentIsInsn(const uint16_t* code_ptr) {
120 uint16_t instr = *code_ptr;
121 Instruction::Code opcode = static_cast<Instruction::Code>(instr & 0xff);
122 /*
123 * Since the low 8-bit in metadata may look like NOP, we need to check
124 * both the low and whole sub-word to determine whether it is code or data.
125 */
126 return (opcode != Instruction::NOP || instr == 0);
127}
128
129/*
130 * Parse an instruction, return the length of the instruction
131 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700132int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -0800133 // Don't parse instruction data
134 if (!ContentIsInsn(code_ptr)) {
135 return 0;
136 }
137
138 const Instruction* instruction = Instruction::At(code_ptr);
139 *decoded_instruction = DecodedInstruction(instruction);
140
141 return instruction->SizeInCodeUnits();
142}
143
144
145/* Split an existing block from the specified code offset into two */
146BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700147 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee311ca162013-02-28 15:56:43 -0800148 MIR* insn = orig_block->first_mir_insn;
149 while (insn) {
150 if (insn->offset == code_offset) break;
151 insn = insn->next;
152 }
153 if (insn == NULL) {
154 LOG(FATAL) << "Break split failed";
155 }
buzbee862a7602013-04-05 10:58:54 -0700156 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
157 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800158
159 bottom_block->start_offset = code_offset;
160 bottom_block->first_mir_insn = insn;
161 bottom_block->last_mir_insn = orig_block->last_mir_insn;
162
163 /* If this block was terminated by a return, the flag needs to go with the bottom block */
164 bottom_block->terminated_by_return = orig_block->terminated_by_return;
165 orig_block->terminated_by_return = false;
166
167 /* Add it to the quick lookup cache */
168 block_map_.Put(bottom_block->start_offset, bottom_block);
169
170 /* Handle the taken path */
171 bottom_block->taken = orig_block->taken;
172 if (bottom_block->taken) {
173 orig_block->taken = NULL;
buzbee862a7602013-04-05 10:58:54 -0700174 bottom_block->taken->predecessors->Delete(orig_block);
175 bottom_block->taken->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800176 }
177
178 /* Handle the fallthrough path */
179 bottom_block->fall_through = orig_block->fall_through;
180 orig_block->fall_through = bottom_block;
buzbee862a7602013-04-05 10:58:54 -0700181 bottom_block->predecessors->Insert(orig_block);
buzbee311ca162013-02-28 15:56:43 -0800182 if (bottom_block->fall_through) {
buzbee862a7602013-04-05 10:58:54 -0700183 bottom_block->fall_through->predecessors->Delete(orig_block);
184 bottom_block->fall_through->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800185 }
186
187 /* Handle the successor list */
188 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
189 bottom_block->successor_block_list = orig_block->successor_block_list;
190 orig_block->successor_block_list.block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -0700191 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800192 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700193 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800194 if (successor_block_info == NULL) break;
195 BasicBlock *bb = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700196 bb->predecessors->Delete(orig_block);
197 bb->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800198 }
199 }
200
201 orig_block->last_mir_insn = insn->prev;
202
203 insn->prev->next = NULL;
204 insn->prev = NULL;
205 /*
206 * Update the immediate predecessor block pointer so that outgoing edges
207 * can be applied to the proper block.
208 */
209 if (immed_pred_block_p) {
210 DCHECK_EQ(*immed_pred_block_p, orig_block);
211 *immed_pred_block_p = bottom_block;
212 }
213 return bottom_block;
214}
215
216/*
217 * Given a code offset, find out the block that starts with it. If the offset
218 * is in the middle of an existing block, split it into two. If immed_pred_block_p
219 * is not non-null and is the block being split, update *immed_pred_block_p to
220 * point to the bottom block so that outgoing edges can be set up properly
221 * (by the caller)
222 * Utilizes a map for fast lookup of the typical cases.
223 */
224BasicBlock* MIRGraph::FindBlock(unsigned int code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700225 BasicBlock** immed_pred_block_p) {
buzbee311ca162013-02-28 15:56:43 -0800226 BasicBlock* bb;
227 unsigned int i;
228 SafeMap<unsigned int, BasicBlock*>::iterator it;
229
230 it = block_map_.find(code_offset);
231 if (it != block_map_.end()) {
232 return it->second;
233 } else if (!create) {
234 return NULL;
235 }
236
237 if (split) {
buzbee862a7602013-04-05 10:58:54 -0700238 for (i = 0; i < block_list_.Size(); i++) {
239 bb = block_list_.Get(i);
buzbee311ca162013-02-28 15:56:43 -0800240 if (bb->block_type != kDalvikByteCode) continue;
241 /* Check if a branch jumps into the middle of an existing block */
242 if ((code_offset > bb->start_offset) && (bb->last_mir_insn != NULL) &&
243 (code_offset <= bb->last_mir_insn->offset)) {
244 BasicBlock *new_bb = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ?
245 immed_pred_block_p : NULL);
246 return new_bb;
247 }
248 }
249 }
250
251 /* Create a new one */
buzbee862a7602013-04-05 10:58:54 -0700252 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
253 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800254 bb->start_offset = code_offset;
255 block_map_.Put(bb->start_offset, bb);
256 return bb;
257}
258
259/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700260void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800261 int tries_size = current_code_item_->tries_size_;
262 int offset;
263
264 if (tries_size == 0) {
265 return;
266 }
267
268 for (int i = 0; i < tries_size; i++) {
269 const DexFile::TryItem* pTry =
270 DexFile::GetTryItems(*current_code_item_, i);
271 int start_offset = pTry->start_addr_;
272 int end_offset = start_offset + pTry->insn_count_;
273 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700274 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800275 }
276 }
277
278 // Iterate over each of the handlers to enqueue the empty Catch blocks
279 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
280 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
281 for (uint32_t idx = 0; idx < handlers_size; idx++) {
282 CatchHandlerIterator iterator(handlers_ptr);
283 for (; iterator.HasNext(); iterator.Next()) {
284 uint32_t address = iterator.GetHandlerAddress();
285 FindBlock(address, false /* split */, true /*create*/,
286 /* immed_pred_block_p */ NULL);
287 }
288 handlers_ptr = iterator.EndDataPointer();
289 }
290}
291
292/* Process instructions with the kBranch flag */
293BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
294 int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700295 const uint16_t* code_end) {
buzbee311ca162013-02-28 15:56:43 -0800296 int target = cur_offset;
297 switch (insn->dalvikInsn.opcode) {
298 case Instruction::GOTO:
299 case Instruction::GOTO_16:
300 case Instruction::GOTO_32:
301 target += insn->dalvikInsn.vA;
302 break;
303 case Instruction::IF_EQ:
304 case Instruction::IF_NE:
305 case Instruction::IF_LT:
306 case Instruction::IF_GE:
307 case Instruction::IF_GT:
308 case Instruction::IF_LE:
309 cur_block->conditional_branch = true;
310 target += insn->dalvikInsn.vC;
311 break;
312 case Instruction::IF_EQZ:
313 case Instruction::IF_NEZ:
314 case Instruction::IF_LTZ:
315 case Instruction::IF_GEZ:
316 case Instruction::IF_GTZ:
317 case Instruction::IF_LEZ:
318 cur_block->conditional_branch = true;
319 target += insn->dalvikInsn.vB;
320 break;
321 default:
322 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
323 }
324 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
325 /* immed_pred_block_p */ &cur_block);
326 cur_block->taken = taken_block;
buzbee862a7602013-04-05 10:58:54 -0700327 taken_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800328
329 /* Always terminate the current block for conditional branches */
330 if (flags & Instruction::kContinue) {
331 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
332 /*
333 * If the method is processed
334 * in sequential order from the
335 * beginning, we don't need to
336 * specify split for continue
337 * blocks. However, this
338 * routine can be called by
339 * compileLoop, which starts
340 * parsing the method from an
341 * arbitrary address in the
342 * method body.
343 */
344 true,
345 /* create */
346 true,
347 /* immed_pred_block_p */
348 &cur_block);
349 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700350 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800351 } else if (code_ptr < code_end) {
352 /* Create a fallthrough block for real instructions (incl. NOP) */
353 if (ContentIsInsn(code_ptr)) {
354 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
355 /* immed_pred_block_p */ NULL);
356 }
357 }
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 =
buzbee862a7602013-04-05 10:58:54 -0700420 static_cast<SuccessorBlockInfo*>(arena_->NewMem(sizeof(SuccessorBlockInfo), false,
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*>
buzbee862a7602013-04-05 10:58:54 -0700465 (arena_->NewMem(sizeof(SuccessorBlockInfo), false, 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;
481 if ((code_ptr < code_end) && ContentIsInsn(code_ptr)) {
482 // 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.
505 */
buzbee862a7602013-04-05 10:58:54 -0700506 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
507 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800508 new_block->start_offset = insn->offset;
509 cur_block->fall_through = new_block;
buzbee862a7602013-04-05 10:58:54 -0700510 new_block->predecessors->Insert(cur_block);
511 MIR* new_insn = static_cast<MIR*>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800512 *new_insn = *insn;
513 insn->dalvikInsn.opcode =
514 static_cast<Instruction::Code>(kMirOpCheck);
515 // Associate the two halves
516 insn->meta.throw_insn = new_insn;
517 new_insn->meta.throw_insn = insn;
518 AppendMIR(new_block, new_insn);
519 return new_block;
520}
521
522/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
523void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
524 InvokeType invoke_type, uint32_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700525 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800526 current_code_item_ = code_item;
527 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
528 current_method_ = m_units_.size();
529 current_offset_ = 0;
530 // TODO: will need to snapshot stack image and use that as the mir context identification.
531 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
532 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
533 const uint16_t* code_ptr = current_code_item_->insns_;
534 const uint16_t* code_end =
535 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
536
537 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbee862a7602013-04-05 10:58:54 -0700538 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800539 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700540 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
541 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800542
543 // If this is the first method, set up default entry and exit blocks.
544 if (current_method_ == 0) {
545 DCHECK(entry_block_ == NULL);
546 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700547 DCHECK_EQ(num_blocks_, 0);
buzbee862a7602013-04-05 10:58:54 -0700548 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
549 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
550 block_list_.Insert(entry_block_);
551 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800552 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
553 cu_->dex_file = &dex_file;
554 cu_->class_def_idx = class_def_idx;
555 cu_->method_idx = method_idx;
556 cu_->access_flags = access_flags;
557 cu_->invoke_type = invoke_type;
558 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
559 cu_->num_ins = current_code_item_->ins_size_;
560 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
561 cu_->num_outs = current_code_item_->outs_size_;
562 cu_->num_dalvik_registers = current_code_item_->registers_size_;
563 cu_->insns = current_code_item_->insns_;
564 cu_->code_item = current_code_item_;
565 } else {
566 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
567 /*
568 * Will need to manage storage for ins & outs, push prevous state and update
569 * insert point.
570 */
571 }
572
573 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700574 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800575 DCHECK_EQ(current_offset_, 0);
576 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700577 block_list_.Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800578 /* Add first block to the fast lookup cache */
579// FIXME: block map needs association with offset/method pair rather than just offset
580 block_map_.Put(cur_block->start_offset, cur_block);
581// FIXME: this needs to insert at the insert point rather than entry block.
582 entry_block_->fall_through = cur_block;
buzbee862a7602013-04-05 10:58:54 -0700583 cur_block->predecessors->Insert(entry_block_);
buzbee311ca162013-02-28 15:56:43 -0800584
585 /* Identify code range in try blocks and set up the empty catch blocks */
586 ProcessTryCatchBlocks();
587
588 /* Set up for simple method detection */
589 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
590 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
591 bool* dead_pattern =
buzbee862a7602013-04-05 10:58:54 -0700592 static_cast<bool*>(arena_->NewMem(sizeof(bool) * num_patterns, true,
593 ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800594 int pattern_pos = 0;
595
596 /* Parse all instructions and put them into containing basic blocks */
597 while (code_ptr < code_end) {
buzbee862a7602013-04-05 10:58:54 -0700598 MIR *insn = static_cast<MIR *>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800599 insn->offset = current_offset_;
600 insn->m_unit_index = current_method_;
601 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
602 insn->width = width;
603 Instruction::Code opcode = insn->dalvikInsn.opcode;
604 if (opcode_count_ != NULL) {
605 opcode_count_[static_cast<int>(opcode)]++;
606 }
607
buzbee311ca162013-02-28 15:56:43 -0800608
609 /* Possible simple method? */
610 if (live_pattern) {
611 live_pattern = false;
buzbee479f83c2013-07-19 10:58:21 -0700612 special_case_ = kNoHandler;
buzbee311ca162013-02-28 15:56:43 -0800613 for (int i = 0; i < num_patterns; i++) {
614 if (!dead_pattern[i]) {
615 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
616 live_pattern = true;
buzbee479f83c2013-07-19 10:58:21 -0700617 special_case_ = special_patterns[i].handler_code;
buzbee311ca162013-02-28 15:56:43 -0800618 } else {
619 dead_pattern[i] = true;
620 }
621 }
622 }
623 pattern_pos++;
624 }
625
buzbee311ca162013-02-28 15:56:43 -0800626 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
627
buzbee1fd33462013-03-25 13:40:45 -0700628 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800629
630 if (df_flags & DF_HAS_DEFS) {
631 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
632 }
633
buzbee728328a2013-07-26 16:26:08 -0700634 // Check for inline data block signatures
635 if (opcode == Instruction::NOP) {
636 const uint16_t* tmp_code_ptr = code_ptr;
637 int tmp_width = 0;
638 uint16_t raw_instruction = *tmp_code_ptr;
639 bool embedded_data_block = true;
640 if (raw_instruction == 0x0000) {
641 // Could be an aligning nop - see if an embedded data block follows.
642 tmp_code_ptr++;
643 tmp_width++;
644 raw_instruction = *tmp_code_ptr;
645 }
646 if (raw_instruction == Instruction::kSparseSwitchSignature) {
647 tmp_width += (tmp_code_ptr[1] * 4) + 2;
648 } else if (raw_instruction == Instruction::kPackedSwitchSignature) {
649 tmp_width += (tmp_code_ptr[1] * 2) + 4;
650 } else if (raw_instruction == Instruction::kArrayDataSignature) {
651 int element_width = tmp_code_ptr[1];
652 int num_elements = tmp_code_ptr[2] + (tmp_code_ptr[3] << 16);
653 tmp_width += (((num_elements * element_width) + 1) / 2) + 4;
654 } else {
655 // Just a normal nop - process as usual.
656 embedded_data_block = false;
657 AppendMIR(cur_block, insn);
658 }
659 if (embedded_data_block) {
660 width = tmp_width;
661 DCHECK(cur_block->fall_through == NULL);
662 DCHECK(cur_block->taken == NULL);
663 // No fallthrough for this block
664 flags = 0;
665 df_flags = 0;
666 // If there's more code following, make sure there's a basic block to attach it to.
667 if ((code_ptr + width) < code_end) {
668 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
669 /* immed_pred_block_p */ NULL);
670 }
671 }
672 } else {
673 AppendMIR(cur_block, insn);
674 }
675
676 code_ptr += width;
677
buzbee311ca162013-02-28 15:56:43 -0800678 if (flags & Instruction::kBranch) {
679 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
680 width, flags, code_ptr, code_end);
681 } else if (flags & Instruction::kReturn) {
682 cur_block->terminated_by_return = true;
683 cur_block->fall_through = exit_block_;
buzbee862a7602013-04-05 10:58:54 -0700684 exit_block_->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800685 /*
686 * Terminate the current block if there are instructions
687 * afterwards.
688 */
689 if (code_ptr < code_end) {
690 /*
691 * Create a fallthrough block for real instructions
692 * (incl. NOP).
693 */
694 if (ContentIsInsn(code_ptr)) {
695 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
696 /* immed_pred_block_p */ NULL);
697 }
698 }
699 } else if (flags & Instruction::kThrow) {
700 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
701 code_ptr, code_end);
702 } else if (flags & Instruction::kSwitch) {
703 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
704 }
705 current_offset_ += width;
706 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
707 false, /* immed_pred_block_p */ NULL);
708 if (next_block) {
709 /*
710 * The next instruction could be the target of a previously parsed
711 * forward branch so a block is already created. If the current
712 * instruction is not an unconditional branch, connect them through
713 * the fall-through link.
714 */
715 DCHECK(cur_block->fall_through == NULL ||
716 cur_block->fall_through == next_block ||
717 cur_block->fall_through == exit_block_);
718
719 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
720 cur_block->fall_through = next_block;
buzbee862a7602013-04-05 10:58:54 -0700721 next_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800722 }
723 cur_block = next_block;
724 }
725 }
726 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
727 DumpCFG("/sdcard/1_post_parse_cfg/", true);
728 }
729
730 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700731 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800732 }
733}
734
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700735void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800736 DCHECK(opcode_count_ != NULL);
737 LOG(INFO) << "Opcode Count";
738 for (int i = 0; i < kNumPackedOpcodes; i++) {
739 if (opcode_count_[i] != 0) {
740 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
741 << " " << opcode_count_[i];
742 }
743 }
744}
745
746// TODO: use a configurable base prefix, and adjust callers to supply pass name.
747/* Dump the CFG into a DOT graph */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700748void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks) {
buzbee311ca162013-02-28 15:56:43 -0800749 FILE* file;
750 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
751 ReplaceSpecialChars(fname);
752 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
753 GetEntryBlock()->fall_through->start_offset);
754 file = fopen(fname.c_str(), "w");
755 if (file == NULL) {
756 return;
757 }
758 fprintf(file, "digraph G {\n");
759
760 fprintf(file, " rankdir=TB\n");
761
762 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
763 int idx;
764
765 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700766 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800767 BasicBlock *bb = GetBasicBlock(block_idx);
768 if (bb == NULL) break;
769 if (bb->block_type == kDead) continue;
770 if (bb->block_type == kEntryBlock) {
771 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
772 } else if (bb->block_type == kExitBlock) {
773 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
774 } else if (bb->block_type == kDalvikByteCode) {
775 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
776 bb->start_offset, bb->id);
777 const MIR *mir;
778 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
779 bb->first_mir_insn ? " | " : " ");
780 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
781 int opcode = mir->dalvikInsn.opcode;
782 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700783 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800784 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700785 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800786 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
787 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
788 mir->next ? " | " : " ");
789 }
790 fprintf(file, " }\"];\n\n");
791 } else if (bb->block_type == kExceptionHandling) {
792 char block_name[BLOCK_NAME_LEN];
793
794 GetBlockName(bb, block_name);
795 fprintf(file, " %s [shape=invhouse];\n", block_name);
796 }
797
798 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
799
800 if (bb->taken) {
801 GetBlockName(bb, block_name1);
802 GetBlockName(bb->taken, block_name2);
803 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
804 block_name1, block_name2);
805 }
806 if (bb->fall_through) {
807 GetBlockName(bb, block_name1);
808 GetBlockName(bb->fall_through, block_name2);
809 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
810 }
811
812 if (bb->successor_block_list.block_list_type != kNotUsed) {
813 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
814 bb->start_offset, bb->id,
815 (bb->successor_block_list.block_list_type == kCatch) ?
816 "Mrecord" : "record");
buzbee862a7602013-04-05 10:58:54 -0700817 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_block_list.blocks);
818 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800819
820 int succ_id = 0;
821 while (true) {
822 if (successor_block_info == NULL) break;
823
824 BasicBlock *dest_block = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700825 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800826
827 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
828 succ_id++,
829 successor_block_info->key,
830 dest_block->start_offset,
831 (next_successor_block_info != NULL) ? " | " : " ");
832
833 successor_block_info = next_successor_block_info;
834 }
835 fprintf(file, " }\"];\n\n");
836
837 GetBlockName(bb, block_name1);
838 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
839 block_name1, bb->start_offset, bb->id);
840
841 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
842 bb->successor_block_list.block_list_type == kSparseSwitch) {
buzbee862a7602013-04-05 10:58:54 -0700843 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800844
845 succ_id = 0;
846 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700847 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800848 if (successor_block_info == NULL) break;
849
850 BasicBlock *dest_block = successor_block_info->block;
851
852 GetBlockName(dest_block, block_name2);
853 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
854 bb->id, succ_id++, block_name2);
855 }
856 }
857 }
858 fprintf(file, "\n");
859
860 if (cu_->verbose) {
861 /* Display the dominator tree */
862 GetBlockName(bb, block_name1);
863 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
864 block_name1, block_name1);
865 if (bb->i_dom) {
866 GetBlockName(bb->i_dom, block_name2);
867 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
868 }
869 }
870 }
871 fprintf(file, "}\n");
872 fclose(file);
873}
874
buzbee1fd33462013-03-25 13:40:45 -0700875/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700876void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700877 if (bb->first_mir_insn == NULL) {
878 DCHECK(bb->last_mir_insn == NULL);
879 bb->last_mir_insn = bb->first_mir_insn = mir;
880 mir->prev = mir->next = NULL;
881 } else {
882 bb->last_mir_insn->next = mir;
883 mir->prev = bb->last_mir_insn;
884 mir->next = NULL;
885 bb->last_mir_insn = mir;
886 }
887}
888
889/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700890void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700891 if (bb->first_mir_insn == NULL) {
892 DCHECK(bb->last_mir_insn == NULL);
893 bb->last_mir_insn = bb->first_mir_insn = mir;
894 mir->prev = mir->next = NULL;
895 } else {
896 bb->first_mir_insn->prev = mir;
897 mir->next = bb->first_mir_insn;
898 mir->prev = NULL;
899 bb->first_mir_insn = mir;
900 }
901}
902
903/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700904void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700905 new_mir->prev = current_mir;
906 new_mir->next = current_mir->next;
907 current_mir->next = new_mir;
908
909 if (new_mir->next) {
910 /* Is not the last MIR in the block */
911 new_mir->next->prev = new_mir;
912 } else {
913 /* Is the last MIR in the block */
914 bb->last_mir_insn = new_mir;
915 }
916}
917
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700918char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700919 DecodedInstruction insn = mir->dalvikInsn;
920 std::string str;
921 int flags = 0;
922 int opcode = insn.opcode;
923 char* ret;
924 bool nop = false;
925 SSARepresentation* ssa_rep = mir->ssa_rep;
926 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
927 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
928 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
929
930 // Handle special cases.
931 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
932 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
933 str.append(": ");
934 // Recover the original Dex instruction
935 insn = mir->meta.throw_insn->dalvikInsn;
936 ssa_rep = mir->meta.throw_insn->ssa_rep;
937 defs = ssa_rep->num_defs;
938 uses = ssa_rep->num_uses;
939 opcode = insn.opcode;
940 } else if (opcode == kMirOpNop) {
941 str.append("[");
942 insn.opcode = mir->meta.original_opcode;
943 opcode = mir->meta.original_opcode;
944 nop = true;
945 }
946
947 if (opcode >= kMirOpFirst) {
948 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
949 } else {
950 dalvik_format = Instruction::FormatOf(insn.opcode);
951 flags = Instruction::FlagsOf(insn.opcode);
952 str.append(Instruction::Name(insn.opcode));
953 }
954
955 if (opcode == kMirOpPhi) {
956 int* incoming = reinterpret_cast<int*>(insn.vB);
957 str.append(StringPrintf(" %s = (%s",
958 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
959 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700960 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700961 int i;
962 for (i = 1; i < uses; i++) {
963 str.append(StringPrintf(", %s:%d",
964 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
965 incoming[i]));
966 }
967 str.append(")");
968 } else if ((flags & Instruction::kBranch) != 0) {
969 // For branches, decode the instructions to print out the branch targets.
970 int offset = 0;
971 switch (dalvik_format) {
972 case Instruction::k21t:
973 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
974 offset = insn.vB;
975 break;
976 case Instruction::k22t:
977 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
978 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
979 offset = insn.vC;
980 break;
981 case Instruction::k10t:
982 case Instruction::k20t:
983 case Instruction::k30t:
984 offset = insn.vA;
985 break;
986 default:
987 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
988 }
989 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
990 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
991 } else {
992 // For invokes-style formats, treat wide regs as a pair of singles
993 bool show_singles = ((dalvik_format == Instruction::k35c) ||
994 (dalvik_format == Instruction::k3rc));
995 if (defs != 0) {
996 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
997 if (uses != 0) {
998 str.append(", ");
999 }
1000 }
1001 for (int i = 0; i < uses; i++) {
1002 str.append(
1003 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1004 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1005 // For the listing, skip the high sreg.
1006 i++;
1007 }
1008 if (i != (uses -1)) {
1009 str.append(",");
1010 }
1011 }
1012 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001013 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -07001014 case Instruction::k21s:
1015 case Instruction::k31i:
1016 case Instruction::k21h:
1017 str.append(StringPrintf(", #%d", insn.vB));
1018 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001019 case Instruction::k51l: // Add one wide immediate
buzbee1fd33462013-03-25 13:40:45 -07001020 str.append(StringPrintf(", #%lld", insn.vB_wide));
1021 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001022 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001023 case Instruction::k31c:
1024 str.append(StringPrintf(", index #%d", insn.vB));
1025 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001026 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001027 str.append(StringPrintf(", index #%d", insn.vC));
1028 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001029 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001030 case Instruction::k22b:
1031 str.append(StringPrintf(", #%d", insn.vC));
1032 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001033 default: {
1034 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001035 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001036 }
buzbee1fd33462013-03-25 13:40:45 -07001037 }
1038 if (nop) {
1039 str.append("]--optimized away");
1040 }
1041 int length = str.length() + 1;
buzbee862a7602013-04-05 10:58:54 -07001042 ret = static_cast<char*>(arena_->NewMem(length, false, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001043 strncpy(ret, str.c_str(), length);
1044 return ret;
1045}
1046
1047/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001048void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001049 static const struct { const char before; const char after; } match[] = {
1050 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1051 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1052 };
buzbee1fd33462013-03-25 13:40:45 -07001053 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1054 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1055 }
1056}
1057
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001058std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001059 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1060 // the arena. We should be smarter and just place straight into the arena, or compute the
1061 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001062 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1063}
1064
1065// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001066std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001067 if (reg_location_ == NULL) {
1068 // Pre-SSA - just use the standard name
1069 return GetSSAName(ssa_reg);
1070 }
1071 if (IsConst(reg_location_[ssa_reg])) {
1072 if (!singles_only && reg_location_[ssa_reg].wide) {
1073 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1074 ConstantValueWide(reg_location_[ssa_reg]));
1075 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001076 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001077 ConstantValue(reg_location_[ssa_reg]));
1078 }
1079 } else {
1080 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1081 }
1082}
1083
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001084void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001085 switch (bb->block_type) {
1086 case kEntryBlock:
1087 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1088 break;
1089 case kExitBlock:
1090 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1091 break;
1092 case kDalvikByteCode:
1093 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1094 break;
1095 case kExceptionHandling:
1096 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1097 bb->id);
1098 break;
1099 default:
1100 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1101 break;
1102 }
1103}
1104
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001105const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee1fd33462013-03-25 13:40:45 -07001106 // FIXME: use current code unit for inline support.
1107 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1108 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1109}
1110
1111/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001112void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001113 BasicBlock* bb;
1114 const char* block_type_names[] = {
1115 "Entry Block",
1116 "Code Block",
1117 "Exit Block",
1118 "Exception Handling",
1119 "Catch Block"
1120 };
1121
1122 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1123 LOG(INFO) << cu_->insns << " insns";
1124 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001125 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001126
1127 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001128 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001129 if (bb == NULL) break;
1130 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1131 bb->id,
1132 block_type_names[bb->block_type],
1133 bb->start_offset,
1134 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1135 bb->last_mir_insn ? "" : " empty");
1136 if (bb->taken) {
1137 LOG(INFO) << " Taken branch: block " << bb->taken->id
1138 << "(0x" << std::hex << bb->taken->start_offset << ")";
1139 }
1140 if (bb->fall_through) {
1141 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1142 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1143 }
1144 }
1145}
1146
1147/*
1148 * Build an array of location records for the incoming arguments.
1149 * Note: one location record per word of arguments, with dummy
1150 * high-word loc for wide arguments. Also pull up any following
1151 * MOVE_RESULT and incorporate it into the invoke.
1152 */
1153CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001154 bool is_range) {
buzbee862a7602013-04-05 10:58:54 -07001155 CallInfo* info = static_cast<CallInfo*>(arena_->NewMem(sizeof(CallInfo), true,
1156 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001157 MIR* move_result_mir = FindMoveResult(bb, mir);
1158 if (move_result_mir == NULL) {
1159 info->result.location = kLocInvalid;
1160 } else {
1161 info->result = GetRawDest(move_result_mir);
1162 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1163 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1164 }
1165 info->num_arg_words = mir->ssa_rep->num_uses;
1166 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
buzbee862a7602013-04-05 10:58:54 -07001167 (arena_->NewMem(sizeof(RegLocation) * info->num_arg_words, false,
1168 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001169 for (int i = 0; i < info->num_arg_words; i++) {
1170 info->args[i] = GetRawSrc(mir, i);
1171 }
1172 info->opt_flags = mir->optimization_flags;
1173 info->type = type;
1174 info->is_range = is_range;
1175 info->index = mir->dalvikInsn.vB;
1176 info->offset = mir->offset;
1177 return info;
1178}
1179
buzbee862a7602013-04-05 10:58:54 -07001180// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001181BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
buzbee862a7602013-04-05 10:58:54 -07001182 BasicBlock* bb = static_cast<BasicBlock*>(arena_->NewMem(sizeof(BasicBlock), true,
1183 ArenaAllocator::kAllocBB));
1184 bb->block_type = block_type;
1185 bb->id = block_id;
1186 // TUNING: better estimate of the exit block predecessors?
Brian Carlstromdf629502013-07-17 22:39:56 -07001187 bb->predecessors = new (arena_) GrowableArray<BasicBlock*>(arena_,
1188 (block_type == kExitBlock) ? 2048 : 2,
1189 kGrowableArrayPredecessors);
buzbee862a7602013-04-05 10:58:54 -07001190 bb->successor_block_list.block_list_type = kNotUsed;
1191 block_id_map_.Put(block_id, block_id);
1192 return bb;
1193}
buzbee1fd33462013-03-25 13:40:45 -07001194
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001195} // namespace art