blob: 2a1828013350f560ac1bd4cf13aa0d73d77bb6a4 [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ian Rogers6282dc12013-04-18 15:54:02 -070017#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080018#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080019#include "dex_file-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070020#include "leb128.h"
21#include "mir_graph.h"
buzbee311ca162013-02-28 15:56:43 -080022
23namespace art {
24
25#define MAX_PATTERN_LEN 5
26
27struct CodePattern {
28 const Instruction::Code opcodes[MAX_PATTERN_LEN];
29 const SpecialCaseHandler handler_code;
30};
31
32static const CodePattern special_patterns[] = {
33 {{Instruction::RETURN_VOID}, kNullMethod},
34 {{Instruction::CONST, Instruction::RETURN}, kConstFunction},
35 {{Instruction::CONST_4, Instruction::RETURN}, kConstFunction},
36 {{Instruction::CONST_4, Instruction::RETURN_OBJECT}, kConstFunction},
37 {{Instruction::CONST_16, Instruction::RETURN}, kConstFunction},
38 {{Instruction::IGET, Instruction:: RETURN}, kIGet},
39 {{Instruction::IGET_BOOLEAN, Instruction::RETURN}, kIGetBoolean},
40 {{Instruction::IGET_OBJECT, Instruction::RETURN_OBJECT}, kIGetObject},
41 {{Instruction::IGET_BYTE, Instruction::RETURN}, kIGetByte},
42 {{Instruction::IGET_CHAR, Instruction::RETURN}, kIGetChar},
43 {{Instruction::IGET_SHORT, Instruction::RETURN}, kIGetShort},
44 {{Instruction::IGET_WIDE, Instruction::RETURN_WIDE}, kIGetWide},
45 {{Instruction::IPUT, Instruction::RETURN_VOID}, kIPut},
46 {{Instruction::IPUT_BOOLEAN, Instruction::RETURN_VOID}, kIPutBoolean},
47 {{Instruction::IPUT_OBJECT, Instruction::RETURN_VOID}, kIPutObject},
48 {{Instruction::IPUT_BYTE, Instruction::RETURN_VOID}, kIPutByte},
49 {{Instruction::IPUT_CHAR, Instruction::RETURN_VOID}, kIPutChar},
50 {{Instruction::IPUT_SHORT, Instruction::RETURN_VOID}, kIPutShort},
51 {{Instruction::IPUT_WIDE, Instruction::RETURN_VOID}, kIPutWide},
52 {{Instruction::RETURN}, kIdentity},
53 {{Instruction::RETURN_OBJECT}, kIdentity},
54 {{Instruction::RETURN_WIDE}, kIdentity},
55};
56
buzbee1fd33462013-03-25 13:40:45 -070057const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
58 "Phi",
59 "Copy",
60 "FusedCmplFloat",
61 "FusedCmpgFloat",
62 "FusedCmplDouble",
63 "FusedCmpgDouble",
64 "FusedCmpLong",
65 "Nop",
66 "OpNullCheck",
67 "OpRangeCheck",
68 "OpDivZeroCheck",
69 "Check1",
70 "Check2",
71 "Select",
72};
73
buzbee862a7602013-04-05 10:58:54 -070074MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070075 : reg_location_(NULL),
buzbee862a7602013-04-05 10:58:54 -070076 compiler_temps_(arena, 6, kGrowableArrayMisc),
buzbee1fd33462013-03-25 13:40:45 -070077 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080078 ssa_base_vregs_(NULL),
79 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080080 vreg_to_ssa_map_(NULL),
81 ssa_last_defs_(NULL),
82 is_constant_v_(NULL),
83 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070084 use_counts_(arena, 256, kGrowableArrayMisc),
85 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080086 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070087 dfs_order_(NULL),
88 dfs_post_order_(NULL),
89 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080090 i_dom_list_(NULL),
91 def_block_matrix_(NULL),
92 temp_block_v_(NULL),
93 temp_dalvik_register_v_(NULL),
94 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070095 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080096 try_block_addr_(NULL),
97 entry_block_(NULL),
98 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080099 num_blocks_(0),
100 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700101 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -0800102 current_method_(kInvalidEntry),
103 current_offset_(kInvalidEntry),
104 def_count_(0),
105 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700106 num_ssa_regs_(0),
107 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700108 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
109 checkstats_(NULL),
buzbee479f83c2013-07-19 10:58:21 -0700110 special_case_(kNoHandler),
buzbeeb48819d2013-09-14 16:15:25 -0700111 arena_(arena),
112 backward_branches_(0),
113 forward_branches_(0) {
buzbee862a7602013-04-05 10:58:54 -0700114 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
buzbee311ca162013-02-28 15:56:43 -0800115}
116
Ian Rogers6282dc12013-04-18 15:54:02 -0700117MIRGraph::~MIRGraph() {
118 STLDeleteElements(&m_units_);
119}
120
buzbee311ca162013-02-28 15:56:43 -0800121/*
122 * Parse an instruction, return the length of the instruction
123 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700124int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -0800125 const Instruction* instruction = Instruction::At(code_ptr);
126 *decoded_instruction = DecodedInstruction(instruction);
127
128 return instruction->SizeInCodeUnits();
129}
130
131
132/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700133BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700134 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700135 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800136 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700137 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800138 while (insn) {
139 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700140 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800141 insn = insn->next;
142 }
143 if (insn == NULL) {
144 LOG(FATAL) << "Break split failed";
145 }
buzbee862a7602013-04-05 10:58:54 -0700146 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
147 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800148
149 bottom_block->start_offset = code_offset;
150 bottom_block->first_mir_insn = insn;
151 bottom_block->last_mir_insn = orig_block->last_mir_insn;
152
153 /* If this block was terminated by a return, the flag needs to go with the bottom block */
154 bottom_block->terminated_by_return = orig_block->terminated_by_return;
155 orig_block->terminated_by_return = false;
156
157 /* Add it to the quick lookup cache */
buzbeeb48819d2013-09-14 16:15:25 -0700158 dex_pc_to_block_map_.Put(bottom_block->start_offset, bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800159
160 /* Handle the taken path */
161 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700162 if (bottom_block->taken != NullBasicBlockId) {
163 orig_block->taken = NullBasicBlockId;
164 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
165 bb_taken->predecessors->Delete(orig_block->id);
166 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800167 }
168
169 /* Handle the fallthrough path */
170 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700171 orig_block->fall_through = bottom_block->id;
172 bottom_block->predecessors->Insert(orig_block->id);
173 if (bottom_block->fall_through != NullBasicBlockId) {
174 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
175 bb_fall_through->predecessors->Delete(orig_block->id);
176 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800177 }
178
179 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700180 if (orig_block->successor_block_list_type != kNotUsed) {
181 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
182 bottom_block->successor_blocks = orig_block->successor_blocks;
183 orig_block->successor_block_list_type = kNotUsed;
184 orig_block->successor_blocks = NULL;
185 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800186 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700187 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800188 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700189 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
190 bb->predecessors->Delete(orig_block->id);
191 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800192 }
193 }
194
buzbee0d829482013-10-11 15:24:55 -0700195 orig_block->last_mir_insn = prev;
196 prev->next = NULL;
buzbee311ca162013-02-28 15:56:43 -0800197
buzbee311ca162013-02-28 15:56:43 -0800198 /*
199 * Update the immediate predecessor block pointer so that outgoing edges
200 * can be applied to the proper block.
201 */
202 if (immed_pred_block_p) {
203 DCHECK_EQ(*immed_pred_block_p, orig_block);
204 *immed_pred_block_p = bottom_block;
205 }
buzbeeb48819d2013-09-14 16:15:25 -0700206
207 // Associate dex instructions in the bottom block with the new container.
208 MIR* p = bottom_block->first_mir_insn;
209 while (p != NULL) {
210 int opcode = p->dalvikInsn.opcode;
211 /*
212 * Some messiness here to ensure that we only enter real opcodes and only the
213 * first half of a potentially throwing instruction that has been split into
214 * CHECK and work portions. The 2nd half of a split operation will have a non-null
215 * throw_insn pointer that refers to the 1st half.
216 */
217 if ((opcode == kMirOpCheck) || (!IsPseudoMirOp(opcode) && (p->meta.throw_insn == NULL))) {
218 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
219 }
220 p = (p == bottom_block->last_mir_insn) ? NULL : p->next;
221 }
222
buzbee311ca162013-02-28 15:56:43 -0800223 return bottom_block;
224}
225
226/*
227 * Given a code offset, find out the block that starts with it. If the offset
228 * is in the middle of an existing block, split it into two. If immed_pred_block_p
229 * is not non-null and is the block being split, update *immed_pred_block_p to
230 * point to the bottom block so that outgoing edges can be set up properly
231 * (by the caller)
232 * Utilizes a map for fast lookup of the typical cases.
233 */
buzbee0d829482013-10-11 15:24:55 -0700234BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700235 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700236 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800237 return NULL;
238 }
buzbeeb48819d2013-09-14 16:15:25 -0700239
240 int block_id = dex_pc_to_block_map_.Get(code_offset);
241 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
242
243 if ((bb != NULL) && (bb->start_offset == code_offset)) {
244 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700245 return bb;
246 }
buzbee311ca162013-02-28 15:56:43 -0800247
buzbeeb48819d2013-09-14 16:15:25 -0700248 // No direct hit.
249 if (!create) {
250 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800251 }
252
buzbeeb48819d2013-09-14 16:15:25 -0700253 if (bb != NULL) {
254 // The target exists somewhere in an existing block.
255 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
256 }
257
258 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700259 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
260 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800261 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700262 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800263 return bb;
264}
265
buzbeeb48819d2013-09-14 16:15:25 -0700266
buzbee311ca162013-02-28 15:56:43 -0800267/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700268void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800269 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700270 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800271
272 if (tries_size == 0) {
273 return;
274 }
275
276 for (int i = 0; i < tries_size; i++) {
277 const DexFile::TryItem* pTry =
278 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700279 DexOffset start_offset = pTry->start_addr_;
280 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800281 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700282 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800283 }
284 }
285
286 // Iterate over each of the handlers to enqueue the empty Catch blocks
287 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
288 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
289 for (uint32_t idx = 0; idx < handlers_size; idx++) {
290 CatchHandlerIterator iterator(handlers_ptr);
291 for (; iterator.HasNext(); iterator.Next()) {
292 uint32_t address = iterator.GetHandlerAddress();
293 FindBlock(address, false /* split */, true /*create*/,
294 /* immed_pred_block_p */ NULL);
295 }
296 handlers_ptr = iterator.EndDataPointer();
297 }
298}
299
300/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700301BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
302 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700303 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700304 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800305 switch (insn->dalvikInsn.opcode) {
306 case Instruction::GOTO:
307 case Instruction::GOTO_16:
308 case Instruction::GOTO_32:
309 target += insn->dalvikInsn.vA;
310 break;
311 case Instruction::IF_EQ:
312 case Instruction::IF_NE:
313 case Instruction::IF_LT:
314 case Instruction::IF_GE:
315 case Instruction::IF_GT:
316 case Instruction::IF_LE:
317 cur_block->conditional_branch = true;
318 target += insn->dalvikInsn.vC;
319 break;
320 case Instruction::IF_EQZ:
321 case Instruction::IF_NEZ:
322 case Instruction::IF_LTZ:
323 case Instruction::IF_GEZ:
324 case Instruction::IF_GTZ:
325 case Instruction::IF_LEZ:
326 cur_block->conditional_branch = true;
327 target += insn->dalvikInsn.vB;
328 break;
329 default:
330 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
331 }
buzbeeb48819d2013-09-14 16:15:25 -0700332 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800333 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
334 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700335 cur_block->taken = taken_block->id;
336 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800337
338 /* Always terminate the current block for conditional branches */
339 if (flags & Instruction::kContinue) {
340 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
341 /*
342 * If the method is processed
343 * in sequential order from the
344 * beginning, we don't need to
345 * specify split for continue
346 * blocks. However, this
347 * routine can be called by
348 * compileLoop, which starts
349 * parsing the method from an
350 * arbitrary address in the
351 * method body.
352 */
353 true,
354 /* create */
355 true,
356 /* immed_pred_block_p */
357 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700358 cur_block->fall_through = fallthrough_block->id;
359 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800360 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700361 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800362 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800363 }
364 return cur_block;
365}
366
367/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800368BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
369 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800370 const uint16_t* switch_data =
371 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
372 int size;
373 const int* keyTable;
374 const int* target_table;
375 int i;
376 int first_key;
377
378 /*
379 * Packed switch data format:
380 * ushort ident = 0x0100 magic value
381 * ushort size number of entries in the table
382 * int first_key first (and lowest) switch case value
383 * int targets[size] branch targets, relative to switch opcode
384 *
385 * Total size is (4+size*2) 16-bit code units.
386 */
387 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
388 DCHECK_EQ(static_cast<int>(switch_data[0]),
389 static_cast<int>(Instruction::kPackedSwitchSignature));
390 size = switch_data[1];
391 first_key = switch_data[2] | (switch_data[3] << 16);
392 target_table = reinterpret_cast<const int*>(&switch_data[4]);
393 keyTable = NULL; // Make the compiler happy
394 /*
395 * Sparse switch data format:
396 * ushort ident = 0x0200 magic value
397 * ushort size number of entries in the table; > 0
398 * int keys[size] keys, sorted low-to-high; 32-bit aligned
399 * int targets[size] branch targets, relative to switch opcode
400 *
401 * Total size is (2+size*4) 16-bit code units.
402 */
403 } else {
404 DCHECK_EQ(static_cast<int>(switch_data[0]),
405 static_cast<int>(Instruction::kSparseSwitchSignature));
406 size = switch_data[1];
407 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
408 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
409 first_key = 0; // To make the compiler happy
410 }
411
buzbee0d829482013-10-11 15:24:55 -0700412 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800413 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700414 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800415 }
buzbee0d829482013-10-11 15:24:55 -0700416 cur_block->successor_block_list_type =
417 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
418 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700419 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800420
421 for (i = 0; i < size; i++) {
422 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
423 /* create */ true, /* immed_pred_block_p */ &cur_block);
424 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700425 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
426 ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700427 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800428 successor_block_info->key =
429 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
430 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700431 cur_block->successor_blocks->Insert(successor_block_info);
432 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800433 }
434
435 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700436 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
437 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700438 cur_block->fall_through = fallthrough_block->id;
439 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800440 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800441}
442
443/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700444BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
445 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700446 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700447 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800448 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
449 bool build_all_edges =
450 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800451
452 /* In try block */
453 if (in_try_block) {
454 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
455
buzbee0d829482013-10-11 15:24:55 -0700456 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800457 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
458 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700459 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800460 }
461
buzbee0d829482013-10-11 15:24:55 -0700462 cur_block->successor_block_list_type = kCatch;
463 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700464 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800465
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700466 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800467 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
468 false /* creat */, NULL /* immed_pred_block_p */);
469 catch_block->catch_entry = true;
470 if (kIsDebugBuild) {
471 catches_.insert(catch_block->start_offset);
472 }
473 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700474 (arena_->Alloc(sizeof(SuccessorBlockInfo), ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700475 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800476 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700477 cur_block->successor_blocks->Insert(successor_block_info);
478 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800479 }
buzbee17189ac2013-11-08 11:07:02 -0800480 } else if (build_all_edges) {
buzbee862a7602013-04-05 10:58:54 -0700481 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700482 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700483 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800484 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700485 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800486 }
487
buzbee17189ac2013-11-08 11:07:02 -0800488 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800489 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700490 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800491 // Force creation of new block following THROW via side-effect
492 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
493 /* immed_pred_block_p */ NULL);
494 }
495 if (!in_try_block) {
496 // Don't split a THROW that can't rethrow - we're done.
497 return cur_block;
498 }
499 }
500
buzbee17189ac2013-11-08 11:07:02 -0800501 if (!build_all_edges) {
502 /*
503 * Even though there is an exception edge here, control cannot return to this
504 * method. Thus, for the purposes of dataflow analysis and optimization, we can
505 * ignore the edge. Doing this reduces compile time, and increases the scope
506 * of the basic-block level optimization pass.
507 */
508 return cur_block;
509 }
510
buzbee311ca162013-02-28 15:56:43 -0800511 /*
512 * Split the potentially-throwing instruction into two parts.
513 * The first half will be a pseudo-op that captures the exception
514 * edges and terminates the basic block. It always falls through.
515 * Then, create a new basic block that begins with the throwing instruction
516 * (minus exceptions). Note: this new basic block must NOT be entered into
517 * the block_map. If the potentially-throwing instruction is the target of a
518 * future branch, we need to find the check psuedo half. The new
519 * basic block containing the work portion of the instruction should
520 * only be entered via fallthrough from the block containing the
521 * pseudo exception edge MIR. Note also that this new block is
522 * not automatically terminated after the work portion, and may
523 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700524 *
525 * Note also that the dex_pc_to_block_map_ entry for the potentially
526 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800527 */
buzbee862a7602013-04-05 10:58:54 -0700528 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
529 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800530 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700531 cur_block->fall_through = new_block->id;
532 new_block->predecessors->Insert(cur_block->id);
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700533 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800534 *new_insn = *insn;
535 insn->dalvikInsn.opcode =
536 static_cast<Instruction::Code>(kMirOpCheck);
537 // Associate the two halves
538 insn->meta.throw_insn = new_insn;
539 new_insn->meta.throw_insn = insn;
540 AppendMIR(new_block, new_insn);
541 return new_block;
542}
543
544/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
545void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700546 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700547 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800548 current_code_item_ = code_item;
549 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
550 current_method_ = m_units_.size();
551 current_offset_ = 0;
552 // TODO: will need to snapshot stack image and use that as the mir context identification.
553 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
554 dex_file, current_code_item_, class_def_idx, method_idx, access_flags));
555 const uint16_t* code_ptr = current_code_item_->insns_;
556 const uint16_t* code_end =
557 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
558
559 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700560 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700561 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700562 dex_pc_to_block_map_.SetSize(dex_pc_to_block_map_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700563
buzbee311ca162013-02-28 15:56:43 -0800564 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700565 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
566 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800567
568 // If this is the first method, set up default entry and exit blocks.
569 if (current_method_ == 0) {
570 DCHECK(entry_block_ == NULL);
571 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700572 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700573 // Use id 0 to represent a null block.
574 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
575 DCHECK_EQ(null_block->id, NullBasicBlockId);
576 null_block->hidden = true;
577 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700578 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700579 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700580 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700581 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800582 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
583 cu_->dex_file = &dex_file;
584 cu_->class_def_idx = class_def_idx;
585 cu_->method_idx = method_idx;
586 cu_->access_flags = access_flags;
587 cu_->invoke_type = invoke_type;
588 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
589 cu_->num_ins = current_code_item_->ins_size_;
590 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
591 cu_->num_outs = current_code_item_->outs_size_;
592 cu_->num_dalvik_registers = current_code_item_->registers_size_;
593 cu_->insns = current_code_item_->insns_;
594 cu_->code_item = current_code_item_;
595 } else {
596 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
597 /*
598 * Will need to manage storage for ins & outs, push prevous state and update
599 * insert point.
600 */
601 }
602
603 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700604 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700605 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800606 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700607 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700608 // TODO: for inlining support, insert at the insert point rather than entry block.
609 entry_block_->fall_through = cur_block->id;
610 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800611
612 /* Identify code range in try blocks and set up the empty catch blocks */
613 ProcessTryCatchBlocks();
614
615 /* Set up for simple method detection */
616 int num_patterns = sizeof(special_patterns)/sizeof(special_patterns[0]);
617 bool live_pattern = (num_patterns > 0) && !(cu_->disable_opt & (1 << kMatch));
618 bool* dead_pattern =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700619 static_cast<bool*>(arena_->Alloc(sizeof(bool) * num_patterns, ArenaAllocator::kAllocMisc));
buzbee311ca162013-02-28 15:56:43 -0800620 int pattern_pos = 0;
621
622 /* Parse all instructions and put them into containing basic blocks */
623 while (code_ptr < code_end) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700624 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800625 insn->offset = current_offset_;
626 insn->m_unit_index = current_method_;
627 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
628 insn->width = width;
629 Instruction::Code opcode = insn->dalvikInsn.opcode;
630 if (opcode_count_ != NULL) {
631 opcode_count_[static_cast<int>(opcode)]++;
632 }
633
buzbee311ca162013-02-28 15:56:43 -0800634 /* Possible simple method? */
635 if (live_pattern) {
636 live_pattern = false;
buzbee479f83c2013-07-19 10:58:21 -0700637 special_case_ = kNoHandler;
buzbee311ca162013-02-28 15:56:43 -0800638 for (int i = 0; i < num_patterns; i++) {
639 if (!dead_pattern[i]) {
640 if (special_patterns[i].opcodes[pattern_pos] == opcode) {
641 live_pattern = true;
buzbee479f83c2013-07-19 10:58:21 -0700642 special_case_ = special_patterns[i].handler_code;
buzbee311ca162013-02-28 15:56:43 -0800643 } else {
644 dead_pattern[i] = true;
645 }
646 }
647 }
648 pattern_pos++;
649 }
650
buzbee311ca162013-02-28 15:56:43 -0800651 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
652
buzbee1da1e2f2013-11-15 13:37:01 -0800653 uint64_t df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800654
655 if (df_flags & DF_HAS_DEFS) {
656 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
657 }
658
buzbee1da1e2f2013-11-15 13:37:01 -0800659 if (df_flags & DF_LVN) {
660 cur_block->use_lvn = true; // Run local value numbering on this basic block.
661 }
662
buzbee27247762013-07-28 12:03:58 -0700663 // Check for inline data block signatures
664 if (opcode == Instruction::NOP) {
665 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
666 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
667 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
668 uint16_t following_raw_instruction = code_ptr[1];
669 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
670 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
671 (following_raw_instruction == Instruction::kArrayDataSignature)) {
672 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
673 }
674 }
675 if (width == 1) {
676 // It is a simple nop - treat normally.
677 AppendMIR(cur_block, insn);
678 } else {
buzbee0d829482013-10-11 15:24:55 -0700679 DCHECK(cur_block->fall_through == NullBasicBlockId);
680 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700681 // Unreachable instruction, mark for no continuation.
682 flags &= ~Instruction::kContinue;
683 }
684 } else {
685 AppendMIR(cur_block, insn);
686 }
687
buzbeeb48819d2013-09-14 16:15:25 -0700688 // Associate the starting dex_pc for this opcode with its containing basic block.
689 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
690
buzbee27247762013-07-28 12:03:58 -0700691 code_ptr += width;
692
buzbee311ca162013-02-28 15:56:43 -0800693 if (flags & Instruction::kBranch) {
694 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
695 width, flags, code_ptr, code_end);
696 } else if (flags & Instruction::kReturn) {
697 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700698 cur_block->fall_through = exit_block_->id;
699 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800700 /*
701 * Terminate the current block if there are instructions
702 * afterwards.
703 */
704 if (code_ptr < code_end) {
705 /*
706 * Create a fallthrough block for real instructions
707 * (incl. NOP).
708 */
buzbee27247762013-07-28 12:03:58 -0700709 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
710 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800711 }
712 } else if (flags & Instruction::kThrow) {
713 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
714 code_ptr, code_end);
715 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800716 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800717 }
718 current_offset_ += width;
719 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
720 false, /* immed_pred_block_p */ NULL);
721 if (next_block) {
722 /*
723 * The next instruction could be the target of a previously parsed
724 * forward branch so a block is already created. If the current
725 * instruction is not an unconditional branch, connect them through
726 * the fall-through link.
727 */
buzbee0d829482013-10-11 15:24:55 -0700728 DCHECK(cur_block->fall_through == NullBasicBlockId ||
729 GetBasicBlock(cur_block->fall_through) == next_block ||
730 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800731
buzbee0d829482013-10-11 15:24:55 -0700732 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
733 cur_block->fall_through = next_block->id;
734 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800735 }
736 cur_block = next_block;
737 }
738 }
739 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
740 DumpCFG("/sdcard/1_post_parse_cfg/", true);
741 }
742
743 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700744 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800745 }
746}
747
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700748void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800749 DCHECK(opcode_count_ != NULL);
750 LOG(INFO) << "Opcode Count";
751 for (int i = 0; i < kNumPackedOpcodes; i++) {
752 if (opcode_count_[i] != 0) {
753 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
754 << " " << opcode_count_[i];
755 }
756 }
757}
758
759// TODO: use a configurable base prefix, and adjust callers to supply pass name.
760/* Dump the CFG into a DOT graph */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700761void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks) {
buzbee311ca162013-02-28 15:56:43 -0800762 FILE* file;
763 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
764 ReplaceSpecialChars(fname);
765 fname = StringPrintf("%s%s%x.dot", dir_prefix, fname.c_str(),
buzbee0d829482013-10-11 15:24:55 -0700766 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800767 file = fopen(fname.c_str(), "w");
768 if (file == NULL) {
769 return;
770 }
771 fprintf(file, "digraph G {\n");
772
773 fprintf(file, " rankdir=TB\n");
774
775 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
776 int idx;
777
778 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700779 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
buzbee311ca162013-02-28 15:56:43 -0800780 BasicBlock *bb = GetBasicBlock(block_idx);
781 if (bb == NULL) break;
782 if (bb->block_type == kDead) continue;
783 if (bb->block_type == kEntryBlock) {
784 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
785 } else if (bb->block_type == kExitBlock) {
786 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
787 } else if (bb->block_type == kDalvikByteCode) {
788 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
789 bb->start_offset, bb->id);
790 const MIR *mir;
791 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
792 bb->first_mir_insn ? " | " : " ");
793 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
794 int opcode = mir->dalvikInsn.opcode;
795 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
buzbee1fd33462013-03-25 13:40:45 -0700796 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee311ca162013-02-28 15:56:43 -0800797 (opcode < kMirOpFirst) ? Instruction::Name(mir->dalvikInsn.opcode) :
buzbee1fd33462013-03-25 13:40:45 -0700798 extended_mir_op_names_[opcode - kMirOpFirst],
buzbee311ca162013-02-28 15:56:43 -0800799 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
800 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
801 mir->next ? " | " : " ");
802 }
803 fprintf(file, " }\"];\n\n");
804 } else if (bb->block_type == kExceptionHandling) {
805 char block_name[BLOCK_NAME_LEN];
806
807 GetBlockName(bb, block_name);
808 fprintf(file, " %s [shape=invhouse];\n", block_name);
809 }
810
811 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
812
buzbee0d829482013-10-11 15:24:55 -0700813 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800814 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700815 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800816 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
817 block_name1, block_name2);
818 }
buzbee0d829482013-10-11 15:24:55 -0700819 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800820 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700821 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800822 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
823 }
824
buzbee0d829482013-10-11 15:24:55 -0700825 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800826 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
827 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700828 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
829 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700830 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800831
832 int succ_id = 0;
833 while (true) {
834 if (successor_block_info == NULL) break;
835
buzbee0d829482013-10-11 15:24:55 -0700836 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700837 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800838
839 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
840 succ_id++,
841 successor_block_info->key,
842 dest_block->start_offset,
843 (next_successor_block_info != NULL) ? " | " : " ");
844
845 successor_block_info = next_successor_block_info;
846 }
847 fprintf(file, " }\"];\n\n");
848
849 GetBlockName(bb, block_name1);
850 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
851 block_name1, bb->start_offset, bb->id);
852
buzbee0d829482013-10-11 15:24:55 -0700853 if (bb->successor_block_list_type == kPackedSwitch ||
854 bb->successor_block_list_type == kSparseSwitch) {
855 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800856
857 succ_id = 0;
858 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700859 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800860 if (successor_block_info == NULL) break;
861
buzbee0d829482013-10-11 15:24:55 -0700862 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800863
864 GetBlockName(dest_block, block_name2);
865 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
866 bb->id, succ_id++, block_name2);
867 }
868 }
869 }
870 fprintf(file, "\n");
871
872 if (cu_->verbose) {
873 /* Display the dominator tree */
874 GetBlockName(bb, block_name1);
875 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
876 block_name1, block_name1);
877 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700878 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800879 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
880 }
881 }
882 }
883 fprintf(file, "}\n");
884 fclose(file);
885}
886
buzbee1fd33462013-03-25 13:40:45 -0700887/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700888void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700889 if (bb->first_mir_insn == NULL) {
890 DCHECK(bb->last_mir_insn == NULL);
891 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700892 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700893 } else {
894 bb->last_mir_insn->next = mir;
buzbee1fd33462013-03-25 13:40:45 -0700895 mir->next = NULL;
896 bb->last_mir_insn = mir;
897 }
898}
899
900/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700901void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700902 if (bb->first_mir_insn == NULL) {
903 DCHECK(bb->last_mir_insn == NULL);
904 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700905 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700906 } else {
buzbee1fd33462013-03-25 13:40:45 -0700907 mir->next = bb->first_mir_insn;
buzbee1fd33462013-03-25 13:40:45 -0700908 bb->first_mir_insn = mir;
909 }
910}
911
912/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700913void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700914 new_mir->next = current_mir->next;
915 current_mir->next = new_mir;
916
buzbee0d829482013-10-11 15:24:55 -0700917 if (bb->last_mir_insn == current_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700918 /* Is the last MIR in the block */
919 bb->last_mir_insn = new_mir;
920 }
921}
922
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700923char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700924 DecodedInstruction insn = mir->dalvikInsn;
925 std::string str;
926 int flags = 0;
927 int opcode = insn.opcode;
928 char* ret;
929 bool nop = false;
930 SSARepresentation* ssa_rep = mir->ssa_rep;
931 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
932 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
933 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
934
935 // Handle special cases.
936 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
937 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
938 str.append(": ");
939 // Recover the original Dex instruction
940 insn = mir->meta.throw_insn->dalvikInsn;
941 ssa_rep = mir->meta.throw_insn->ssa_rep;
942 defs = ssa_rep->num_defs;
943 uses = ssa_rep->num_uses;
944 opcode = insn.opcode;
945 } else if (opcode == kMirOpNop) {
946 str.append("[");
buzbee0d829482013-10-11 15:24:55 -0700947 // Recover original opcode.
948 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
949 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -0700950 nop = true;
951 }
952
953 if (opcode >= kMirOpFirst) {
954 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
955 } else {
956 dalvik_format = Instruction::FormatOf(insn.opcode);
957 flags = Instruction::FlagsOf(insn.opcode);
958 str.append(Instruction::Name(insn.opcode));
959 }
960
961 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -0700962 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -0700963 str.append(StringPrintf(" %s = (%s",
964 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
965 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700966 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700967 int i;
968 for (i = 1; i < uses; i++) {
969 str.append(StringPrintf(", %s:%d",
970 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
971 incoming[i]));
972 }
973 str.append(")");
974 } else if ((flags & Instruction::kBranch) != 0) {
975 // For branches, decode the instructions to print out the branch targets.
976 int offset = 0;
977 switch (dalvik_format) {
978 case Instruction::k21t:
979 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
980 offset = insn.vB;
981 break;
982 case Instruction::k22t:
983 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
984 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
985 offset = insn.vC;
986 break;
987 case Instruction::k10t:
988 case Instruction::k20t:
989 case Instruction::k30t:
990 offset = insn.vA;
991 break;
992 default:
993 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
994 }
995 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
996 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
997 } else {
998 // For invokes-style formats, treat wide regs as a pair of singles
999 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1000 (dalvik_format == Instruction::k3rc));
1001 if (defs != 0) {
1002 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1003 if (uses != 0) {
1004 str.append(", ");
1005 }
1006 }
1007 for (int i = 0; i < uses; i++) {
1008 str.append(
1009 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1010 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1011 // For the listing, skip the high sreg.
1012 i++;
1013 }
1014 if (i != (uses -1)) {
1015 str.append(",");
1016 }
1017 }
1018 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001019 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -07001020 case Instruction::k21s:
1021 case Instruction::k31i:
1022 case Instruction::k21h:
1023 str.append(StringPrintf(", #%d", insn.vB));
1024 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001025 case Instruction::k51l: // Add one wide immediate
buzbee1fd33462013-03-25 13:40:45 -07001026 str.append(StringPrintf(", #%lld", insn.vB_wide));
1027 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001028 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001029 case Instruction::k31c:
1030 str.append(StringPrintf(", index #%d", insn.vB));
1031 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001032 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001033 str.append(StringPrintf(", index #%d", insn.vC));
1034 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001035 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001036 case Instruction::k22b:
1037 str.append(StringPrintf(", #%d", insn.vC));
1038 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001039 default: {
1040 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001041 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001042 }
buzbee1fd33462013-03-25 13:40:45 -07001043 }
1044 if (nop) {
1045 str.append("]--optimized away");
1046 }
1047 int length = str.length() + 1;
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001048 ret = static_cast<char*>(arena_->Alloc(length, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001049 strncpy(ret, str.c_str(), length);
1050 return ret;
1051}
1052
1053/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001054void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001055 static const struct { const char before; const char after; } match[] = {
1056 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1057 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1058 };
buzbee1fd33462013-03-25 13:40:45 -07001059 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1060 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1061 }
1062}
1063
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001064std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001065 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1066 // the arena. We should be smarter and just place straight into the arena, or compute the
1067 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001068 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1069}
1070
1071// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001072std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001073 if (reg_location_ == NULL) {
1074 // Pre-SSA - just use the standard name
1075 return GetSSAName(ssa_reg);
1076 }
1077 if (IsConst(reg_location_[ssa_reg])) {
1078 if (!singles_only && reg_location_[ssa_reg].wide) {
1079 return StringPrintf("v%d_%d#0x%llx", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
1080 ConstantValueWide(reg_location_[ssa_reg]));
1081 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001082 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001083 ConstantValue(reg_location_[ssa_reg]));
1084 }
1085 } else {
1086 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1087 }
1088}
1089
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001090void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001091 switch (bb->block_type) {
1092 case kEntryBlock:
1093 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1094 break;
1095 case kExitBlock:
1096 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1097 break;
1098 case kDalvikByteCode:
1099 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1100 break;
1101 case kExceptionHandling:
1102 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1103 bb->id);
1104 break;
1105 default:
1106 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1107 break;
1108 }
1109}
1110
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001111const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001112 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001113 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1114 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1115}
1116
1117/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001118void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001119 BasicBlock* bb;
1120 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001121 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001122 "Entry Block",
1123 "Code Block",
1124 "Exit Block",
1125 "Exception Handling",
1126 "Catch Block"
1127 };
1128
1129 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1130 LOG(INFO) << cu_->insns << " insns";
1131 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001132 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001133
1134 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001135 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001136 if (bb == NULL) break;
1137 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1138 bb->id,
1139 block_type_names[bb->block_type],
1140 bb->start_offset,
1141 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1142 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001143 if (bb->taken != NullBasicBlockId) {
1144 LOG(INFO) << " Taken branch: block " << bb->taken
1145 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001146 }
buzbee0d829482013-10-11 15:24:55 -07001147 if (bb->fall_through != NullBasicBlockId) {
1148 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1149 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001150 }
1151 }
1152}
1153
1154/*
1155 * Build an array of location records for the incoming arguments.
1156 * Note: one location record per word of arguments, with dummy
1157 * high-word loc for wide arguments. Also pull up any following
1158 * MOVE_RESULT and incorporate it into the invoke.
1159 */
1160CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001161 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001162 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
1163 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001164 MIR* move_result_mir = FindMoveResult(bb, mir);
1165 if (move_result_mir == NULL) {
1166 info->result.location = kLocInvalid;
1167 } else {
1168 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001169 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1170 }
1171 info->num_arg_words = mir->ssa_rep->num_uses;
1172 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001173 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001174 for (int i = 0; i < info->num_arg_words; i++) {
1175 info->args[i] = GetRawSrc(mir, i);
1176 }
1177 info->opt_flags = mir->optimization_flags;
1178 info->type = type;
1179 info->is_range = is_range;
1180 info->index = mir->dalvikInsn.vB;
1181 info->offset = mir->offset;
1182 return info;
1183}
1184
buzbee862a7602013-04-05 10:58:54 -07001185// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001186BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001187 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
1188 ArenaAllocator::kAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001189 bb->block_type = block_type;
1190 bb->id = block_id;
1191 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001192 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001193 (block_type == kExitBlock) ? 2048 : 2,
1194 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001195 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001196 block_id_map_.Put(block_id, block_id);
1197 return bb;
1198}
buzbee1fd33462013-03-25 13:40:45 -07001199
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001200} // namespace art