blob: fe0f0c7c8533a5b79fd0ed7ffa8222f9009630e6 [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),
80 ssa_strings_(NULL),
81 vreg_to_ssa_map_(NULL),
82 ssa_last_defs_(NULL),
83 is_constant_v_(NULL),
84 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070085 use_counts_(arena, 256, kGrowableArrayMisc),
86 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080087 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070088 dfs_order_(NULL),
89 dfs_post_order_(NULL),
90 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080091 i_dom_list_(NULL),
92 def_block_matrix_(NULL),
93 temp_block_v_(NULL),
94 temp_dalvik_register_v_(NULL),
95 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070096 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080097 try_block_addr_(NULL),
98 entry_block_(NULL),
99 exit_block_(NULL),
100 cur_block_(NULL),
101 num_blocks_(0),
102 current_code_item_(NULL),
103 current_method_(kInvalidEntry),
104 current_offset_(kInvalidEntry),
105 def_count_(0),
106 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700107 num_ssa_regs_(0),
108 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700109 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
110 checkstats_(NULL),
111 arena_(arena)
buzbee1fd33462013-03-25 13:40:45 -0700112 {
buzbee862a7602013-04-05 10:58:54 -0700113 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -0800114}
115
Ian Rogers6282dc12013-04-18 15:54:02 -0700116MIRGraph::~MIRGraph() {
117 STLDeleteElements(&m_units_);
118}
119
buzbee311ca162013-02-28 15:56:43 -0800120bool MIRGraph::ContentIsInsn(const uint16_t* code_ptr) {
121 uint16_t instr = *code_ptr;
122 Instruction::Code opcode = static_cast<Instruction::Code>(instr & 0xff);
123 /*
124 * Since the low 8-bit in metadata may look like NOP, we need to check
125 * both the low and whole sub-word to determine whether it is code or data.
126 */
127 return (opcode != Instruction::NOP || instr == 0);
128}
129
130/*
131 * Parse an instruction, return the length of the instruction
132 */
133int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction)
134{
135 // Don't parse instruction data
136 if (!ContentIsInsn(code_ptr)) {
137 return 0;
138 }
139
140 const Instruction* instruction = Instruction::At(code_ptr);
141 *decoded_instruction = DecodedInstruction(instruction);
142
143 return instruction->SizeInCodeUnits();
144}
145
146
147/* Split an existing block from the specified code offset into two */
148BasicBlock* MIRGraph::SplitBlock(unsigned int code_offset,
149 BasicBlock* orig_block, BasicBlock** immed_pred_block_p)
150{
151 MIR* insn = orig_block->first_mir_insn;
152 while (insn) {
153 if (insn->offset == code_offset) break;
154 insn = insn->next;
155 }
156 if (insn == NULL) {
157 LOG(FATAL) << "Break split failed";
158 }
buzbee862a7602013-04-05 10:58:54 -0700159 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
160 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800161
162 bottom_block->start_offset = code_offset;
163 bottom_block->first_mir_insn = insn;
164 bottom_block->last_mir_insn = orig_block->last_mir_insn;
165
166 /* If this block was terminated by a return, the flag needs to go with the bottom block */
167 bottom_block->terminated_by_return = orig_block->terminated_by_return;
168 orig_block->terminated_by_return = false;
169
170 /* Add it to the quick lookup cache */
171 block_map_.Put(bottom_block->start_offset, bottom_block);
172
173 /* Handle the taken path */
174 bottom_block->taken = orig_block->taken;
175 if (bottom_block->taken) {
176 orig_block->taken = NULL;
buzbee862a7602013-04-05 10:58:54 -0700177 bottom_block->taken->predecessors->Delete(orig_block);
178 bottom_block->taken->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800179 }
180
181 /* Handle the fallthrough path */
182 bottom_block->fall_through = orig_block->fall_through;
183 orig_block->fall_through = bottom_block;
buzbee862a7602013-04-05 10:58:54 -0700184 bottom_block->predecessors->Insert(orig_block);
buzbee311ca162013-02-28 15:56:43 -0800185 if (bottom_block->fall_through) {
buzbee862a7602013-04-05 10:58:54 -0700186 bottom_block->fall_through->predecessors->Delete(orig_block);
187 bottom_block->fall_through->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800188 }
189
190 /* Handle the successor list */
191 if (orig_block->successor_block_list.block_list_type != kNotUsed) {
192 bottom_block->successor_block_list = orig_block->successor_block_list;
193 orig_block->successor_block_list.block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -0700194 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800195 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700196 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800197 if (successor_block_info == NULL) break;
198 BasicBlock *bb = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700199 bb->predecessors->Delete(orig_block);
200 bb->predecessors->Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800201 }
202 }
203
204 orig_block->last_mir_insn = insn->prev;
205
206 insn->prev->next = NULL;
207 insn->prev = NULL;
208 /*
209 * Update the immediate predecessor block pointer so that outgoing edges
210 * can be applied to the proper block.
211 */
212 if (immed_pred_block_p) {
213 DCHECK_EQ(*immed_pred_block_p, orig_block);
214 *immed_pred_block_p = bottom_block;
215 }
216 return bottom_block;
217}
218
219/*
220 * Given a code offset, find out the block that starts with it. If the offset
221 * is in the middle of an existing block, split it into two. If immed_pred_block_p
222 * is not non-null and is the block being split, update *immed_pred_block_p to
223 * point to the bottom block so that outgoing edges can be set up properly
224 * (by the caller)
225 * Utilizes a map for fast lookup of the typical cases.
226 */
227BasicBlock* MIRGraph::FindBlock(unsigned int code_offset, bool split, bool create,
228 BasicBlock** immed_pred_block_p)
229{
230 BasicBlock* bb;
231 unsigned int i;
232 SafeMap<unsigned int, BasicBlock*>::iterator it;
233
234 it = block_map_.find(code_offset);
235 if (it != block_map_.end()) {
236 return it->second;
237 } else if (!create) {
238 return NULL;
239 }
240
241 if (split) {
buzbee862a7602013-04-05 10:58:54 -0700242 for (i = 0; i < block_list_.Size(); i++) {
243 bb = block_list_.Get(i);
buzbee311ca162013-02-28 15:56:43 -0800244 if (bb->block_type != kDalvikByteCode) continue;
245 /* Check if a branch jumps into the middle of an existing block */
246 if ((code_offset > bb->start_offset) && (bb->last_mir_insn != NULL) &&
247 (code_offset <= bb->last_mir_insn->offset)) {
248 BasicBlock *new_bb = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ?
249 immed_pred_block_p : NULL);
250 return new_bb;
251 }
252 }
253 }
254
255 /* Create a new one */
buzbee862a7602013-04-05 10:58:54 -0700256 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
257 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800258 bb->start_offset = code_offset;
259 block_map_.Put(bb->start_offset, bb);
260 return bb;
261}
262
263/* Identify code range in try blocks and set up the empty catch blocks */
264void MIRGraph::ProcessTryCatchBlocks()
265{
266 int tries_size = current_code_item_->tries_size_;
267 int offset;
268
269 if (tries_size == 0) {
270 return;
271 }
272
273 for (int i = 0; i < tries_size; i++) {
274 const DexFile::TryItem* pTry =
275 DexFile::GetTryItems(*current_code_item_, i);
276 int start_offset = pTry->start_addr_;
277 int end_offset = start_offset + pTry->insn_count_;
278 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700279 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800280 }
281 }
282
283 // Iterate over each of the handlers to enqueue the empty Catch blocks
284 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
285 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
286 for (uint32_t idx = 0; idx < handlers_size; idx++) {
287 CatchHandlerIterator iterator(handlers_ptr);
288 for (; iterator.HasNext(); iterator.Next()) {
289 uint32_t address = iterator.GetHandlerAddress();
290 FindBlock(address, false /* split */, true /*create*/,
291 /* immed_pred_block_p */ NULL);
292 }
293 handlers_ptr = iterator.EndDataPointer();
294 }
295}
296
297/* Process instructions with the kBranch flag */
298BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
299 int flags, const uint16_t* code_ptr,
300 const uint16_t* code_end)
301{
302 int target = cur_offset;
303 switch (insn->dalvikInsn.opcode) {
304 case Instruction::GOTO:
305 case Instruction::GOTO_16:
306 case Instruction::GOTO_32:
307 target += insn->dalvikInsn.vA;
308 break;
309 case Instruction::IF_EQ:
310 case Instruction::IF_NE:
311 case Instruction::IF_LT:
312 case Instruction::IF_GE:
313 case Instruction::IF_GT:
314 case Instruction::IF_LE:
315 cur_block->conditional_branch = true;
316 target += insn->dalvikInsn.vC;
317 break;
318 case Instruction::IF_EQZ:
319 case Instruction::IF_NEZ:
320 case Instruction::IF_LTZ:
321 case Instruction::IF_GEZ:
322 case Instruction::IF_GTZ:
323 case Instruction::IF_LEZ:
324 cur_block->conditional_branch = true;
325 target += insn->dalvikInsn.vB;
326 break;
327 default:
328 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
329 }
330 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
331 /* immed_pred_block_p */ &cur_block);
332 cur_block->taken = taken_block;
buzbee862a7602013-04-05 10:58:54 -0700333 taken_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800334
335 /* Always terminate the current block for conditional branches */
336 if (flags & Instruction::kContinue) {
337 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
338 /*
339 * If the method is processed
340 * in sequential order from the
341 * beginning, we don't need to
342 * specify split for continue
343 * blocks. However, this
344 * routine can be called by
345 * compileLoop, which starts
346 * parsing the method from an
347 * arbitrary address in the
348 * method body.
349 */
350 true,
351 /* create */
352 true,
353 /* immed_pred_block_p */
354 &cur_block);
355 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700356 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800357 } else if (code_ptr < code_end) {
358 /* Create a fallthrough block for real instructions (incl. NOP) */
359 if (ContentIsInsn(code_ptr)) {
360 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
361 /* immed_pred_block_p */ NULL);
362 }
363 }
364 return cur_block;
365}
366
367/* Process instructions with the kSwitch flag */
368void MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
369 int flags)
370{
371 const uint16_t* switch_data =
372 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
373 int size;
374 const int* keyTable;
375 const int* target_table;
376 int i;
377 int first_key;
378
379 /*
380 * Packed switch data format:
381 * ushort ident = 0x0100 magic value
382 * ushort size number of entries in the table
383 * int first_key first (and lowest) switch case value
384 * int targets[size] branch targets, relative to switch opcode
385 *
386 * Total size is (4+size*2) 16-bit code units.
387 */
388 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
389 DCHECK_EQ(static_cast<int>(switch_data[0]),
390 static_cast<int>(Instruction::kPackedSwitchSignature));
391 size = switch_data[1];
392 first_key = switch_data[2] | (switch_data[3] << 16);
393 target_table = reinterpret_cast<const int*>(&switch_data[4]);
394 keyTable = NULL; // Make the compiler happy
395 /*
396 * Sparse switch data format:
397 * ushort ident = 0x0200 magic value
398 * ushort size number of entries in the table; > 0
399 * int keys[size] keys, sorted low-to-high; 32-bit aligned
400 * int targets[size] branch targets, relative to switch opcode
401 *
402 * Total size is (2+size*4) 16-bit code units.
403 */
404 } else {
405 DCHECK_EQ(static_cast<int>(switch_data[0]),
406 static_cast<int>(Instruction::kSparseSwitchSignature));
407 size = switch_data[1];
408 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
409 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
410 first_key = 0; // To make the compiler happy
411 }
412
413 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
414 LOG(FATAL) << "Successor block list already in use: "
415 << static_cast<int>(cur_block->successor_block_list.block_list_type);
416 }
417 cur_block->successor_block_list.block_list_type =
418 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
419 kPackedSwitch : kSparseSwitch;
buzbee862a7602013-04-05 10:58:54 -0700420 cur_block->successor_block_list.blocks =
421 new (arena_)GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800422
423 for (i = 0; i < size; i++) {
424 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
425 /* create */ true, /* immed_pred_block_p */ &cur_block);
426 SuccessorBlockInfo *successor_block_info =
buzbee862a7602013-04-05 10:58:54 -0700427 static_cast<SuccessorBlockInfo*>(arena_->NewMem(sizeof(SuccessorBlockInfo), false,
428 ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800429 successor_block_info->block = case_block;
430 successor_block_info->key =
431 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
432 first_key + i : keyTable[i];
buzbee862a7602013-04-05 10:58:54 -0700433 cur_block->successor_block_list.blocks->Insert(successor_block_info);
434 case_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800435 }
436
437 /* Fall-through case */
438 BasicBlock* fallthrough_block = FindBlock( cur_offset + width, /* split */ false,
439 /* create */ true, /* immed_pred_block_p */ NULL);
440 cur_block->fall_through = fallthrough_block;
buzbee862a7602013-04-05 10:58:54 -0700441 fallthrough_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800442}
443
444/* Process instructions with the kThrow flag */
445BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, int cur_offset, int width,
446 int flags, ArenaBitVector* try_block_addr,
447 const uint16_t* code_ptr, const uint16_t* code_end)
448{
buzbee862a7602013-04-05 10:58:54 -0700449 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee311ca162013-02-28 15:56:43 -0800450
451 /* In try block */
452 if (in_try_block) {
453 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
454
455 if (cur_block->successor_block_list.block_list_type != kNotUsed) {
456 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
457 LOG(FATAL) << "Successor block list already in use: "
458 << static_cast<int>(cur_block->successor_block_list.block_list_type);
459 }
460
461 cur_block->successor_block_list.block_list_type = kCatch;
buzbee862a7602013-04-05 10:58:54 -0700462 cur_block->successor_block_list.blocks =
463 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800464
465 for (;iterator.HasNext(); iterator.Next()) {
466 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
467 false /* creat */, NULL /* immed_pred_block_p */);
468 catch_block->catch_entry = true;
469 if (kIsDebugBuild) {
470 catches_.insert(catch_block->start_offset);
471 }
472 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
buzbee862a7602013-04-05 10:58:54 -0700473 (arena_->NewMem(sizeof(SuccessorBlockInfo), false, ArenaAllocator::kAllocSuccessor));
buzbee311ca162013-02-28 15:56:43 -0800474 successor_block_info->block = catch_block;
475 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee862a7602013-04-05 10:58:54 -0700476 cur_block->successor_block_list.blocks->Insert(successor_block_info);
477 catch_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800478 }
479 } else {
buzbee862a7602013-04-05 10:58:54 -0700480 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800481 cur_block->taken = eh_block;
buzbee862a7602013-04-05 10:58:54 -0700482 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800483 eh_block->start_offset = cur_offset;
buzbee862a7602013-04-05 10:58:54 -0700484 eh_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800485 }
486
487 if (insn->dalvikInsn.opcode == Instruction::THROW){
488 cur_block->explicit_throw = true;
489 if ((code_ptr < code_end) && ContentIsInsn(code_ptr)) {
490 // Force creation of new block following THROW via side-effect
491 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
492 /* immed_pred_block_p */ NULL);
493 }
494 if (!in_try_block) {
495 // Don't split a THROW that can't rethrow - we're done.
496 return cur_block;
497 }
498 }
499
500 /*
501 * Split the potentially-throwing instruction into two parts.
502 * The first half will be a pseudo-op that captures the exception
503 * edges and terminates the basic block. It always falls through.
504 * Then, create a new basic block that begins with the throwing instruction
505 * (minus exceptions). Note: this new basic block must NOT be entered into
506 * the block_map. If the potentially-throwing instruction is the target of a
507 * future branch, we need to find the check psuedo half. The new
508 * basic block containing the work portion of the instruction should
509 * only be entered via fallthrough from the block containing the
510 * pseudo exception edge MIR. Note also that this new block is
511 * not automatically terminated after the work portion, and may
512 * contain following instructions.
513 */
buzbee862a7602013-04-05 10:58:54 -0700514 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
515 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800516 new_block->start_offset = insn->offset;
517 cur_block->fall_through = new_block;
buzbee862a7602013-04-05 10:58:54 -0700518 new_block->predecessors->Insert(cur_block);
519 MIR* new_insn = static_cast<MIR*>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800520 *new_insn = *insn;
521 insn->dalvikInsn.opcode =
522 static_cast<Instruction::Code>(kMirOpCheck);
523 // Associate the two halves
524 insn->meta.throw_insn = new_insn;
525 new_insn->meta.throw_insn = insn;
526 AppendMIR(new_block, new_insn);
527 return new_block;
528}
529
530/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
531void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
532 InvokeType invoke_type, uint32_t class_def_idx,
533 uint32_t method_idx, jobject class_loader, const DexFile& dex_file)
534{
535 current_code_item_ = code_item;
536 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
537 current_method_ = m_units_.size();
538 current_offset_ = 0;
539 // TODO: will need to snapshot stack image and use that as the mir context identification.
540 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
541 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
542 const uint16_t* code_ptr = current_code_item_->insns_;
543 const uint16_t* code_end =
544 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
545
546 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbee862a7602013-04-05 10:58:54 -0700547 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800548 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700549 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
550 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800551
552 // If this is the first method, set up default entry and exit blocks.
553 if (current_method_ == 0) {
554 DCHECK(entry_block_ == NULL);
555 DCHECK(exit_block_ == NULL);
556 DCHECK(num_blocks_ == 0);
buzbee862a7602013-04-05 10:58:54 -0700557 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
558 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
559 block_list_.Insert(entry_block_);
560 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800561 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
562 cu_->dex_file = &dex_file;
563 cu_->class_def_idx = class_def_idx;
564 cu_->method_idx = method_idx;
565 cu_->access_flags = access_flags;
566 cu_->invoke_type = invoke_type;
567 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
568 cu_->num_ins = current_code_item_->ins_size_;
569 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
570 cu_->num_outs = current_code_item_->outs_size_;
571 cu_->num_dalvik_registers = current_code_item_->registers_size_;
572 cu_->insns = current_code_item_->insns_;
573 cu_->code_item = current_code_item_;
574 } else {
575 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
576 /*
577 * Will need to manage storage for ins & outs, push prevous state and update
578 * insert point.
579 */
580 }
581
582 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700583 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee311ca162013-02-28 15:56:43 -0800584 DCHECK_EQ(current_offset_, 0);
585 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700586 block_list_.Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800587 /* Add first block to the fast lookup cache */
588// FIXME: block map needs association with offset/method pair rather than just offset
589 block_map_.Put(cur_block->start_offset, cur_block);
590// FIXME: this needs to insert at the insert point rather than entry block.
591 entry_block_->fall_through = cur_block;
buzbee862a7602013-04-05 10:58:54 -0700592 cur_block->predecessors->Insert(entry_block_);
buzbee311ca162013-02-28 15:56:43 -0800593
594 /* Identify code range in try blocks and set up the empty catch blocks */
595 ProcessTryCatchBlocks();
596
597 /* Set up for simple method detection */
598 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
599 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
600 bool* dead_pattern =
buzbee862a7602013-04-05 10:58:54 -0700601 static_cast<bool*>(arena_->NewMem(sizeof(bool) * num_patterns, true,
602 ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800603 SpecialCaseHandler special_case = kNoHandler;
604 // FIXME - wire this up
605 (void)special_case;
606 int pattern_pos = 0;
607
608 /* Parse all instructions and put them into containing basic blocks */
609 while (code_ptr < code_end) {
buzbee862a7602013-04-05 10:58:54 -0700610 MIR *insn = static_cast<MIR *>(arena_->NewMem(sizeof(MIR), true, ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800611 insn->offset = current_offset_;
612 insn->m_unit_index = current_method_;
613 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
614 insn->width = width;
615 Instruction::Code opcode = insn->dalvikInsn.opcode;
616 if (opcode_count_ != NULL) {
617 opcode_count_[static_cast<int>(opcode)]++;
618 }
619
620 /* Terminate when the data section is seen */
621 if (width == 0)
622 break;
623
624 /* Possible simple method? */
625 if (live_pattern) {
626 live_pattern = false;
627 special_case = kNoHandler;
628 for (int i = 0; i < num_patterns; i++) {
629 if (!dead_pattern[i]) {
630 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
631 live_pattern = true;
632 special_case = special_patterns[i].handler_code;
633 } else {
634 dead_pattern[i] = true;
635 }
636 }
637 }
638 pattern_pos++;
639 }
640
641 AppendMIR(cur_block, insn);
642
643 code_ptr += width;
644 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
645
buzbee1fd33462013-03-25 13:40:45 -0700646 int df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800647
648 if (df_flags & DF_HAS_DEFS) {
649 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
650 }
651
652 if (flags & Instruction::kBranch) {
653 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
654 width, flags, code_ptr, code_end);
655 } else if (flags & Instruction::kReturn) {
656 cur_block->terminated_by_return = true;
657 cur_block->fall_through = exit_block_;
buzbee862a7602013-04-05 10:58:54 -0700658 exit_block_->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800659 /*
660 * Terminate the current block if there are instructions
661 * afterwards.
662 */
663 if (code_ptr < code_end) {
664 /*
665 * Create a fallthrough block for real instructions
666 * (incl. NOP).
667 */
668 if (ContentIsInsn(code_ptr)) {
669 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
670 /* immed_pred_block_p */ NULL);
671 }
672 }
673 } else if (flags & Instruction::kThrow) {
674 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
675 code_ptr, code_end);
676 } else if (flags & Instruction::kSwitch) {
677 ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
678 }
679 current_offset_ += width;
680 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
681 false, /* immed_pred_block_p */ NULL);
682 if (next_block) {
683 /*
684 * The next instruction could be the target of a previously parsed
685 * forward branch so a block is already created. If the current
686 * instruction is not an unconditional branch, connect them through
687 * the fall-through link.
688 */
689 DCHECK(cur_block->fall_through == NULL ||
690 cur_block->fall_through == next_block ||
691 cur_block->fall_through == exit_block_);
692
693 if ((cur_block->fall_through == NULL) && (flags & Instruction::kContinue)) {
694 cur_block->fall_through = next_block;
buzbee862a7602013-04-05 10:58:54 -0700695 next_block->predecessors->Insert(cur_block);
buzbee311ca162013-02-28 15:56:43 -0800696 }
697 cur_block = next_block;
698 }
699 }
700 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
701 DumpCFG("/sdcard/1_post_parse_cfg/", true);
702 }
703
704 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700705 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800706 }
707}
708
709void MIRGraph::ShowOpcodeStats()
710{
711 DCHECK(opcode_count_ != NULL);
712 LOG(INFO) << "Opcode Count";
713 for (int i = 0; i < kNumPackedOpcodes; i++) {
714 if (opcode_count_[i] != 0) {
715 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
716 << " " << opcode_count_[i];
717 }
718 }
719}
720
721// TODO: use a configurable base prefix, and adjust callers to supply pass name.
722/* Dump the CFG into a DOT graph */
723void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks)
724{
725 FILE* file;
726 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
727 ReplaceSpecialChars(fname);
728 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
729 GetEntryBlock()->fall_through->start_offset);
730 file = fopen(fname.c_str(), "w");
731 if (file == NULL) {
732 return;
733 }
734 fprintf(file, "digraph G {\n");
735
736 fprintf(file, " rankdir=TB\n");
737
738 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
739 int idx;
740
741 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700742 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800743 BasicBlock *bb = GetBasicBlock(block_idx);
744 if (bb == NULL) break;
745 if (bb->block_type == kDead) continue;
746 if (bb->block_type == kEntryBlock) {
747 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
748 } else if (bb->block_type == kExitBlock) {
749 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
750 } else if (bb->block_type == kDalvikByteCode) {
751 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
752 bb->start_offset, bb->id);
753 const MIR *mir;
754 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
755 bb->first_mir_insn ? " | " : " ");
756 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
757 int opcode = mir->dalvikInsn.opcode;
758 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700759 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800760 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700761 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800762 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
763 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
764 mir->next ? " | " : " ");
765 }
766 fprintf(file, " }\"];\n\n");
767 } else if (bb->block_type == kExceptionHandling) {
768 char block_name[BLOCK_NAME_LEN];
769
770 GetBlockName(bb, block_name);
771 fprintf(file, " %s [shape=invhouse];\n", block_name);
772 }
773
774 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
775
776 if (bb->taken) {
777 GetBlockName(bb, block_name1);
778 GetBlockName(bb->taken, block_name2);
779 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
780 block_name1, block_name2);
781 }
782 if (bb->fall_through) {
783 GetBlockName(bb, block_name1);
784 GetBlockName(bb->fall_through, block_name2);
785 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
786 }
787
788 if (bb->successor_block_list.block_list_type != kNotUsed) {
789 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
790 bb->start_offset, bb->id,
791 (bb->successor_block_list.block_list_type == kCatch) ?
792 "Mrecord" : "record");
buzbee862a7602013-04-05 10:58:54 -0700793 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_block_list.blocks);
794 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800795
796 int succ_id = 0;
797 while (true) {
798 if (successor_block_info == NULL) break;
799
800 BasicBlock *dest_block = successor_block_info->block;
buzbee862a7602013-04-05 10:58:54 -0700801 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800802
803 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
804 succ_id++,
805 successor_block_info->key,
806 dest_block->start_offset,
807 (next_successor_block_info != NULL) ? " | " : " ");
808
809 successor_block_info = next_successor_block_info;
810 }
811 fprintf(file, " }\"];\n\n");
812
813 GetBlockName(bb, block_name1);
814 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
815 block_name1, bb->start_offset, bb->id);
816
817 if (bb->successor_block_list.block_list_type == kPackedSwitch ||
818 bb->successor_block_list.block_list_type == kSparseSwitch) {
819
buzbee862a7602013-04-05 10:58:54 -0700820 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_block_list.blocks);
buzbee311ca162013-02-28 15:56:43 -0800821
822 succ_id = 0;
823 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700824 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800825 if (successor_block_info == NULL) break;
826
827 BasicBlock *dest_block = successor_block_info->block;
828
829 GetBlockName(dest_block, block_name2);
830 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
831 bb->id, succ_id++, block_name2);
832 }
833 }
834 }
835 fprintf(file, "\n");
836
837 if (cu_->verbose) {
838 /* Display the dominator tree */
839 GetBlockName(bb, block_name1);
840 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
841 block_name1, block_name1);
842 if (bb->i_dom) {
843 GetBlockName(bb->i_dom, block_name2);
844 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
845 }
846 }
847 }
848 fprintf(file, "}\n");
849 fclose(file);
850}
851
buzbee1fd33462013-03-25 13:40:45 -0700852/* Insert an MIR instruction to the end of a basic block */
853void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir)
854{
855 if (bb->first_mir_insn == NULL) {
856 DCHECK(bb->last_mir_insn == NULL);
857 bb->last_mir_insn = bb->first_mir_insn = mir;
858 mir->prev = mir->next = NULL;
859 } else {
860 bb->last_mir_insn->next = mir;
861 mir->prev = bb->last_mir_insn;
862 mir->next = NULL;
863 bb->last_mir_insn = mir;
864 }
865}
866
867/* Insert an MIR instruction to the head of a basic block */
868void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir)
869{
870 if (bb->first_mir_insn == NULL) {
871 DCHECK(bb->last_mir_insn == NULL);
872 bb->last_mir_insn = bb->first_mir_insn = mir;
873 mir->prev = mir->next = NULL;
874 } else {
875 bb->first_mir_insn->prev = mir;
876 mir->next = bb->first_mir_insn;
877 mir->prev = NULL;
878 bb->first_mir_insn = mir;
879 }
880}
881
882/* Insert a MIR instruction after the specified MIR */
883void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir)
884{
885 new_mir->prev = current_mir;
886 new_mir->next = current_mir->next;
887 current_mir->next = new_mir;
888
889 if (new_mir->next) {
890 /* Is not the last MIR in the block */
891 new_mir->next->prev = new_mir;
892 } else {
893 /* Is the last MIR in the block */
894 bb->last_mir_insn = new_mir;
895 }
896}
897
898char* MIRGraph::GetDalvikDisassembly(const MIR* mir)
899{
900 DecodedInstruction insn = mir->dalvikInsn;
901 std::string str;
902 int flags = 0;
903 int opcode = insn.opcode;
904 char* ret;
905 bool nop = false;
906 SSARepresentation* ssa_rep = mir->ssa_rep;
907 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
908 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
909 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
910
911 // Handle special cases.
912 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
913 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
914 str.append(": ");
915 // Recover the original Dex instruction
916 insn = mir->meta.throw_insn->dalvikInsn;
917 ssa_rep = mir->meta.throw_insn->ssa_rep;
918 defs = ssa_rep->num_defs;
919 uses = ssa_rep->num_uses;
920 opcode = insn.opcode;
921 } else if (opcode == kMirOpNop) {
922 str.append("[");
923 insn.opcode = mir->meta.original_opcode;
924 opcode = mir->meta.original_opcode;
925 nop = true;
926 }
927
928 if (opcode >= kMirOpFirst) {
929 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
930 } else {
931 dalvik_format = Instruction::FormatOf(insn.opcode);
932 flags = Instruction::FlagsOf(insn.opcode);
933 str.append(Instruction::Name(insn.opcode));
934 }
935
936 if (opcode == kMirOpPhi) {
937 int* incoming = reinterpret_cast<int*>(insn.vB);
938 str.append(StringPrintf(" %s = (%s",
939 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
940 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
941 str.append(StringPrintf(":%d",incoming[0]));
942 int i;
943 for (i = 1; i < uses; i++) {
944 str.append(StringPrintf(", %s:%d",
945 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
946 incoming[i]));
947 }
948 str.append(")");
949 } else if ((flags & Instruction::kBranch) != 0) {
950 // For branches, decode the instructions to print out the branch targets.
951 int offset = 0;
952 switch (dalvik_format) {
953 case Instruction::k21t:
954 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
955 offset = insn.vB;
956 break;
957 case Instruction::k22t:
958 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
959 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
960 offset = insn.vC;
961 break;
962 case Instruction::k10t:
963 case Instruction::k20t:
964 case Instruction::k30t:
965 offset = insn.vA;
966 break;
967 default:
968 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
969 }
970 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
971 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
972 } else {
973 // For invokes-style formats, treat wide regs as a pair of singles
974 bool show_singles = ((dalvik_format == Instruction::k35c) ||
975 (dalvik_format == Instruction::k3rc));
976 if (defs != 0) {
977 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
978 if (uses != 0) {
979 str.append(", ");
980 }
981 }
982 for (int i = 0; i < uses; i++) {
983 str.append(
984 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
985 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
986 // For the listing, skip the high sreg.
987 i++;
988 }
989 if (i != (uses -1)) {
990 str.append(",");
991 }
992 }
993 switch (dalvik_format) {
994 case Instruction::k11n: // Add one immediate from vB
995 case Instruction::k21s:
996 case Instruction::k31i:
997 case Instruction::k21h:
998 str.append(StringPrintf(", #%d", insn.vB));
999 break;
1000 case Instruction::k51l: // Add one wide immediate
1001 str.append(StringPrintf(", #%lld", insn.vB_wide));
1002 break;
1003 case Instruction::k21c: // One register, one string/type/method index
1004 case Instruction::k31c:
1005 str.append(StringPrintf(", index #%d", insn.vB));
1006 break;
1007 case Instruction::k22c: // Two registers, one string/type/method index
1008 str.append(StringPrintf(", index #%d", insn.vC));
1009 break;
1010 case Instruction::k22s: // Add one immediate from vC
1011 case Instruction::k22b:
1012 str.append(StringPrintf(", #%d", insn.vC));
1013 break;
1014 default:
1015 ; // Nothing left to print
1016 }
1017 }
1018 if (nop) {
1019 str.append("]--optimized away");
1020 }
1021 int length = str.length() + 1;
buzbee862a7602013-04-05 10:58:54 -07001022 ret = static_cast<char*>(arena_->NewMem(length, false, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001023 strncpy(ret, str.c_str(), length);
1024 return ret;
1025}
1026
1027/* Turn method name into a legal Linux file name */
1028void MIRGraph::ReplaceSpecialChars(std::string& str)
1029{
1030 static const struct { const char before; const char after; } match[] =
1031 {{'/','-'}, {';','#'}, {' ','#'}, {'$','+'},
1032 {'(','@'}, {')','@'}, {'<','='}, {'>','='}};
1033 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1034 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1035 }
1036}
1037
1038std::string MIRGraph::GetSSAName(int ssa_reg)
1039{
Ian Rogers39ebcb82013-05-30 16:57:23 -07001040 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1041 // the arena. We should be smarter and just place straight into the arena, or compute the
1042 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001043 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1044}
1045
1046// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
1047std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only)
1048{
1049 if (reg_location_ == NULL) {
1050 // Pre-SSA - just use the standard name
1051 return GetSSAName(ssa_reg);
1052 }
1053 if (IsConst(reg_location_[ssa_reg])) {
1054 if (!singles_only && reg_location_[ssa_reg].wide) {
1055 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1056 ConstantValueWide(reg_location_[ssa_reg]));
1057 } else {
1058 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg),GetSSASubscript(ssa_reg),
1059 ConstantValue(reg_location_[ssa_reg]));
1060 }
1061 } else {
1062 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1063 }
1064}
1065
1066void MIRGraph::GetBlockName(BasicBlock* bb, char* name)
1067{
1068 switch (bb->block_type) {
1069 case kEntryBlock:
1070 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1071 break;
1072 case kExitBlock:
1073 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1074 break;
1075 case kDalvikByteCode:
1076 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1077 break;
1078 case kExceptionHandling:
1079 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1080 bb->id);
1081 break;
1082 default:
1083 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1084 break;
1085 }
1086}
1087
1088const char* MIRGraph::GetShortyFromTargetIdx(int target_idx)
1089{
1090 // FIXME: use current code unit for inline support.
1091 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1092 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1093}
1094
1095/* Debug Utility - dump a compilation unit */
1096void MIRGraph::DumpMIRGraph()
1097{
1098 BasicBlock* bb;
1099 const char* block_type_names[] = {
1100 "Entry Block",
1101 "Code Block",
1102 "Exit Block",
1103 "Exception Handling",
1104 "Catch Block"
1105 };
1106
1107 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1108 LOG(INFO) << cu_->insns << " insns";
1109 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001110 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001111
1112 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001113 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001114 if (bb == NULL) break;
1115 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1116 bb->id,
1117 block_type_names[bb->block_type],
1118 bb->start_offset,
1119 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1120 bb->last_mir_insn ? "" : " empty");
1121 if (bb->taken) {
1122 LOG(INFO) << " Taken branch: block " << bb->taken->id
1123 << "(0x" << std::hex << bb->taken->start_offset << ")";
1124 }
1125 if (bb->fall_through) {
1126 LOG(INFO) << " Fallthrough : block " << bb->fall_through->id
1127 << " (0x" << std::hex << bb->fall_through->start_offset << ")";
1128 }
1129 }
1130}
1131
1132/*
1133 * Build an array of location records for the incoming arguments.
1134 * Note: one location record per word of arguments, with dummy
1135 * high-word loc for wide arguments. Also pull up any following
1136 * MOVE_RESULT and incorporate it into the invoke.
1137 */
1138CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
1139 bool is_range)
1140{
buzbee862a7602013-04-05 10:58:54 -07001141 CallInfo* info = static_cast<CallInfo*>(arena_->NewMem(sizeof(CallInfo), true,
1142 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001143 MIR* move_result_mir = FindMoveResult(bb, mir);
1144 if (move_result_mir == NULL) {
1145 info->result.location = kLocInvalid;
1146 } else {
1147 info->result = GetRawDest(move_result_mir);
1148 move_result_mir->meta.original_opcode = move_result_mir->dalvikInsn.opcode;
1149 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1150 }
1151 info->num_arg_words = mir->ssa_rep->num_uses;
1152 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
buzbee862a7602013-04-05 10:58:54 -07001153 (arena_->NewMem(sizeof(RegLocation) * info->num_arg_words, false,
1154 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001155 for (int i = 0; i < info->num_arg_words; i++) {
1156 info->args[i] = GetRawSrc(mir, i);
1157 }
1158 info->opt_flags = mir->optimization_flags;
1159 info->type = type;
1160 info->is_range = is_range;
1161 info->index = mir->dalvikInsn.vB;
1162 info->offset = mir->offset;
1163 return info;
1164}
1165
buzbee862a7602013-04-05 10:58:54 -07001166// Allocate a new basic block.
1167BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id)
1168{
1169 BasicBlock* bb = static_cast<BasicBlock*>(arena_->NewMem(sizeof(BasicBlock), true,
1170 ArenaAllocator::kAllocBB));
1171 bb->block_type = block_type;
1172 bb->id = block_id;
1173 // TUNING: better estimate of the exit block predecessors?
1174 bb->predecessors = new (arena_)
1175 GrowableArray<BasicBlock*>(arena_, (block_type == kExitBlock) ? 2048 : 2, kGrowableArrayPredecessors);
1176 bb->successor_block_list.block_list_type = kNotUsed;
1177 block_id_map_.Put(block_id, block_id);
1178 return bb;
1179}
buzbee1fd33462013-03-25 13:40:45 -07001180
buzbee311ca162013-02-28 15:56:43 -08001181} // namespace art