blob: e4550d1e6045e3a1866de7e67b6ecc0371e38919 [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
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
20
Ian Rogers6282dc12013-04-18 15:54:02 -070021#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080022#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "dex_file-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000024#include "dex/quick/dex_file_to_method_inliner_map.h"
25#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000026#include "leb128.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000027
buzbee311ca162013-02-28 15:56:43 -080028namespace art {
29
30#define MAX_PATTERN_LEN 5
31
buzbee1fd33462013-03-25 13:40:45 -070032const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
33 "Phi",
34 "Copy",
35 "FusedCmplFloat",
36 "FusedCmpgFloat",
37 "FusedCmplDouble",
38 "FusedCmpgDouble",
39 "FusedCmpLong",
40 "Nop",
41 "OpNullCheck",
42 "OpRangeCheck",
43 "OpDivZeroCheck",
44 "Check1",
45 "Check2",
46 "Select",
47};
48
buzbee862a7602013-04-05 10:58:54 -070049MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070050 : reg_location_(NULL),
51 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080052 ssa_base_vregs_(NULL),
53 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080054 vreg_to_ssa_map_(NULL),
55 ssa_last_defs_(NULL),
56 is_constant_v_(NULL),
57 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070058 use_counts_(arena, 256, kGrowableArrayMisc),
59 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080060 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070061 dfs_order_(NULL),
62 dfs_post_order_(NULL),
63 dom_post_order_traversal_(NULL),
buzbee311ca162013-02-28 15:56:43 -080064 i_dom_list_(NULL),
65 def_block_matrix_(NULL),
66 temp_block_v_(NULL),
67 temp_dalvik_register_v_(NULL),
68 temp_ssa_register_v_(NULL),
buzbee862a7602013-04-05 10:58:54 -070069 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080070 try_block_addr_(NULL),
71 entry_block_(NULL),
72 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080073 num_blocks_(0),
74 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070075 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080076 current_method_(kInvalidEntry),
77 current_offset_(kInvalidEntry),
78 def_count_(0),
79 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070080 num_ssa_regs_(0),
81 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -070082 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
83 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070084 arena_(arena),
85 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -080086 forward_branches_(0),
87 compiler_temps_(arena, 6, kGrowableArrayMisc),
88 num_non_special_compiler_temps_(0),
Ian Rogers9c86a022014-02-21 16:40:21 +000089 max_available_non_special_compiler_temps_(0) {
buzbee862a7602013-04-05 10:58:54 -070090 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -080091 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
92 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -080093}
94
Ian Rogers6282dc12013-04-18 15:54:02 -070095MIRGraph::~MIRGraph() {
96 STLDeleteElements(&m_units_);
97}
98
buzbee311ca162013-02-28 15:56:43 -080099/*
100 * Parse an instruction, return the length of the instruction
101 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700102int MIRGraph::ParseInsn(const uint16_t* code_ptr, DecodedInstruction* decoded_instruction) {
buzbee311ca162013-02-28 15:56:43 -0800103 const Instruction* instruction = Instruction::At(code_ptr);
104 *decoded_instruction = DecodedInstruction(instruction);
105
106 return instruction->SizeInCodeUnits();
107}
108
109
110/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700111BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700112 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700113 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800114 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700115 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800116 while (insn) {
117 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700118 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800119 insn = insn->next;
120 }
121 if (insn == NULL) {
122 LOG(FATAL) << "Break split failed";
123 }
buzbee862a7602013-04-05 10:58:54 -0700124 BasicBlock *bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
125 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800126
127 bottom_block->start_offset = code_offset;
128 bottom_block->first_mir_insn = insn;
129 bottom_block->last_mir_insn = orig_block->last_mir_insn;
130
131 /* If this block was terminated by a return, the flag needs to go with the bottom block */
132 bottom_block->terminated_by_return = orig_block->terminated_by_return;
133 orig_block->terminated_by_return = false;
134
buzbee311ca162013-02-28 15:56:43 -0800135 /* Handle the taken path */
136 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700137 if (bottom_block->taken != NullBasicBlockId) {
138 orig_block->taken = NullBasicBlockId;
139 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
140 bb_taken->predecessors->Delete(orig_block->id);
141 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800142 }
143
144 /* Handle the fallthrough path */
145 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700146 orig_block->fall_through = bottom_block->id;
147 bottom_block->predecessors->Insert(orig_block->id);
148 if (bottom_block->fall_through != NullBasicBlockId) {
149 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
150 bb_fall_through->predecessors->Delete(orig_block->id);
151 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800152 }
153
154 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700155 if (orig_block->successor_block_list_type != kNotUsed) {
156 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
157 bottom_block->successor_blocks = orig_block->successor_blocks;
158 orig_block->successor_block_list_type = kNotUsed;
159 orig_block->successor_blocks = NULL;
160 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800161 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700162 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800163 if (successor_block_info == NULL) break;
buzbee0d829482013-10-11 15:24:55 -0700164 BasicBlock *bb = GetBasicBlock(successor_block_info->block);
165 bb->predecessors->Delete(orig_block->id);
166 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800167 }
168 }
169
buzbee0d829482013-10-11 15:24:55 -0700170 orig_block->last_mir_insn = prev;
171 prev->next = NULL;
buzbee311ca162013-02-28 15:56:43 -0800172
buzbee311ca162013-02-28 15:56:43 -0800173 /*
174 * Update the immediate predecessor block pointer so that outgoing edges
175 * can be applied to the proper block.
176 */
177 if (immed_pred_block_p) {
178 DCHECK_EQ(*immed_pred_block_p, orig_block);
179 *immed_pred_block_p = bottom_block;
180 }
buzbeeb48819d2013-09-14 16:15:25 -0700181
182 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000183 DCHECK(insn != nullptr);
184 DCHECK(insn != orig_block->first_mir_insn);
185 DCHECK(insn == bottom_block->first_mir_insn);
186 DCHECK_EQ(insn->offset, bottom_block->start_offset);
187 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
188 !IsPseudoMirOp(insn->dalvikInsn.opcode));
189 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
190 MIR* p = insn;
191 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
192 while (p != bottom_block->last_mir_insn) {
193 p = p->next;
194 DCHECK(p != nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700195 int opcode = p->dalvikInsn.opcode;
196 /*
197 * Some messiness here to ensure that we only enter real opcodes and only the
198 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000199 * CHECK and work portions. Since the 2nd half of a split operation is always
200 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700201 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000202 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
203 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700204 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
205 }
buzbeeb48819d2013-09-14 16:15:25 -0700206 }
207
buzbee311ca162013-02-28 15:56:43 -0800208 return bottom_block;
209}
210
211/*
212 * Given a code offset, find out the block that starts with it. If the offset
213 * is in the middle of an existing block, split it into two. If immed_pred_block_p
214 * is not non-null and is the block being split, update *immed_pred_block_p to
215 * point to the bottom block so that outgoing edges can be set up properly
216 * (by the caller)
217 * Utilizes a map for fast lookup of the typical cases.
218 */
buzbee0d829482013-10-11 15:24:55 -0700219BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700220 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700221 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800222 return NULL;
223 }
buzbeeb48819d2013-09-14 16:15:25 -0700224
225 int block_id = dex_pc_to_block_map_.Get(code_offset);
226 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
227
228 if ((bb != NULL) && (bb->start_offset == code_offset)) {
229 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700230 return bb;
231 }
buzbee311ca162013-02-28 15:56:43 -0800232
buzbeeb48819d2013-09-14 16:15:25 -0700233 // No direct hit.
234 if (!create) {
235 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800236 }
237
buzbeeb48819d2013-09-14 16:15:25 -0700238 if (bb != NULL) {
239 // The target exists somewhere in an existing block.
240 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
241 }
242
243 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700244 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
245 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800246 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700247 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800248 return bb;
249}
250
buzbeeb48819d2013-09-14 16:15:25 -0700251
buzbee311ca162013-02-28 15:56:43 -0800252/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700253void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800254 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700255 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800256
257 if (tries_size == 0) {
258 return;
259 }
260
261 for (int i = 0; i < tries_size; i++) {
262 const DexFile::TryItem* pTry =
263 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700264 DexOffset start_offset = pTry->start_addr_;
265 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800266 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700267 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800268 }
269 }
270
271 // Iterate over each of the handlers to enqueue the empty Catch blocks
272 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
273 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
274 for (uint32_t idx = 0; idx < handlers_size; idx++) {
275 CatchHandlerIterator iterator(handlers_ptr);
276 for (; iterator.HasNext(); iterator.Next()) {
277 uint32_t address = iterator.GetHandlerAddress();
278 FindBlock(address, false /* split */, true /*create*/,
279 /* immed_pred_block_p */ NULL);
280 }
281 handlers_ptr = iterator.EndDataPointer();
282 }
283}
284
285/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700286BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
287 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700288 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700289 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800290 switch (insn->dalvikInsn.opcode) {
291 case Instruction::GOTO:
292 case Instruction::GOTO_16:
293 case Instruction::GOTO_32:
294 target += insn->dalvikInsn.vA;
295 break;
296 case Instruction::IF_EQ:
297 case Instruction::IF_NE:
298 case Instruction::IF_LT:
299 case Instruction::IF_GE:
300 case Instruction::IF_GT:
301 case Instruction::IF_LE:
302 cur_block->conditional_branch = true;
303 target += insn->dalvikInsn.vC;
304 break;
305 case Instruction::IF_EQZ:
306 case Instruction::IF_NEZ:
307 case Instruction::IF_LTZ:
308 case Instruction::IF_GEZ:
309 case Instruction::IF_GTZ:
310 case Instruction::IF_LEZ:
311 cur_block->conditional_branch = true;
312 target += insn->dalvikInsn.vB;
313 break;
314 default:
315 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
316 }
buzbeeb48819d2013-09-14 16:15:25 -0700317 CountBranch(target);
buzbee311ca162013-02-28 15:56:43 -0800318 BasicBlock *taken_block = FindBlock(target, /* split */ true, /* create */ true,
319 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700320 cur_block->taken = taken_block->id;
321 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800322
323 /* Always terminate the current block for conditional branches */
324 if (flags & Instruction::kContinue) {
325 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
326 /*
327 * If the method is processed
328 * in sequential order from the
329 * beginning, we don't need to
330 * specify split for continue
331 * blocks. However, this
332 * routine can be called by
333 * compileLoop, which starts
334 * parsing the method from an
335 * arbitrary address in the
336 * method body.
337 */
338 true,
339 /* create */
340 true,
341 /* immed_pred_block_p */
342 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700343 cur_block->fall_through = fallthrough_block->id;
344 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800345 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700346 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800347 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800348 }
349 return cur_block;
350}
351
352/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800353BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
354 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800355 const uint16_t* switch_data =
356 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
357 int size;
358 const int* keyTable;
359 const int* target_table;
360 int i;
361 int first_key;
362
363 /*
364 * Packed switch data format:
365 * ushort ident = 0x0100 magic value
366 * ushort size number of entries in the table
367 * int first_key first (and lowest) switch case value
368 * int targets[size] branch targets, relative to switch opcode
369 *
370 * Total size is (4+size*2) 16-bit code units.
371 */
372 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
373 DCHECK_EQ(static_cast<int>(switch_data[0]),
374 static_cast<int>(Instruction::kPackedSwitchSignature));
375 size = switch_data[1];
376 first_key = switch_data[2] | (switch_data[3] << 16);
377 target_table = reinterpret_cast<const int*>(&switch_data[4]);
378 keyTable = NULL; // Make the compiler happy
379 /*
380 * Sparse switch data format:
381 * ushort ident = 0x0200 magic value
382 * ushort size number of entries in the table; > 0
383 * int keys[size] keys, sorted low-to-high; 32-bit aligned
384 * int targets[size] branch targets, relative to switch opcode
385 *
386 * Total size is (2+size*4) 16-bit code units.
387 */
388 } else {
389 DCHECK_EQ(static_cast<int>(switch_data[0]),
390 static_cast<int>(Instruction::kSparseSwitchSignature));
391 size = switch_data[1];
392 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
393 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
394 first_key = 0; // To make the compiler happy
395 }
396
buzbee0d829482013-10-11 15:24:55 -0700397 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800398 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700399 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800400 }
buzbee0d829482013-10-11 15:24:55 -0700401 cur_block->successor_block_list_type =
402 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
403 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700404 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800405
406 for (i = 0; i < size; i++) {
407 BasicBlock *case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
408 /* create */ true, /* immed_pred_block_p */ &cur_block);
409 SuccessorBlockInfo *successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700410 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
411 ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700412 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800413 successor_block_info->key =
414 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
415 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700416 cur_block->successor_blocks->Insert(successor_block_info);
417 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800418 }
419
420 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700421 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
422 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700423 cur_block->fall_through = fallthrough_block->id;
424 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800425 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800426}
427
428/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700429BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
430 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700431 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700432 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800433 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
434 bool build_all_edges =
435 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800436
437 /* In try block */
438 if (in_try_block) {
439 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
440
buzbee0d829482013-10-11 15:24:55 -0700441 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800442 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
443 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700444 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800445 }
446
buzbee0d829482013-10-11 15:24:55 -0700447 cur_block->successor_block_list_type = kCatch;
448 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700449 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800450
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700451 for (; iterator.HasNext(); iterator.Next()) {
buzbee311ca162013-02-28 15:56:43 -0800452 BasicBlock *catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
453 false /* creat */, NULL /* immed_pred_block_p */);
454 catch_block->catch_entry = true;
455 if (kIsDebugBuild) {
456 catches_.insert(catch_block->start_offset);
457 }
458 SuccessorBlockInfo *successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700459 (arena_->Alloc(sizeof(SuccessorBlockInfo), ArenaAllocator::kAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700460 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800461 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700462 cur_block->successor_blocks->Insert(successor_block_info);
463 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800464 }
buzbee17189ac2013-11-08 11:07:02 -0800465 } else if (build_all_edges) {
buzbee862a7602013-04-05 10:58:54 -0700466 BasicBlock *eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700467 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700468 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800469 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700470 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800471 }
472
buzbee17189ac2013-11-08 11:07:02 -0800473 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800474 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700475 if (code_ptr < code_end) {
buzbee311ca162013-02-28 15:56:43 -0800476 // Force creation of new block following THROW via side-effect
477 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
478 /* immed_pred_block_p */ NULL);
479 }
480 if (!in_try_block) {
481 // Don't split a THROW that can't rethrow - we're done.
482 return cur_block;
483 }
484 }
485
buzbee17189ac2013-11-08 11:07:02 -0800486 if (!build_all_edges) {
487 /*
488 * Even though there is an exception edge here, control cannot return to this
489 * method. Thus, for the purposes of dataflow analysis and optimization, we can
490 * ignore the edge. Doing this reduces compile time, and increases the scope
491 * of the basic-block level optimization pass.
492 */
493 return cur_block;
494 }
495
buzbee311ca162013-02-28 15:56:43 -0800496 /*
497 * Split the potentially-throwing instruction into two parts.
498 * The first half will be a pseudo-op that captures the exception
499 * edges and terminates the basic block. It always falls through.
500 * Then, create a new basic block that begins with the throwing instruction
501 * (minus exceptions). Note: this new basic block must NOT be entered into
502 * the block_map. If the potentially-throwing instruction is the target of a
503 * future branch, we need to find the check psuedo half. The new
504 * basic block containing the work portion of the instruction should
505 * only be entered via fallthrough from the block containing the
506 * pseudo exception edge MIR. Note also that this new block is
507 * not automatically terminated after the work portion, and may
508 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700509 *
510 * Note also that the dex_pc_to_block_map_ entry for the potentially
511 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800512 */
buzbee862a7602013-04-05 10:58:54 -0700513 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
514 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800515 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700516 cur_block->fall_through = new_block->id;
517 new_block->predecessors->Insert(cur_block->id);
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700518 MIR* new_insn = static_cast<MIR*>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800519 *new_insn = *insn;
520 insn->dalvikInsn.opcode =
521 static_cast<Instruction::Code>(kMirOpCheck);
522 // Associate the two halves
523 insn->meta.throw_insn = new_insn;
buzbee311ca162013-02-28 15:56:43 -0800524 AppendMIR(new_block, new_insn);
525 return new_block;
526}
527
528/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
529void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700530 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700531 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800532 current_code_item_ = code_item;
533 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
534 current_method_ = m_units_.size();
535 current_offset_ = 0;
536 // TODO: will need to snapshot stack image and use that as the mir context identification.
537 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000538 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
539 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800540 const uint16_t* code_ptr = current_code_item_->insns_;
541 const uint16_t* code_end =
542 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
543
544 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700545 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700546 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700547 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 -0700548
buzbee311ca162013-02-28 15:56:43 -0800549 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700550 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
551 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800552
553 // If this is the first method, set up default entry and exit blocks.
554 if (current_method_ == 0) {
555 DCHECK(entry_block_ == NULL);
556 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700557 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700558 // Use id 0 to represent a null block.
559 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
560 DCHECK_EQ(null_block->id, NullBasicBlockId);
561 null_block->hidden = true;
562 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700563 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700564 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700565 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700566 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800567 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
568 cu_->dex_file = &dex_file;
569 cu_->class_def_idx = class_def_idx;
570 cu_->method_idx = method_idx;
571 cu_->access_flags = access_flags;
572 cu_->invoke_type = invoke_type;
573 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
574 cu_->num_ins = current_code_item_->ins_size_;
575 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
576 cu_->num_outs = current_code_item_->outs_size_;
577 cu_->num_dalvik_registers = current_code_item_->registers_size_;
578 cu_->insns = current_code_item_->insns_;
579 cu_->code_item = current_code_item_;
580 } else {
581 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
582 /*
583 * Will need to manage storage for ins & outs, push prevous state and update
584 * insert point.
585 */
586 }
587
588 /* Current block to record parsed instructions */
buzbee862a7602013-04-05 10:58:54 -0700589 BasicBlock *cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700590 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800591 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700592 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700593 // TODO: for inlining support, insert at the insert point rather than entry block.
594 entry_block_->fall_through = cur_block->id;
595 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800596
597 /* Identify code range in try blocks and set up the empty catch blocks */
598 ProcessTryCatchBlocks();
599
buzbee311ca162013-02-28 15:56:43 -0800600 /* Parse all instructions and put them into containing basic blocks */
601 while (code_ptr < code_end) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700602 MIR *insn = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), ArenaAllocator::kAllocMIR));
buzbee311ca162013-02-28 15:56:43 -0800603 insn->offset = current_offset_;
604 insn->m_unit_index = current_method_;
605 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
606 insn->width = width;
607 Instruction::Code opcode = insn->dalvikInsn.opcode;
608 if (opcode_count_ != NULL) {
609 opcode_count_[static_cast<int>(opcode)]++;
610 }
611
buzbee311ca162013-02-28 15:56:43 -0800612 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
613
buzbee1da1e2f2013-11-15 13:37:01 -0800614 uint64_t df_flags = oat_data_flow_attributes_[insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800615
616 if (df_flags & DF_HAS_DEFS) {
617 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
618 }
619
buzbee1da1e2f2013-11-15 13:37:01 -0800620 if (df_flags & DF_LVN) {
621 cur_block->use_lvn = true; // Run local value numbering on this basic block.
622 }
623
buzbee27247762013-07-28 12:03:58 -0700624 // Check for inline data block signatures
625 if (opcode == Instruction::NOP) {
626 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
627 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
628 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
629 uint16_t following_raw_instruction = code_ptr[1];
630 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
631 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
632 (following_raw_instruction == Instruction::kArrayDataSignature)) {
633 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
634 }
635 }
636 if (width == 1) {
637 // It is a simple nop - treat normally.
638 AppendMIR(cur_block, insn);
639 } else {
buzbee0d829482013-10-11 15:24:55 -0700640 DCHECK(cur_block->fall_through == NullBasicBlockId);
641 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700642 // Unreachable instruction, mark for no continuation.
643 flags &= ~Instruction::kContinue;
644 }
645 } else {
646 AppendMIR(cur_block, insn);
647 }
648
buzbeeb48819d2013-09-14 16:15:25 -0700649 // Associate the starting dex_pc for this opcode with its containing basic block.
650 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
651
buzbee27247762013-07-28 12:03:58 -0700652 code_ptr += width;
653
buzbee311ca162013-02-28 15:56:43 -0800654 if (flags & Instruction::kBranch) {
655 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
656 width, flags, code_ptr, code_end);
657 } else if (flags & Instruction::kReturn) {
658 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700659 cur_block->fall_through = exit_block_->id;
660 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800661 /*
662 * Terminate the current block if there are instructions
663 * afterwards.
664 */
665 if (code_ptr < code_end) {
666 /*
667 * Create a fallthrough block for real instructions
668 * (incl. NOP).
669 */
buzbee27247762013-07-28 12:03:58 -0700670 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
671 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800672 }
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) {
buzbee17189ac2013-11-08 11:07:02 -0800677 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800678 }
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 */
buzbee0d829482013-10-11 15:24:55 -0700689 DCHECK(cur_block->fall_through == NullBasicBlockId ||
690 GetBasicBlock(cur_block->fall_through) == next_block ||
691 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800692
buzbee0d829482013-10-11 15:24:55 -0700693 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
694 cur_block->fall_through = next_block->id;
695 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800696 }
697 cur_block = next_block;
698 }
699 }
Vladimir Marko5816ed42013-11-27 17:04:20 +0000700
buzbee311ca162013-02-28 15:56:43 -0800701 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
702 DumpCFG("/sdcard/1_post_parse_cfg/", true);
703 }
704
705 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700706 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800707 }
708}
709
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700710void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800711 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 */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800723void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800724 FILE* file;
725 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
726 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800727 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
728 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
729 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800730 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
buzbee0d829482013-10-11 15:24:55 -0700776 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800777 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700778 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800779 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
780 block_name1, block_name2);
781 }
buzbee0d829482013-10-11 15:24:55 -0700782 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800783 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700784 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800785 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
786 }
787
buzbee0d829482013-10-11 15:24:55 -0700788 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800789 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
790 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700791 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
792 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
buzbee862a7602013-04-05 10:58:54 -0700793 SuccessorBlockInfo *successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800794
795 int succ_id = 0;
796 while (true) {
797 if (successor_block_info == NULL) break;
798
buzbee0d829482013-10-11 15:24:55 -0700799 BasicBlock *dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700800 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800801
802 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
803 succ_id++,
804 successor_block_info->key,
805 dest_block->start_offset,
806 (next_successor_block_info != NULL) ? " | " : " ");
807
808 successor_block_info = next_successor_block_info;
809 }
810 fprintf(file, " }\"];\n\n");
811
812 GetBlockName(bb, block_name1);
813 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
814 block_name1, bb->start_offset, bb->id);
815
buzbee0d829482013-10-11 15:24:55 -0700816 if (bb->successor_block_list_type == kPackedSwitch ||
817 bb->successor_block_list_type == kSparseSwitch) {
818 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800819
820 succ_id = 0;
821 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700822 SuccessorBlockInfo *successor_block_info = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800823 if (successor_block_info == NULL) break;
824
buzbee0d829482013-10-11 15:24:55 -0700825 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800826
827 GetBlockName(dest_block, block_name2);
828 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
829 bb->id, succ_id++, block_name2);
830 }
831 }
832 }
833 fprintf(file, "\n");
834
835 if (cu_->verbose) {
836 /* Display the dominator tree */
837 GetBlockName(bb, block_name1);
838 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
839 block_name1, block_name1);
840 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700841 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800842 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
843 }
844 }
845 }
846 fprintf(file, "}\n");
847 fclose(file);
848}
849
buzbee1fd33462013-03-25 13:40:45 -0700850/* Insert an MIR instruction to the end of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700851void MIRGraph::AppendMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700852 if (bb->first_mir_insn == NULL) {
853 DCHECK(bb->last_mir_insn == NULL);
854 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700855 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700856 } else {
857 bb->last_mir_insn->next = mir;
buzbee1fd33462013-03-25 13:40:45 -0700858 mir->next = NULL;
859 bb->last_mir_insn = mir;
860 }
861}
862
863/* Insert an MIR instruction to the head of a basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700864void MIRGraph::PrependMIR(BasicBlock* bb, MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700865 if (bb->first_mir_insn == NULL) {
866 DCHECK(bb->last_mir_insn == NULL);
867 bb->last_mir_insn = bb->first_mir_insn = mir;
buzbee0d829482013-10-11 15:24:55 -0700868 mir->next = NULL;
buzbee1fd33462013-03-25 13:40:45 -0700869 } else {
buzbee1fd33462013-03-25 13:40:45 -0700870 mir->next = bb->first_mir_insn;
buzbee1fd33462013-03-25 13:40:45 -0700871 bb->first_mir_insn = mir;
872 }
873}
874
875/* Insert a MIR instruction after the specified MIR */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700876void MIRGraph::InsertMIRAfter(BasicBlock* bb, MIR* current_mir, MIR* new_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700877 new_mir->next = current_mir->next;
878 current_mir->next = new_mir;
879
buzbee0d829482013-10-11 15:24:55 -0700880 if (bb->last_mir_insn == current_mir) {
buzbee1fd33462013-03-25 13:40:45 -0700881 /* Is the last MIR in the block */
882 bb->last_mir_insn = new_mir;
883 }
884}
885
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -0800886MIR* MIRGraph::GetNextUnconditionalMir(BasicBlock* bb, MIR* current) {
887 MIR* next_mir = nullptr;
888
889 if (current != nullptr) {
890 next_mir = current->next;
891 }
892
893 if (next_mir == nullptr) {
894 // Only look for next MIR that follows unconditionally.
895 if ((bb->taken == NullBasicBlockId) && (bb->fall_through != NullBasicBlockId)) {
896 next_mir = GetBasicBlock(bb->fall_through)->first_mir_insn;
897 }
898 }
899
900 return next_mir;
901}
902
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700903char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
buzbee1fd33462013-03-25 13:40:45 -0700904 DecodedInstruction insn = mir->dalvikInsn;
905 std::string str;
906 int flags = 0;
907 int opcode = insn.opcode;
908 char* ret;
909 bool nop = false;
910 SSARepresentation* ssa_rep = mir->ssa_rep;
911 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format
912 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
913 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
914
915 // Handle special cases.
916 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
917 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
918 str.append(": ");
919 // Recover the original Dex instruction
920 insn = mir->meta.throw_insn->dalvikInsn;
921 ssa_rep = mir->meta.throw_insn->ssa_rep;
922 defs = ssa_rep->num_defs;
923 uses = ssa_rep->num_uses;
924 opcode = insn.opcode;
925 } else if (opcode == kMirOpNop) {
926 str.append("[");
buzbee0d829482013-10-11 15:24:55 -0700927 // Recover original opcode.
928 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
929 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -0700930 nop = true;
931 }
932
933 if (opcode >= kMirOpFirst) {
934 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
935 } else {
936 dalvik_format = Instruction::FormatOf(insn.opcode);
937 flags = Instruction::FlagsOf(insn.opcode);
938 str.append(Instruction::Name(insn.opcode));
939 }
940
941 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -0700942 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -0700943 str.append(StringPrintf(" %s = (%s",
944 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
945 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -0700946 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -0700947 int i;
948 for (i = 1; i < uses; i++) {
949 str.append(StringPrintf(", %s:%d",
950 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
951 incoming[i]));
952 }
953 str.append(")");
954 } else if ((flags & Instruction::kBranch) != 0) {
955 // For branches, decode the instructions to print out the branch targets.
956 int offset = 0;
957 switch (dalvik_format) {
958 case Instruction::k21t:
959 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
960 offset = insn.vB;
961 break;
962 case Instruction::k22t:
963 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
964 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
965 offset = insn.vC;
966 break;
967 case Instruction::k10t:
968 case Instruction::k20t:
969 case Instruction::k30t:
970 offset = insn.vA;
971 break;
972 default:
973 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
974 }
975 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
976 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
977 } else {
978 // For invokes-style formats, treat wide regs as a pair of singles
979 bool show_singles = ((dalvik_format == Instruction::k35c) ||
980 (dalvik_format == Instruction::k3rc));
981 if (defs != 0) {
982 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
983 if (uses != 0) {
984 str.append(", ");
985 }
986 }
987 for (int i = 0; i < uses; i++) {
988 str.append(
989 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
990 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
991 // For the listing, skip the high sreg.
992 i++;
993 }
994 if (i != (uses -1)) {
995 str.append(",");
996 }
997 }
998 switch (dalvik_format) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700999 case Instruction::k11n: // Add one immediate from vB
buzbee1fd33462013-03-25 13:40:45 -07001000 case Instruction::k21s:
1001 case Instruction::k31i:
1002 case Instruction::k21h:
1003 str.append(StringPrintf(", #%d", insn.vB));
1004 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001005 case Instruction::k51l: // Add one wide immediate
Ian Rogers23b03b52014-01-24 11:10:03 -08001006 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001007 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001008 case Instruction::k21c: // One register, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001009 case Instruction::k31c:
1010 str.append(StringPrintf(", index #%d", insn.vB));
1011 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001012 case Instruction::k22c: // Two registers, one string/type/method index
buzbee1fd33462013-03-25 13:40:45 -07001013 str.append(StringPrintf(", index #%d", insn.vC));
1014 break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001015 case Instruction::k22s: // Add one immediate from vC
buzbee1fd33462013-03-25 13:40:45 -07001016 case Instruction::k22b:
1017 str.append(StringPrintf(", #%d", insn.vC));
1018 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001019 default: {
1020 // Nothing left to print
buzbee1fd33462013-03-25 13:40:45 -07001021 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001022 }
buzbee1fd33462013-03-25 13:40:45 -07001023 }
1024 if (nop) {
1025 str.append("]--optimized away");
1026 }
1027 int length = str.length() + 1;
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001028 ret = static_cast<char*>(arena_->Alloc(length, ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001029 strncpy(ret, str.c_str(), length);
1030 return ret;
1031}
1032
1033/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001034void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001035 static const struct { const char before; const char after; } match[] = {
1036 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1037 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1038 };
buzbee1fd33462013-03-25 13:40:45 -07001039 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1040 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1041 }
1042}
1043
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001044std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001045 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1046 // the arena. We should be smarter and just place straight into the arena, or compute the
1047 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001048 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1049}
1050
1051// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001052std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001053 if (reg_location_ == NULL) {
1054 // Pre-SSA - just use the standard name
1055 return GetSSAName(ssa_reg);
1056 }
1057 if (IsConst(reg_location_[ssa_reg])) {
1058 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001059 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001060 ConstantValueWide(reg_location_[ssa_reg]));
1061 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001062 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001063 ConstantValue(reg_location_[ssa_reg]));
1064 }
1065 } else {
1066 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1067 }
1068}
1069
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001070void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001071 switch (bb->block_type) {
1072 case kEntryBlock:
1073 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1074 break;
1075 case kExitBlock:
1076 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1077 break;
1078 case kDalvikByteCode:
1079 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1080 break;
1081 case kExceptionHandling:
1082 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1083 bb->id);
1084 break;
1085 default:
1086 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1087 break;
1088 }
1089}
1090
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001091const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001092 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001093 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1094 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1095}
1096
1097/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001098void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001099 BasicBlock* bb;
1100 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001101 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001102 "Entry Block",
1103 "Code Block",
1104 "Exit Block",
1105 "Exception Handling",
1106 "Catch Block"
1107 };
1108
1109 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1110 LOG(INFO) << cu_->insns << " insns";
1111 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001112 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001113
1114 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001115 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001116 if (bb == NULL) break;
1117 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1118 bb->id,
1119 block_type_names[bb->block_type],
1120 bb->start_offset,
1121 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1122 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001123 if (bb->taken != NullBasicBlockId) {
1124 LOG(INFO) << " Taken branch: block " << bb->taken
1125 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001126 }
buzbee0d829482013-10-11 15:24:55 -07001127 if (bb->fall_through != NullBasicBlockId) {
1128 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1129 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001130 }
1131 }
1132}
1133
1134/*
1135 * Build an array of location records for the incoming arguments.
1136 * Note: one location record per word of arguments, with dummy
1137 * high-word loc for wide arguments. Also pull up any following
1138 * MOVE_RESULT and incorporate it into the invoke.
1139 */
1140CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001141 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001142 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
1143 ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001144 MIR* move_result_mir = FindMoveResult(bb, mir);
1145 if (move_result_mir == NULL) {
1146 info->result.location = kLocInvalid;
1147 } else {
1148 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001149 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*>
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001153 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, ArenaAllocator::kAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001154 for (int i = 0; i < info->num_arg_words; i++) {
1155 info->args[i] = GetRawSrc(mir, i);
1156 }
1157 info->opt_flags = mir->optimization_flags;
1158 info->type = type;
1159 info->is_range = is_range;
1160 info->index = mir->dalvikInsn.vB;
1161 info->offset = mir->offset;
1162 return info;
1163}
1164
buzbee862a7602013-04-05 10:58:54 -07001165// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001166BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001167 BasicBlock* bb = static_cast<BasicBlock*>(arena_->Alloc(sizeof(BasicBlock),
1168 ArenaAllocator::kAllocBB));
buzbee862a7602013-04-05 10:58:54 -07001169 bb->block_type = block_type;
1170 bb->id = block_id;
1171 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001172 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001173 (block_type == kExitBlock) ? 2048 : 2,
1174 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001175 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001176 block_id_map_.Put(block_id, block_id);
1177 return bb;
1178}
buzbee1fd33462013-03-25 13:40:45 -07001179
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001180void MIRGraph::InitializeConstantPropagation() {
1181 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
1182 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), ArenaAllocator::kAllocDFInfo));
1183}
1184
1185void MIRGraph::InitializeMethodUses() {
1186 // The gate starts by initializing the use counts
1187 int num_ssa_regs = GetNumSSARegs();
1188 use_counts_.Resize(num_ssa_regs + 32);
1189 raw_use_counts_.Resize(num_ssa_regs + 32);
1190 // Initialize list
1191 for (int i = 0; i < num_ssa_regs; i++) {
1192 use_counts_.Insert(0);
1193 raw_use_counts_.Insert(0);
1194 }
1195}
1196
1197void MIRGraph::InitializeSSATransformation() {
1198 /* Compute the DFS order */
1199 ComputeDFSOrders();
1200
1201 /* Compute the dominator info */
1202 ComputeDominators();
1203
1204 /* Allocate data structures in preparation for SSA conversion */
1205 CompilerInitializeSSAConversion();
1206
1207 /* Find out the "Dalvik reg def x block" relation */
1208 ComputeDefBlockMatrix();
1209
1210 /* Insert phi nodes to dominance frontiers for all variables */
1211 InsertPhiNodes();
1212
1213 /* Rename register names by local defs and phi nodes */
1214 ClearAllVisitedFlags();
1215 DoDFSPreOrderSSARename(GetEntryBlock());
1216
1217 /*
1218 * Shared temp bit vector used by each block to count the number of defs
1219 * from all the predecessor blocks.
1220 */
1221 temp_ssa_register_v_ =
1222 new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false, kBitMapTempSSARegisterV);
1223}
1224
1225void MIRGraph::CheckSSARegisterVector() {
1226 DCHECK(temp_ssa_register_v_ != nullptr);
1227}
1228
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001229} // namespace art