blob: 71bb2c6166afe36d81bebe42b49c8df201ca85f0 [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>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogers6282dc12013-04-18 15:54:02 -070022#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070025#include "dex_instruction-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000026#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000028#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070029#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010030#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000031
buzbee311ca162013-02-28 15:56:43 -080032namespace art {
33
34#define MAX_PATTERN_LEN 5
35
buzbee1fd33462013-03-25 13:40:45 -070036const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
37 "Phi",
38 "Copy",
39 "FusedCmplFloat",
40 "FusedCmpgFloat",
41 "FusedCmplDouble",
42 "FusedCmpgDouble",
43 "FusedCmpLong",
44 "Nop",
45 "OpNullCheck",
46 "OpRangeCheck",
47 "OpDivZeroCheck",
48 "Check1",
49 "Check2",
50 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040051 "ConstVector",
52 "MoveVector",
53 "PackedMultiply",
54 "PackedAddition",
55 "PackedSubtract",
56 "PackedShiftLeft",
57 "PackedSignedShiftRight",
58 "PackedUnsignedShiftRight",
59 "PackedAnd",
60 "PackedOr",
61 "PackedXor",
62 "PackedAddReduce",
63 "PackedReduce",
64 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070065};
66
buzbee862a7602013-04-05 10:58:54 -070067MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070068 : reg_location_(NULL),
69 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080070 ssa_base_vregs_(NULL),
71 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080072 vreg_to_ssa_map_(NULL),
73 ssa_last_defs_(NULL),
74 is_constant_v_(NULL),
75 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070076 use_counts_(arena, 256, kGrowableArrayMisc),
77 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080078 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070079 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070080 dfs_order_(NULL),
81 dfs_post_order_(NULL),
82 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070083 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080084 i_dom_list_(NULL),
85 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000086 temp_scoped_alloc_(),
87 temp_insn_data_(nullptr),
88 temp_bit_vector_size_(0u),
89 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070090 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080091 try_block_addr_(NULL),
92 entry_block_(NULL),
93 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080094 num_blocks_(0),
95 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070096 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080097 current_method_(kInvalidEntry),
98 current_offset_(kInvalidEntry),
99 def_count_(0),
100 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700101 num_ssa_regs_(0),
102 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700103 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
104 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700105 arena_(arena),
106 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800107 forward_branches_(0),
108 compiler_temps_(arena, 6, kGrowableArrayMisc),
109 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800110 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000111 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000112 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000113 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000114 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700115 method_lowering_infos_(arena, 0u),
116 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700117 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800118 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
119 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800120}
121
Ian Rogers6282dc12013-04-18 15:54:02 -0700122MIRGraph::~MIRGraph() {
123 STLDeleteElements(&m_units_);
124}
125
buzbee311ca162013-02-28 15:56:43 -0800126/*
127 * Parse an instruction, return the length of the instruction
128 */
Ian Rogers29a26482014-05-02 15:27:29 -0700129int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
130 const Instruction* inst = Instruction::At(code_ptr);
131 decoded_instruction->opcode = inst->Opcode();
132 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
133 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
134 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
135 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
136 if (inst->HasVarArgs()) {
137 inst->GetVarArgs(decoded_instruction->arg);
138 }
139 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800140}
141
142
143/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700144BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700145 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700146 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800147 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700148 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800149 while (insn) {
150 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700151 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800152 insn = insn->next;
153 }
154 if (insn == NULL) {
155 LOG(FATAL) << "Break split failed";
156 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700157 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700158 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800159
160 bottom_block->start_offset = code_offset;
161 bottom_block->first_mir_insn = insn;
162 bottom_block->last_mir_insn = orig_block->last_mir_insn;
163
164 /* If this block was terminated by a return, the flag needs to go with the bottom block */
165 bottom_block->terminated_by_return = orig_block->terminated_by_return;
166 orig_block->terminated_by_return = false;
167
buzbee311ca162013-02-28 15:56:43 -0800168 /* Handle the taken path */
169 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700170 if (bottom_block->taken != NullBasicBlockId) {
171 orig_block->taken = NullBasicBlockId;
172 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
173 bb_taken->predecessors->Delete(orig_block->id);
174 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800175 }
176
177 /* Handle the fallthrough path */
178 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700179 orig_block->fall_through = bottom_block->id;
180 bottom_block->predecessors->Insert(orig_block->id);
181 if (bottom_block->fall_through != NullBasicBlockId) {
182 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
183 bb_fall_through->predecessors->Delete(orig_block->id);
184 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800185 }
186
187 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700188 if (orig_block->successor_block_list_type != kNotUsed) {
189 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
190 bottom_block->successor_blocks = orig_block->successor_blocks;
191 orig_block->successor_block_list_type = kNotUsed;
192 orig_block->successor_blocks = NULL;
193 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800194 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700195 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800196 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700197 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700198 bb->predecessors->Delete(orig_block->id);
199 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800200 }
201 }
202
buzbee0d829482013-10-11 15:24:55 -0700203 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700204 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800205
buzbee311ca162013-02-28 15:56:43 -0800206 /*
207 * Update the immediate predecessor block pointer so that outgoing edges
208 * can be applied to the proper block.
209 */
210 if (immed_pred_block_p) {
211 DCHECK_EQ(*immed_pred_block_p, orig_block);
212 *immed_pred_block_p = bottom_block;
213 }
buzbeeb48819d2013-09-14 16:15:25 -0700214
215 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000216 DCHECK(insn != nullptr);
217 DCHECK(insn != orig_block->first_mir_insn);
218 DCHECK(insn == bottom_block->first_mir_insn);
219 DCHECK_EQ(insn->offset, bottom_block->start_offset);
220 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
221 !IsPseudoMirOp(insn->dalvikInsn.opcode));
222 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
223 MIR* p = insn;
224 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
225 while (p != bottom_block->last_mir_insn) {
226 p = p->next;
227 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700228 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700229 int opcode = p->dalvikInsn.opcode;
230 /*
231 * Some messiness here to ensure that we only enter real opcodes and only the
232 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000233 * CHECK and work portions. Since the 2nd half of a split operation is always
234 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700235 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000236 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
237 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700238 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
239 }
buzbeeb48819d2013-09-14 16:15:25 -0700240 }
241
buzbee311ca162013-02-28 15:56:43 -0800242 return bottom_block;
243}
244
245/*
246 * Given a code offset, find out the block that starts with it. If the offset
247 * is in the middle of an existing block, split it into two. If immed_pred_block_p
248 * is not non-null and is the block being split, update *immed_pred_block_p to
249 * point to the bottom block so that outgoing edges can be set up properly
250 * (by the caller)
251 * Utilizes a map for fast lookup of the typical cases.
252 */
buzbee0d829482013-10-11 15:24:55 -0700253BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700254 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700255 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800256 return NULL;
257 }
buzbeeb48819d2013-09-14 16:15:25 -0700258
259 int block_id = dex_pc_to_block_map_.Get(code_offset);
260 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
261
262 if ((bb != NULL) && (bb->start_offset == code_offset)) {
263 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700264 return bb;
265 }
buzbee311ca162013-02-28 15:56:43 -0800266
buzbeeb48819d2013-09-14 16:15:25 -0700267 // No direct hit.
268 if (!create) {
269 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800270 }
271
buzbeeb48819d2013-09-14 16:15:25 -0700272 if (bb != NULL) {
273 // The target exists somewhere in an existing block.
274 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
275 }
276
277 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700278 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
279 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800280 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700281 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800282 return bb;
283}
284
buzbeeb48819d2013-09-14 16:15:25 -0700285
buzbee311ca162013-02-28 15:56:43 -0800286/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700287void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800288 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700289 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800290
291 if (tries_size == 0) {
292 return;
293 }
294
295 for (int i = 0; i < tries_size; i++) {
296 const DexFile::TryItem* pTry =
297 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700298 DexOffset start_offset = pTry->start_addr_;
299 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800300 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700301 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800302 }
303 }
304
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700305 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800306 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
307 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
308 for (uint32_t idx = 0; idx < handlers_size; idx++) {
309 CatchHandlerIterator iterator(handlers_ptr);
310 for (; iterator.HasNext(); iterator.Next()) {
311 uint32_t address = iterator.GetHandlerAddress();
312 FindBlock(address, false /* split */, true /*create*/,
313 /* immed_pred_block_p */ NULL);
314 }
315 handlers_ptr = iterator.EndDataPointer();
316 }
317}
318
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100319bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
320 NarrowDexOffset catch_offset) {
321 // Catches for monitor-exit during stack unwinding have the pattern
322 // move-exception (move)* (goto)? monitor-exit throw
323 // In the currently generated dex bytecode we see these catching a bytecode range including
324 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
325 // it's the case for a given monitor-exit and catch block so that we can ignore it.
326 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
327 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
328 // even though a throwing monitor-exit certainly indicates a bytecode error.)
329 const Instruction* monitor_exit = Instruction::At(cu_->code_item->insns_ + monitor_exit_offset);
330 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
331 int monitor_reg = monitor_exit->VRegA_11x();
332 const Instruction* check_insn = Instruction::At(cu_->code_item->insns_ + catch_offset);
333 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
334 if (check_insn->VRegA_11x() == monitor_reg) {
335 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
336 return false;
337 }
338 check_insn = check_insn->Next();
339 while (true) {
340 int dest = -1;
341 bool wide = false;
342 switch (check_insn->Opcode()) {
343 case Instruction::MOVE_WIDE:
344 wide = true;
345 // Intentional fall-through.
346 case Instruction::MOVE_OBJECT:
347 case Instruction::MOVE:
348 dest = check_insn->VRegA_12x();
349 break;
350
351 case Instruction::MOVE_WIDE_FROM16:
352 wide = true;
353 // Intentional fall-through.
354 case Instruction::MOVE_OBJECT_FROM16:
355 case Instruction::MOVE_FROM16:
356 dest = check_insn->VRegA_22x();
357 break;
358
359 case Instruction::MOVE_WIDE_16:
360 wide = true;
361 // Intentional fall-through.
362 case Instruction::MOVE_OBJECT_16:
363 case Instruction::MOVE_16:
364 dest = check_insn->VRegA_32x();
365 break;
366
367 case Instruction::GOTO:
368 case Instruction::GOTO_16:
369 case Instruction::GOTO_32:
370 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
371 // Intentional fall-through.
372 default:
373 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
374 check_insn->VRegA_11x() == monitor_reg;
375 }
376
377 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
378 return false;
379 }
380
381 check_insn = check_insn->Next();
382 }
383}
384
buzbee311ca162013-02-28 15:56:43 -0800385/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700386BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
387 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700388 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700389 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800390 switch (insn->dalvikInsn.opcode) {
391 case Instruction::GOTO:
392 case Instruction::GOTO_16:
393 case Instruction::GOTO_32:
394 target += insn->dalvikInsn.vA;
395 break;
396 case Instruction::IF_EQ:
397 case Instruction::IF_NE:
398 case Instruction::IF_LT:
399 case Instruction::IF_GE:
400 case Instruction::IF_GT:
401 case Instruction::IF_LE:
402 cur_block->conditional_branch = true;
403 target += insn->dalvikInsn.vC;
404 break;
405 case Instruction::IF_EQZ:
406 case Instruction::IF_NEZ:
407 case Instruction::IF_LTZ:
408 case Instruction::IF_GEZ:
409 case Instruction::IF_GTZ:
410 case Instruction::IF_LEZ:
411 cur_block->conditional_branch = true;
412 target += insn->dalvikInsn.vB;
413 break;
414 default:
415 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
416 }
buzbeeb48819d2013-09-14 16:15:25 -0700417 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700418 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800419 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700420 cur_block->taken = taken_block->id;
421 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800422
423 /* Always terminate the current block for conditional branches */
424 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700425 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800426 /*
427 * If the method is processed
428 * in sequential order from the
429 * beginning, we don't need to
430 * specify split for continue
431 * blocks. However, this
432 * routine can be called by
433 * compileLoop, which starts
434 * parsing the method from an
435 * arbitrary address in the
436 * method body.
437 */
438 true,
439 /* create */
440 true,
441 /* immed_pred_block_p */
442 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700443 cur_block->fall_through = fallthrough_block->id;
444 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800445 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700446 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800447 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800448 }
449 return cur_block;
450}
451
452/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800453BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
454 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800455 const uint16_t* switch_data =
456 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
457 int size;
458 const int* keyTable;
459 const int* target_table;
460 int i;
461 int first_key;
462
463 /*
464 * Packed switch data format:
465 * ushort ident = 0x0100 magic value
466 * ushort size number of entries in the table
467 * int first_key first (and lowest) switch case value
468 * int targets[size] branch targets, relative to switch opcode
469 *
470 * Total size is (4+size*2) 16-bit code units.
471 */
472 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
473 DCHECK_EQ(static_cast<int>(switch_data[0]),
474 static_cast<int>(Instruction::kPackedSwitchSignature));
475 size = switch_data[1];
476 first_key = switch_data[2] | (switch_data[3] << 16);
477 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700478 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800479 /*
480 * Sparse switch data format:
481 * ushort ident = 0x0200 magic value
482 * ushort size number of entries in the table; > 0
483 * int keys[size] keys, sorted low-to-high; 32-bit aligned
484 * int targets[size] branch targets, relative to switch opcode
485 *
486 * Total size is (2+size*4) 16-bit code units.
487 */
488 } else {
489 DCHECK_EQ(static_cast<int>(switch_data[0]),
490 static_cast<int>(Instruction::kSparseSwitchSignature));
491 size = switch_data[1];
492 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
493 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700494 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800495 }
496
buzbee0d829482013-10-11 15:24:55 -0700497 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800498 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700499 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800500 }
buzbee0d829482013-10-11 15:24:55 -0700501 cur_block->successor_block_list_type =
502 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
503 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700504 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800505
506 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700507 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800508 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700509 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700510 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000511 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700512 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800513 successor_block_info->key =
514 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
515 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700516 cur_block->successor_blocks->Insert(successor_block_info);
517 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800518 }
519
520 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700521 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
522 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700523 cur_block->fall_through = fallthrough_block->id;
524 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800525 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800526}
527
528/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700529BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
530 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700531 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700532 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800533 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
534 bool build_all_edges =
535 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800536
537 /* In try block */
538 if (in_try_block) {
539 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
540
buzbee0d829482013-10-11 15:24:55 -0700541 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800542 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
543 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700544 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800545 }
546
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700547 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700548 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800549 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100550 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
551 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
552 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
553 continue;
554 }
555 if (cur_block->successor_block_list_type == kNotUsed) {
556 cur_block->successor_block_list_type = kCatch;
557 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
558 arena_, 2, kGrowableArraySuccessorBlocks);
559 }
buzbee311ca162013-02-28 15:56:43 -0800560 catch_block->catch_entry = true;
561 if (kIsDebugBuild) {
562 catches_.insert(catch_block->start_offset);
563 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700564 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000565 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700566 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800567 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700568 cur_block->successor_blocks->Insert(successor_block_info);
569 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800570 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100571 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
572 }
573 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700574 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700575 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700576 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800577 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700578 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800579 }
580
buzbee17189ac2013-11-08 11:07:02 -0800581 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800582 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700583 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700584 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800585 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
586 /* immed_pred_block_p */ NULL);
587 }
588 if (!in_try_block) {
589 // Don't split a THROW that can't rethrow - we're done.
590 return cur_block;
591 }
592 }
593
buzbee17189ac2013-11-08 11:07:02 -0800594 if (!build_all_edges) {
595 /*
596 * Even though there is an exception edge here, control cannot return to this
597 * method. Thus, for the purposes of dataflow analysis and optimization, we can
598 * ignore the edge. Doing this reduces compile time, and increases the scope
599 * of the basic-block level optimization pass.
600 */
601 return cur_block;
602 }
603
buzbee311ca162013-02-28 15:56:43 -0800604 /*
605 * Split the potentially-throwing instruction into two parts.
606 * The first half will be a pseudo-op that captures the exception
607 * edges and terminates the basic block. It always falls through.
608 * Then, create a new basic block that begins with the throwing instruction
609 * (minus exceptions). Note: this new basic block must NOT be entered into
610 * the block_map. If the potentially-throwing instruction is the target of a
611 * future branch, we need to find the check psuedo half. The new
612 * basic block containing the work portion of the instruction should
613 * only be entered via fallthrough from the block containing the
614 * pseudo exception edge MIR. Note also that this new block is
615 * not automatically terminated after the work portion, and may
616 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700617 *
618 * Note also that the dex_pc_to_block_map_ entry for the potentially
619 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800620 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700621 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700622 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800623 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700624 cur_block->fall_through = new_block->id;
625 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700626 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800627 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700628 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700629 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800630 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700631 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800632 return new_block;
633}
634
635/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
636void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700637 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700638 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800639 current_code_item_ = code_item;
640 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
641 current_method_ = m_units_.size();
642 current_offset_ = 0;
643 // TODO: will need to snapshot stack image and use that as the mir context identification.
644 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000645 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
646 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800647 const uint16_t* code_ptr = current_code_item_->insns_;
648 const uint16_t* code_end =
649 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
650
651 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700652 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700653 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700654 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 -0700655
buzbee311ca162013-02-28 15:56:43 -0800656 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700657 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
658 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800659
660 // If this is the first method, set up default entry and exit blocks.
661 if (current_method_ == 0) {
662 DCHECK(entry_block_ == NULL);
663 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700664 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700665 // Use id 0 to represent a null block.
666 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
667 DCHECK_EQ(null_block->id, NullBasicBlockId);
668 null_block->hidden = true;
669 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700670 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700671 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700672 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700673 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800674 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
675 cu_->dex_file = &dex_file;
676 cu_->class_def_idx = class_def_idx;
677 cu_->method_idx = method_idx;
678 cu_->access_flags = access_flags;
679 cu_->invoke_type = invoke_type;
680 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
681 cu_->num_ins = current_code_item_->ins_size_;
682 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
683 cu_->num_outs = current_code_item_->outs_size_;
684 cu_->num_dalvik_registers = current_code_item_->registers_size_;
685 cu_->insns = current_code_item_->insns_;
686 cu_->code_item = current_code_item_;
687 } else {
688 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
689 /*
690 * Will need to manage storage for ins & outs, push prevous state and update
691 * insert point.
692 */
693 }
694
695 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700696 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700697 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800698 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700699 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700700 // TODO: for inlining support, insert at the insert point rather than entry block.
701 entry_block_->fall_through = cur_block->id;
702 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800703
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000704 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800705 ProcessTryCatchBlocks();
706
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000707 uint64_t merged_df_flags = 0u;
708
buzbee311ca162013-02-28 15:56:43 -0800709 /* Parse all instructions and put them into containing basic blocks */
710 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700711 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800712 insn->offset = current_offset_;
713 insn->m_unit_index = current_method_;
714 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800715 Instruction::Code opcode = insn->dalvikInsn.opcode;
716 if (opcode_count_ != NULL) {
717 opcode_count_[static_cast<int>(opcode)]++;
718 }
719
buzbee311ca162013-02-28 15:56:43 -0800720 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800721 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800722
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700723 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000724 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800725
726 if (df_flags & DF_HAS_DEFS) {
727 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
728 }
729
buzbee1da1e2f2013-11-15 13:37:01 -0800730 if (df_flags & DF_LVN) {
731 cur_block->use_lvn = true; // Run local value numbering on this basic block.
732 }
733
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700734 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700735 if (opcode == Instruction::NOP) {
736 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
737 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
738 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
739 uint16_t following_raw_instruction = code_ptr[1];
740 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
741 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
742 (following_raw_instruction == Instruction::kArrayDataSignature)) {
743 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
744 }
745 }
746 if (width == 1) {
747 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700748 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700749 } else {
buzbee0d829482013-10-11 15:24:55 -0700750 DCHECK(cur_block->fall_through == NullBasicBlockId);
751 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700752 // Unreachable instruction, mark for no continuation.
753 flags &= ~Instruction::kContinue;
754 }
755 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700756 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700757 }
758
buzbeeb48819d2013-09-14 16:15:25 -0700759 // Associate the starting dex_pc for this opcode with its containing basic block.
760 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
761
buzbee27247762013-07-28 12:03:58 -0700762 code_ptr += width;
763
buzbee311ca162013-02-28 15:56:43 -0800764 if (flags & Instruction::kBranch) {
765 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
766 width, flags, code_ptr, code_end);
767 } else if (flags & Instruction::kReturn) {
768 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700769 cur_block->fall_through = exit_block_->id;
770 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800771 /*
772 * Terminate the current block if there are instructions
773 * afterwards.
774 */
775 if (code_ptr < code_end) {
776 /*
777 * Create a fallthrough block for real instructions
778 * (incl. NOP).
779 */
buzbee27247762013-07-28 12:03:58 -0700780 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
781 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800782 }
783 } else if (flags & Instruction::kThrow) {
784 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
785 code_ptr, code_end);
786 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800787 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800788 }
buzbeeb1f1d642014-02-27 12:55:32 -0800789 if (verify_flags & Instruction::kVerifyVarArgRange) {
790 /*
791 * The Quick backend's runtime model includes a gap between a method's
792 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
793 * which spans the gap is somewhat complicated, and should not happen
794 * in normal usage of dx. Punt to the interpreter.
795 */
796 int first_reg_in_range = insn->dalvikInsn.vC;
797 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
798 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
799 punt_to_interpreter_ = true;
800 }
801 }
buzbee311ca162013-02-28 15:56:43 -0800802 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700803 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800804 false, /* immed_pred_block_p */ NULL);
805 if (next_block) {
806 /*
807 * The next instruction could be the target of a previously parsed
808 * forward branch so a block is already created. If the current
809 * instruction is not an unconditional branch, connect them through
810 * the fall-through link.
811 */
buzbee0d829482013-10-11 15:24:55 -0700812 DCHECK(cur_block->fall_through == NullBasicBlockId ||
813 GetBasicBlock(cur_block->fall_through) == next_block ||
814 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800815
buzbee0d829482013-10-11 15:24:55 -0700816 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
817 cur_block->fall_through = next_block->id;
818 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800819 }
820 cur_block = next_block;
821 }
822 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000823 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000824
buzbee311ca162013-02-28 15:56:43 -0800825 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
826 DumpCFG("/sdcard/1_post_parse_cfg/", true);
827 }
828
829 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700830 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800831 }
832}
833
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700834void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800835 DCHECK(opcode_count_ != NULL);
836 LOG(INFO) << "Opcode Count";
837 for (int i = 0; i < kNumPackedOpcodes; i++) {
838 if (opcode_count_[i] != 0) {
839 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
840 << " " << opcode_count_[i];
841 }
842 }
843}
844
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700845uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
846 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
847 return oat_data_flow_attributes_[opcode];
848}
849
850uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
851 DCHECK(mir != nullptr);
852 Instruction::Code opcode = mir->dalvikInsn.opcode;
853 return GetDataFlowAttributes(opcode);
854}
855
buzbee311ca162013-02-28 15:56:43 -0800856// TODO: use a configurable base prefix, and adjust callers to supply pass name.
857/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800858void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800859 FILE* file;
860 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
861 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800862 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
863 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
864 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800865 file = fopen(fname.c_str(), "w");
866 if (file == NULL) {
867 return;
868 }
869 fprintf(file, "digraph G {\n");
870
871 fprintf(file, " rankdir=TB\n");
872
873 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
874 int idx;
875
876 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700877 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700878 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700879 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800880 if (bb->block_type == kDead) continue;
881 if (bb->block_type == kEntryBlock) {
882 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
883 } else if (bb->block_type == kExitBlock) {
884 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
885 } else if (bb->block_type == kDalvikByteCode) {
886 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
887 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700888 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800889 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
890 bb->first_mir_insn ? " | " : " ");
891 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
892 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400893 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
894 if (opcode == kMirOpConstVector) {
895 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
896 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
897 mir->dalvikInsn.vA,
898 mir->dalvikInsn.vB,
899 mir->dalvikInsn.arg[0],
900 mir->dalvikInsn.arg[1],
901 mir->dalvikInsn.arg[2],
902 mir->dalvikInsn.arg[3],
903 mir->next ? " | " : " ");
904 } else {
905 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
906 extended_mir_op_names_[opcode - kMirOpFirst],
907 mir->dalvikInsn.vA,
908 mir->dalvikInsn.vB,
909 mir->dalvikInsn.vC,
910 mir->next ? " | " : " ");
911 }
912 } else {
913 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
914 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700915 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400916 extended_mir_op_names_[opcode - kMirOpFirst],
917 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
918 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
919 mir->next ? " | " : " ");
920 }
buzbee311ca162013-02-28 15:56:43 -0800921 }
922 fprintf(file, " }\"];\n\n");
923 } else if (bb->block_type == kExceptionHandling) {
924 char block_name[BLOCK_NAME_LEN];
925
926 GetBlockName(bb, block_name);
927 fprintf(file, " %s [shape=invhouse];\n", block_name);
928 }
929
930 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
931
buzbee0d829482013-10-11 15:24:55 -0700932 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800933 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700934 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800935 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
936 block_name1, block_name2);
937 }
buzbee0d829482013-10-11 15:24:55 -0700938 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800939 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700940 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800941 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
942 }
943
buzbee0d829482013-10-11 15:24:55 -0700944 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800945 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
946 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700947 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
948 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700949 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800950
951 int succ_id = 0;
952 while (true) {
953 if (successor_block_info == NULL) break;
954
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700955 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700956 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800957
958 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
959 succ_id++,
960 successor_block_info->key,
961 dest_block->start_offset,
962 (next_successor_block_info != NULL) ? " | " : " ");
963
964 successor_block_info = next_successor_block_info;
965 }
966 fprintf(file, " }\"];\n\n");
967
968 GetBlockName(bb, block_name1);
969 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
970 block_name1, bb->start_offset, bb->id);
971
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700972 // Link the successor pseudo-block with all of its potential targets.
973 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800974
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700975 succ_id = 0;
976 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700977 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700978 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800979
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700980 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800981
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700982 GetBlockName(dest_block, block_name2);
983 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
984 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800985 }
986 }
987 fprintf(file, "\n");
988
989 if (cu_->verbose) {
990 /* Display the dominator tree */
991 GetBlockName(bb, block_name1);
992 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
993 block_name1, block_name1);
994 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700995 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800996 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
997 }
998 }
999 }
1000 fprintf(file, "}\n");
1001 fclose(file);
1002}
1003
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001004/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001005void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001006 // Insert it after the last MIR.
1007 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001008}
1009
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001010void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1011 // Insert it after the last MIR.
1012 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1013}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001014
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001015void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1016 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1017 MIR* new_mir = *it;
1018
1019 // Add a copy of each MIR.
1020 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1021 }
buzbee1fd33462013-03-25 13:40:45 -07001022}
1023
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001024/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001025void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001026 InsertMIRListAfter(current_mir, new_mir, new_mir);
1027}
buzbee1fd33462013-03-25 13:40:45 -07001028
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001029void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1030 // If no MIR, we are done.
1031 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1032 return;
buzbee1fd33462013-03-25 13:40:45 -07001033 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001034
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001035 // If insert_after is null, assume BB is empty.
1036 if (insert_after == nullptr) {
1037 first_mir_insn = first_list_mir;
1038 last_mir_insn = last_list_mir;
1039 last_list_mir->next = nullptr;
1040 } else {
1041 MIR* after_list = insert_after->next;
1042 insert_after->next = first_list_mir;
1043 last_list_mir->next = after_list;
1044 if (after_list == nullptr) {
1045 last_mir_insn = last_list_mir;
1046 }
1047 }
1048
1049 // Set this BB to be the basic block of the MIRs.
1050 MIR* last = last_list_mir->next;
1051 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1052 mir->bb = id;
1053 }
1054}
1055
1056/* Insert an MIR instruction to the head of a basic block. */
1057void BasicBlock::PrependMIR(MIR* mir) {
1058 InsertMIRListBefore(first_mir_insn, mir, mir);
1059}
1060
1061void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1062 // Insert it before the first MIR.
1063 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1064}
1065
1066void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1067 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1068 MIR* mir = *it;
1069
1070 InsertMIRListBefore(first_mir_insn, mir, mir);
1071 }
1072}
1073
1074/* Insert a MIR instruction before the specified MIR. */
1075void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1076 // Insert as a single element list.
1077 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001078}
1079
1080MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1081 MIR* current = first_mir_insn;
1082
1083 while (current != nullptr) {
1084 MIR* next = current->next;
1085
1086 if (next == mir) {
1087 return current;
1088 }
1089
1090 current = next;
1091 }
1092
1093 return nullptr;
1094}
1095
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001096void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1097 // If no MIR, we are done.
1098 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1099 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001100 }
1101
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001102 // If insert_before is null, assume BB is empty.
1103 if (insert_before == nullptr) {
1104 first_mir_insn = first_list_mir;
1105 last_mir_insn = last_list_mir;
1106 last_list_mir->next = nullptr;
1107 } else {
1108 if (first_mir_insn == insert_before) {
1109 last_list_mir->next = first_mir_insn;
1110 first_mir_insn = first_list_mir;
1111 } else {
1112 // Find the preceding MIR.
1113 MIR* before_list = FindPreviousMIR(insert_before);
1114 DCHECK(before_list != nullptr);
1115 before_list->next = first_list_mir;
1116 last_list_mir->next = insert_before;
1117 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001118 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001119
1120 // Set this BB to be the basic block of the MIRs.
1121 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1122 mir->bb = id;
1123 }
1124}
1125
1126bool BasicBlock::RemoveMIR(MIR* mir) {
1127 // Remove as a single element list.
1128 return RemoveMIRList(mir, mir);
1129}
1130
1131bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1132 if (first_list_mir == nullptr) {
1133 return false;
1134 }
1135
1136 // Try to find the MIR.
1137 MIR* before_list = nullptr;
1138 MIR* after_list = nullptr;
1139
1140 // If we are removing from the beginning of the MIR list.
1141 if (first_mir_insn == first_list_mir) {
1142 before_list = nullptr;
1143 } else {
1144 before_list = FindPreviousMIR(first_list_mir);
1145 if (before_list == nullptr) {
1146 // We did not find the mir.
1147 return false;
1148 }
1149 }
1150
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001151 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001152 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1153 mir->bb = NullBasicBlockId;
1154 }
1155
1156 after_list = last_list_mir->next;
1157
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001158 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001159 if (before_list == nullptr) {
1160 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001161 } else {
1162 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001163 }
1164
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001165 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001166 if (after_list == nullptr) {
1167 last_mir_insn = before_list;
1168 }
1169
1170 return true;
buzbee1fd33462013-03-25 13:40:45 -07001171}
1172
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001173MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001174 MIR* next_mir = nullptr;
1175
1176 if (current != nullptr) {
1177 next_mir = current->next;
1178 }
1179
1180 if (next_mir == nullptr) {
1181 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001182 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1183 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001184 }
1185 }
1186
1187 return next_mir;
1188}
1189
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001190char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001191 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001192 std::string str;
1193 int flags = 0;
1194 int opcode = insn.opcode;
1195 char* ret;
1196 bool nop = false;
1197 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001198 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001199 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1200 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1201
1202 // Handle special cases.
1203 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1204 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1205 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001206 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001207 insn = mir->meta.throw_insn->dalvikInsn;
1208 ssa_rep = mir->meta.throw_insn->ssa_rep;
1209 defs = ssa_rep->num_defs;
1210 uses = ssa_rep->num_uses;
1211 opcode = insn.opcode;
1212 } else if (opcode == kMirOpNop) {
1213 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001214 // Recover original opcode.
1215 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1216 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001217 nop = true;
1218 }
1219
buzbee35ba7f32014-05-31 08:59:01 -07001220 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001221 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1222 } else {
1223 dalvik_format = Instruction::FormatOf(insn.opcode);
1224 flags = Instruction::FlagsOf(insn.opcode);
1225 str.append(Instruction::Name(insn.opcode));
1226 }
1227
1228 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001229 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001230 str.append(StringPrintf(" %s = (%s",
1231 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1232 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001233 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001234 int i;
1235 for (i = 1; i < uses; i++) {
1236 str.append(StringPrintf(", %s:%d",
1237 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1238 incoming[i]));
1239 }
1240 str.append(")");
1241 } else if ((flags & Instruction::kBranch) != 0) {
1242 // For branches, decode the instructions to print out the branch targets.
1243 int offset = 0;
1244 switch (dalvik_format) {
1245 case Instruction::k21t:
1246 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1247 offset = insn.vB;
1248 break;
1249 case Instruction::k22t:
1250 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1251 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1252 offset = insn.vC;
1253 break;
1254 case Instruction::k10t:
1255 case Instruction::k20t:
1256 case Instruction::k30t:
1257 offset = insn.vA;
1258 break;
1259 default:
1260 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1261 }
1262 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1263 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1264 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001265 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001266 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1267 (dalvik_format == Instruction::k3rc));
1268 if (defs != 0) {
1269 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1270 if (uses != 0) {
1271 str.append(", ");
1272 }
1273 }
1274 for (int i = 0; i < uses; i++) {
1275 str.append(
1276 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1277 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1278 // For the listing, skip the high sreg.
1279 i++;
1280 }
1281 if (i != (uses -1)) {
1282 str.append(",");
1283 }
1284 }
1285 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001286 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001287 case Instruction::k21s:
1288 case Instruction::k31i:
1289 case Instruction::k21h:
1290 str.append(StringPrintf(", #%d", insn.vB));
1291 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001292 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001293 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001294 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001295 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001296 case Instruction::k31c:
1297 str.append(StringPrintf(", index #%d", insn.vB));
1298 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001299 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001300 str.append(StringPrintf(", index #%d", insn.vC));
1301 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001302 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001303 case Instruction::k22b:
1304 str.append(StringPrintf(", #%d", insn.vC));
1305 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001306 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001307 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001308 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001309 }
buzbee1fd33462013-03-25 13:40:45 -07001310 }
1311 if (nop) {
1312 str.append("]--optimized away");
1313 }
1314 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001315 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001316 strncpy(ret, str.c_str(), length);
1317 return ret;
1318}
1319
1320/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001321void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001322 static const struct { const char before; const char after; } match[] = {
1323 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1324 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1325 };
buzbee1fd33462013-03-25 13:40:45 -07001326 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1327 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1328 }
1329}
1330
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001331std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001332 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1333 // the arena. We should be smarter and just place straight into the arena, or compute the
1334 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001335 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1336}
1337
1338// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001339std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001340 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001341 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001342 return GetSSAName(ssa_reg);
1343 }
1344 if (IsConst(reg_location_[ssa_reg])) {
1345 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001346 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001347 ConstantValueWide(reg_location_[ssa_reg]));
1348 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001349 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001350 ConstantValue(reg_location_[ssa_reg]));
1351 }
1352 } else {
1353 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1354 }
1355}
1356
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001357void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001358 switch (bb->block_type) {
1359 case kEntryBlock:
1360 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1361 break;
1362 case kExitBlock:
1363 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1364 break;
1365 case kDalvikByteCode:
1366 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1367 break;
1368 case kExceptionHandling:
1369 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1370 bb->id);
1371 break;
1372 default:
1373 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1374 break;
1375 }
1376}
1377
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001378const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001379 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001380 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1381 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1382}
1383
1384/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001385void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001386 BasicBlock* bb;
1387 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001388 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001389 "Entry Block",
1390 "Code Block",
1391 "Exit Block",
1392 "Exception Handling",
1393 "Catch Block"
1394 };
1395
1396 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1397 LOG(INFO) << cu_->insns << " insns";
1398 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001399 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001400
1401 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001402 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001403 if (bb == NULL) break;
1404 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1405 bb->id,
1406 block_type_names[bb->block_type],
1407 bb->start_offset,
1408 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1409 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001410 if (bb->taken != NullBasicBlockId) {
1411 LOG(INFO) << " Taken branch: block " << bb->taken
1412 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001413 }
buzbee0d829482013-10-11 15:24:55 -07001414 if (bb->fall_through != NullBasicBlockId) {
1415 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1416 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001417 }
1418 }
1419}
1420
1421/*
1422 * Build an array of location records for the incoming arguments.
1423 * Note: one location record per word of arguments, with dummy
1424 * high-word loc for wide arguments. Also pull up any following
1425 * MOVE_RESULT and incorporate it into the invoke.
1426 */
1427CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001428 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001429 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001430 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001431 MIR* move_result_mir = FindMoveResult(bb, mir);
1432 if (move_result_mir == NULL) {
1433 info->result.location = kLocInvalid;
1434 } else {
1435 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001436 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1437 }
1438 info->num_arg_words = mir->ssa_rep->num_uses;
1439 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001440 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001441 for (int i = 0; i < info->num_arg_words; i++) {
1442 info->args[i] = GetRawSrc(mir, i);
1443 }
1444 info->opt_flags = mir->optimization_flags;
1445 info->type = type;
1446 info->is_range = is_range;
1447 info->index = mir->dalvikInsn.vB;
1448 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001449 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001450 return info;
1451}
1452
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001453// Allocate a new MIR.
1454MIR* MIRGraph::NewMIR() {
1455 MIR* mir = new (arena_) MIR();
1456 return mir;
1457}
1458
buzbee862a7602013-04-05 10:58:54 -07001459// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001460BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001461 BasicBlock* bb = new (arena_) BasicBlock();
1462
buzbee862a7602013-04-05 10:58:54 -07001463 bb->block_type = block_type;
1464 bb->id = block_id;
1465 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001466 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001467 (block_type == kExitBlock) ? 2048 : 2,
1468 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001469 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001470 block_id_map_.Put(block_id, block_id);
1471 return bb;
1472}
buzbee1fd33462013-03-25 13:40:45 -07001473
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001474void MIRGraph::InitializeConstantPropagation() {
1475 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001476 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001477}
1478
1479void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001480 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001481 int num_ssa_regs = GetNumSSARegs();
1482 use_counts_.Resize(num_ssa_regs + 32);
1483 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001484 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001485 for (int i = 0; i < num_ssa_regs; i++) {
1486 use_counts_.Insert(0);
1487 raw_use_counts_.Insert(0);
1488 }
1489}
1490
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001491void MIRGraph::SSATransformationStart() {
1492 DCHECK(temp_scoped_alloc_.get() == nullptr);
1493 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1494 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1495 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1496 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1497
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001498 // Update the maximum number of reachable blocks.
1499 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001500}
1501
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001502void MIRGraph::SSATransformationEnd() {
1503 // Verify the dataflow information after the pass.
1504 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1505 VerifyDataflow();
1506 }
1507
1508 temp_bit_vector_size_ = 0u;
1509 temp_bit_vector_ = nullptr;
1510 DCHECK(temp_scoped_alloc_.get() != nullptr);
1511 temp_scoped_alloc_.reset();
1512}
1513
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001514void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001515 // Clear the nodes.
1516 ClearAllVisitedFlags();
1517
1518 // Create the topological order if need be.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001519 if (topological_order_ == nullptr) {
1520 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, GetNumBlocks());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001521 }
1522 topological_order_->Reset();
1523
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001524 ScopedArenaAllocator allocator(&cu_->arena_stack);
1525 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1526 ScopedArenaVector<size_t> visited_cnt_values(GetNumBlocks(), 0u, allocator.Adapter());
1527
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001528 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1529 // also fill initial queue.
1530 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1531
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001532 size_t num_blocks = 0u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001533 while (true) {
1534 BasicBlock* bb = iterator.Next();
1535
1536 if (bb == nullptr) {
1537 break;
1538 }
1539
1540 if (bb->hidden == true) {
1541 continue;
1542 }
1543
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001544 num_blocks += 1u;
1545 size_t unvisited_predecessor_count = bb->predecessors->Size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001546
1547 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1548 // To process loops we should not wait for dominators.
1549 while (true) {
1550 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1551
1552 if (pred_bb == nullptr) {
1553 break;
1554 }
1555
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001556 // Skip the backward branch or hidden predecessor.
1557 if (pred_bb->hidden ||
1558 (pred_bb->dominators != nullptr && pred_bb->dominators->IsBitSet(bb->id))) {
1559 unvisited_predecessor_count -= 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001560 }
1561 }
1562
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001563 visited_cnt_values[bb->id] = unvisited_predecessor_count;
1564
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001565 // Add entry block to queue.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001566 if (unvisited_predecessor_count == 0) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001567 q.push(bb);
1568 }
1569 }
1570
Vladimir Markoe8ae8142014-07-08 18:06:45 +01001571 // We can get a cycle where none of the blocks dominates the other. Therefore don't
1572 // stop when the queue is empty, continue until we've processed all the blocks.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001573 AllNodesIterator candidate_iter(this); // For the empty queue case.
1574 while (num_blocks != 0u) {
1575 num_blocks -= 1u;
1576 BasicBlock* bb = nullptr;
1577 if (!q.empty()) {
1578 // Get top.
1579 bb = q.front();
1580 q.pop();
1581 } else {
1582 // Find some block we didn't visit yet that has at least one visited predecessor.
1583 while (bb == nullptr) {
1584 BasicBlock* candidate = candidate_iter.Next();
1585 DCHECK(candidate != nullptr);
1586 if (candidate->visited || candidate->hidden) {
1587 continue;
1588 }
1589 GrowableArray<BasicBlockId>::Iterator iter(candidate->predecessors);
1590 for (BasicBlock* pred_bb = GetBasicBlock(iter.Next()); pred_bb != nullptr;
1591 pred_bb = GetBasicBlock(iter.Next())) {
1592 if (!pred_bb->hidden && pred_bb->visited) {
1593 bb = candidate;
1594 break;
1595 }
1596 }
1597 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001598 }
1599
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001600 DCHECK_EQ(bb->hidden, false);
1601 DCHECK_EQ(bb->visited, false);
1602
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001603 // We've visited all the predecessors. So, we can visit bb.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001604 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001605
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001606 // Now add the basic block.
1607 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001608
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001609 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1610 ChildBlockIterator succIter(bb, this);
1611 BasicBlock* successor = succIter.Next();
1612 for ( ; successor != nullptr; successor = succIter.Next()) {
1613 if (successor->visited || successor->hidden) {
1614 continue;
1615 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001616
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001617 // one more predecessor was visited.
1618 DCHECK_NE(visited_cnt_values[successor->id], 0u);
1619 visited_cnt_values[successor->id] -= 1u;
1620 if (visited_cnt_values[successor->id] == 0u) {
1621 q.push(successor);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001622 }
1623 }
1624 }
1625}
1626
1627bool BasicBlock::IsExceptionBlock() const {
1628 if (block_type == kExceptionHandling) {
1629 return true;
1630 }
1631 return false;
1632}
1633
Wei Jin04f4d8a2014-05-29 18:04:29 -07001634bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1635 BasicBlock* target = GetBasicBlock(target_id);
1636
1637 if (source == nullptr || target == nullptr)
1638 return false;
1639
1640 int idx;
1641 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1642 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1643 if (bb == source)
1644 return true; // The block has been inserted by a suspend check before.
1645 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1646 return true;
1647 }
1648
1649 return false;
1650}
1651
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001652ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1653 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1654 visited_taken_(false), have_successors_(false) {
1655 // Check if we actually do have successors.
1656 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1657 have_successors_ = true;
1658 successor_iter_.Reset(basic_block_->successor_blocks);
1659 }
1660}
1661
1662BasicBlock* ChildBlockIterator::Next() {
1663 // We check if we have a basic block. If we don't we cannot get next child.
1664 if (basic_block_ == nullptr) {
1665 return nullptr;
1666 }
1667
1668 // If we haven't visited fallthrough, return that.
1669 if (visited_fallthrough_ == false) {
1670 visited_fallthrough_ = true;
1671
1672 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1673 if (result != nullptr) {
1674 return result;
1675 }
1676 }
1677
1678 // If we haven't visited taken, return that.
1679 if (visited_taken_ == false) {
1680 visited_taken_ = true;
1681
1682 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1683 if (result != nullptr) {
1684 return result;
1685 }
1686 }
1687
1688 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1689 if (have_successors_ == true) {
1690 // Get information about next successor block.
1691 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1692
1693 // If we don't have anymore successors, return nullptr.
1694 if (successor_block_info != nullptr) {
1695 return mir_graph_->GetBasicBlock(successor_block_info->block);
1696 }
1697 }
1698
1699 // We do not have anything.
1700 return nullptr;
1701}
1702
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001703BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1704 MIRGraph* mir_graph = c_unit->mir_graph.get();
1705 return Copy(mir_graph);
1706}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001707
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001708BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1709 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001710
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001711 // We don't do a memcpy style copy here because it would lead to a lot of things
1712 // to clean up. Let us do it by hand instead.
1713 // Copy in taken and fallthrough.
1714 result_bb->fall_through = fall_through;
1715 result_bb->taken = taken;
1716
1717 // Copy successor links if needed.
1718 ArenaAllocator* arena = mir_graph->GetArena();
1719
1720 result_bb->successor_block_list_type = successor_block_list_type;
1721 if (result_bb->successor_block_list_type != kNotUsed) {
1722 size_t size = successor_blocks->Size();
1723 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1724 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1725 while (true) {
1726 SuccessorBlockInfo* sbi_old = iterator.Next();
1727 if (sbi_old == nullptr) {
1728 break;
1729 }
1730 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1731 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1732 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001733 }
1734 }
1735
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001736 // Copy offset, method.
1737 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001738
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001739 // Now copy instructions.
1740 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1741 // Get a copy first.
1742 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001743
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001744 // Append it.
1745 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001746 }
1747
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001748 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001749}
1750
1751MIR* MIR::Copy(MIRGraph* mir_graph) {
1752 MIR* res = mir_graph->NewMIR();
1753 *res = *this;
1754
1755 // Remove links
1756 res->next = nullptr;
1757 res->bb = NullBasicBlockId;
1758 res->ssa_rep = nullptr;
1759
1760 return res;
1761}
1762
1763MIR* MIR::Copy(CompilationUnit* c_unit) {
1764 return Copy(c_unit->mir_graph.get());
1765}
1766
1767uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1768 // Default result.
1769 int res = 0;
1770
1771 // We are basically setting the iputs to their igets counterparts.
1772 switch (opcode) {
1773 case Instruction::IPUT:
1774 case Instruction::IPUT_OBJECT:
1775 case Instruction::IPUT_BOOLEAN:
1776 case Instruction::IPUT_BYTE:
1777 case Instruction::IPUT_CHAR:
1778 case Instruction::IPUT_SHORT:
1779 case Instruction::IPUT_QUICK:
1780 case Instruction::IPUT_OBJECT_QUICK:
1781 case Instruction::APUT:
1782 case Instruction::APUT_OBJECT:
1783 case Instruction::APUT_BOOLEAN:
1784 case Instruction::APUT_BYTE:
1785 case Instruction::APUT_CHAR:
1786 case Instruction::APUT_SHORT:
1787 case Instruction::SPUT:
1788 case Instruction::SPUT_OBJECT:
1789 case Instruction::SPUT_BOOLEAN:
1790 case Instruction::SPUT_BYTE:
1791 case Instruction::SPUT_CHAR:
1792 case Instruction::SPUT_SHORT:
1793 // Skip the VR containing what to store.
1794 res = 1;
1795 break;
1796 case Instruction::IPUT_WIDE:
1797 case Instruction::IPUT_WIDE_QUICK:
1798 case Instruction::APUT_WIDE:
1799 case Instruction::SPUT_WIDE:
1800 // Skip the two VRs containing what to store.
1801 res = 2;
1802 break;
1803 default:
1804 // Do nothing in the general case.
1805 break;
1806 }
1807
1808 return res;
1809}
1810
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001811/**
1812 * @brief Given a decoded instruction, it checks whether the instruction
1813 * sets a constant and if it does, more information is provided about the
1814 * constant being set.
1815 * @param ptr_value pointer to a 64-bit holder for the constant.
1816 * @param wide Updated by function whether a wide constant is being set by bytecode.
1817 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1818 */
1819bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1820 bool sets_const = true;
1821 int64_t value = vB;
1822
1823 DCHECK(ptr_value != nullptr);
1824 DCHECK(wide != nullptr);
1825
1826 switch (opcode) {
1827 case Instruction::CONST_4:
1828 case Instruction::CONST_16:
1829 case Instruction::CONST:
1830 *wide = false;
1831 value <<= 32; // In order to get the sign extend.
1832 value >>= 32;
1833 break;
1834 case Instruction::CONST_HIGH16:
1835 *wide = false;
1836 value <<= 48; // In order to get the sign extend.
1837 value >>= 32;
1838 break;
1839 case Instruction::CONST_WIDE_16:
1840 case Instruction::CONST_WIDE_32:
1841 *wide = true;
1842 value <<= 32; // In order to get the sign extend.
1843 value >>= 32;
1844 break;
1845 case Instruction::CONST_WIDE:
1846 *wide = true;
1847 value = vB_wide;
1848 break;
1849 case Instruction::CONST_WIDE_HIGH16:
1850 *wide = true;
1851 value <<= 48; // In order to get the sign extend.
1852 break;
1853 default:
1854 sets_const = false;
1855 break;
1856 }
1857
1858 if (sets_const) {
1859 *ptr_value = value;
1860 }
1861
1862 return sets_const;
1863}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001864
1865void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1866 // Reset flags for all MIRs in bb.
1867 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1868 mir->optimization_flags &= (~reset_flags);
1869 }
1870}
1871
1872void BasicBlock::Hide(CompilationUnit* c_unit) {
1873 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1874 block_type = kDalvikByteCode;
1875
1876 // Mark it as hidden.
1877 hidden = true;
1878
1879 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1880 // are updated to know that they no longer have a parent.
1881 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1882 mir->bb = NullBasicBlockId;
1883 }
1884 first_mir_insn = nullptr;
1885 last_mir_insn = nullptr;
1886
1887 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1888
1889 MIRGraph* mir_graph = c_unit->mir_graph.get();
1890 while (true) {
1891 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1892 if (pred_bb == nullptr) {
1893 break;
1894 }
1895
1896 // Sadly we have to go through the children by hand here.
1897 pred_bb->ReplaceChild(id, NullBasicBlockId);
1898 }
1899
1900 // Iterate through children of bb we are hiding.
1901 ChildBlockIterator successorChildIter(this, mir_graph);
1902
1903 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1904 // Replace child with null child.
1905 childPtr->predecessors->Delete(id);
1906 }
1907}
1908
1909bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1910 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1911 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1912 // then it is not live out of this BB.
1913 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1914
1915 int last_ssa_reg = -1;
1916
1917 // Walk through the MIRs backwards.
1918 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1919 // Get ssa rep.
1920 SSARepresentation *ssa_rep = mir->ssa_rep;
1921
1922 // Go through the defines for this MIR.
1923 for (int i = 0; i < ssa_rep->num_defs; i++) {
1924 DCHECK(ssa_rep->defs != nullptr);
1925
1926 // Get the ssa reg.
1927 int def_ssa_reg = ssa_rep->defs[i];
1928
1929 // Get dalvik reg.
1930 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1931
1932 // Compare dalvik regs.
1933 if (dalvik_reg == def_dalvik_reg) {
1934 // We found a def of the register that we are being asked about.
1935 // Remember it.
1936 last_ssa_reg = def_ssa_reg;
1937 }
1938 }
1939 }
1940
1941 if (last_ssa_reg == -1) {
1942 // If we get to this point we couldn't find a define of register user asked about.
1943 // Let's assume the user knows what he's doing so we can be safe and say that if we
1944 // couldn't find a def, it is live out.
1945 return true;
1946 }
1947
1948 // If it is not -1, we found a match, is it ssa_reg?
1949 return (ssa_reg == last_ssa_reg);
1950}
1951
1952bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1953 // We need to check taken, fall_through, and successor_blocks to replace.
1954 bool found = false;
1955 if (taken == old_bb) {
1956 taken = new_bb;
1957 found = true;
1958 }
1959
1960 if (fall_through == old_bb) {
1961 fall_through = new_bb;
1962 found = true;
1963 }
1964
1965 if (successor_block_list_type != kNotUsed) {
1966 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1967 while (true) {
1968 SuccessorBlockInfo* successor_block_info = iterator.Next();
1969 if (successor_block_info == nullptr) {
1970 break;
1971 }
1972 if (successor_block_info->block == old_bb) {
1973 successor_block_info->block = new_bb;
1974 found = true;
1975 }
1976 }
1977 }
1978
1979 return found;
1980}
1981
1982void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1983 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1984 bool found = false;
1985
1986 while (true) {
1987 BasicBlockId pred_bb_id = iterator.Next();
1988
1989 if (pred_bb_id == NullBasicBlockId) {
1990 break;
1991 }
1992
1993 if (pred_bb_id == old_parent) {
1994 size_t idx = iterator.GetIndex() - 1;
1995 predecessors->Put(idx, new_parent);
1996 found = true;
1997 break;
1998 }
1999 }
2000
2001 // If not found, add it.
2002 if (found == false) {
2003 predecessors->Insert(new_parent);
2004 }
2005}
2006
2007// Create a new basic block with block_id as num_blocks_ that is
2008// post-incremented.
2009BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2010 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2011 block_list_.Insert(res);
2012 return res;
2013}
2014
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002015void MIRGraph::CalculateBasicBlockInformation() {
2016 PassDriverMEPostOpt driver(cu_);
2017 driver.Launch();
2018}
2019
2020void MIRGraph::InitializeBasicBlockData() {
2021 num_blocks_ = block_list_.Size();
2022}
2023
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002024} // namespace art