blob: 5cc3d18d4c30cfcbab18ce1f6bc08fc3d4c9753b [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 Marko95a05972014-05-30 10:01:32 +010026#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000027#include "dex/quick/dex_file_to_method_inliner_map.h"
28#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000029#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070030#include "pass_driver_me_post_opt.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010031#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000032
buzbee311ca162013-02-28 15:56:43 -080033namespace art {
34
35#define MAX_PATTERN_LEN 5
36
buzbee1fd33462013-03-25 13:40:45 -070037const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
38 "Phi",
39 "Copy",
40 "FusedCmplFloat",
41 "FusedCmpgFloat",
42 "FusedCmplDouble",
43 "FusedCmpgDouble",
44 "FusedCmpLong",
45 "Nop",
46 "OpNullCheck",
47 "OpRangeCheck",
48 "OpDivZeroCheck",
49 "Check1",
50 "Check2",
51 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040052 "ConstVector",
53 "MoveVector",
54 "PackedMultiply",
55 "PackedAddition",
56 "PackedSubtract",
57 "PackedShiftLeft",
58 "PackedSignedShiftRight",
59 "PackedUnsignedShiftRight",
60 "PackedAnd",
61 "PackedOr",
62 "PackedXor",
63 "PackedAddReduce",
64 "PackedReduce",
65 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070066 "ReserveVectorRegisters",
67 "ReturnVectorRegisters",
buzbee1fd33462013-03-25 13:40:45 -070068};
69
buzbee862a7602013-04-05 10:58:54 -070070MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070071 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010072 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070073 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080074 ssa_base_vregs_(NULL),
75 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080076 vreg_to_ssa_map_(NULL),
77 ssa_last_defs_(NULL),
78 is_constant_v_(NULL),
79 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070080 use_counts_(arena, 256, kGrowableArrayMisc),
81 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080082 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070083 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070084 dfs_order_(NULL),
85 dfs_post_order_(NULL),
86 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070087 topological_order_(nullptr),
Vladimir Marko55fff042014-07-10 12:42:52 +010088 topological_order_loop_ends_(nullptr),
89 topological_order_indexes_(nullptr),
90 topological_order_loop_head_stack_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080091 i_dom_list_(NULL),
92 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000093 temp_scoped_alloc_(),
94 temp_insn_data_(nullptr),
95 temp_bit_vector_size_(0u),
96 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +010097 temp_gvn_(),
buzbee862a7602013-04-05 10:58:54 -070098 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080099 try_block_addr_(NULL),
100 entry_block_(NULL),
101 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800102 num_blocks_(0),
103 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700104 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100105 m_units_(arena->Adapter()),
106 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800107 current_method_(kInvalidEntry),
108 current_offset_(kInvalidEntry),
109 def_count_(0),
110 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700111 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100112 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700113 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700114 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
115 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700116 arena_(arena),
117 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800118 forward_branches_(0),
119 compiler_temps_(arena, 6, kGrowableArrayMisc),
120 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800121 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000122 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000123 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000124 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000125 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700126 method_lowering_infos_(arena, 0u),
127 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700128 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800129 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
130 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800131}
132
Ian Rogers6282dc12013-04-18 15:54:02 -0700133MIRGraph::~MIRGraph() {
134 STLDeleteElements(&m_units_);
135}
136
buzbee311ca162013-02-28 15:56:43 -0800137/*
138 * Parse an instruction, return the length of the instruction
139 */
Ian Rogers29a26482014-05-02 15:27:29 -0700140int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
141 const Instruction* inst = Instruction::At(code_ptr);
142 decoded_instruction->opcode = inst->Opcode();
143 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
144 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
145 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
146 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
147 if (inst->HasVarArgs()) {
148 inst->GetVarArgs(decoded_instruction->arg);
149 }
150 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800151}
152
153
154/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700155BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700156 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700157 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800158 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700159 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800160 while (insn) {
161 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700162 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800163 insn = insn->next;
164 }
165 if (insn == NULL) {
166 LOG(FATAL) << "Break split failed";
167 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700168 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700169 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800170
171 bottom_block->start_offset = code_offset;
172 bottom_block->first_mir_insn = insn;
173 bottom_block->last_mir_insn = orig_block->last_mir_insn;
174
Junmo Park90223cc2014-08-04 18:51:21 +0900175 /* If this block was terminated by a return, conditional branch or throw,
176 * the flag needs to go with the bottom block
177 */
buzbee311ca162013-02-28 15:56:43 -0800178 bottom_block->terminated_by_return = orig_block->terminated_by_return;
179 orig_block->terminated_by_return = false;
180
Junmo Park90223cc2014-08-04 18:51:21 +0900181 bottom_block->conditional_branch = orig_block->conditional_branch;
182 orig_block->conditional_branch = false;
183
184 bottom_block->explicit_throw = orig_block->explicit_throw;
185 orig_block->explicit_throw = false;
186
buzbee311ca162013-02-28 15:56:43 -0800187 /* Handle the taken path */
188 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700189 if (bottom_block->taken != NullBasicBlockId) {
190 orig_block->taken = NullBasicBlockId;
191 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
192 bb_taken->predecessors->Delete(orig_block->id);
193 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800194 }
195
196 /* Handle the fallthrough path */
197 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700198 orig_block->fall_through = bottom_block->id;
199 bottom_block->predecessors->Insert(orig_block->id);
200 if (bottom_block->fall_through != NullBasicBlockId) {
201 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
202 bb_fall_through->predecessors->Delete(orig_block->id);
203 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800204 }
205
206 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700207 if (orig_block->successor_block_list_type != kNotUsed) {
208 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
209 bottom_block->successor_blocks = orig_block->successor_blocks;
210 orig_block->successor_block_list_type = kNotUsed;
Niranjan Kumar989367a2014-06-12 12:15:48 -0700211 orig_block->successor_blocks = nullptr;
buzbee0d829482013-10-11 15:24:55 -0700212 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800213 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700214 SuccessorBlockInfo* successor_block_info = iterator.Next();
Niranjan Kumar989367a2014-06-12 12:15:48 -0700215 if (successor_block_info == nullptr) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700216 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700217 if (bb != nullptr) {
218 bb->predecessors->Delete(orig_block->id);
219 bb->predecessors->Insert(bottom_block->id);
220 }
buzbee311ca162013-02-28 15:56:43 -0800221 }
222 }
223
buzbee0d829482013-10-11 15:24:55 -0700224 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700225 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800226
buzbee311ca162013-02-28 15:56:43 -0800227 /*
228 * Update the immediate predecessor block pointer so that outgoing edges
229 * can be applied to the proper block.
230 */
231 if (immed_pred_block_p) {
232 DCHECK_EQ(*immed_pred_block_p, orig_block);
233 *immed_pred_block_p = bottom_block;
234 }
buzbeeb48819d2013-09-14 16:15:25 -0700235
236 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000237 DCHECK(insn != nullptr);
238 DCHECK(insn != orig_block->first_mir_insn);
239 DCHECK(insn == bottom_block->first_mir_insn);
240 DCHECK_EQ(insn->offset, bottom_block->start_offset);
241 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700242 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Marko4376c872014-01-23 12:39:29 +0000243 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
244 MIR* p = insn;
245 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
246 while (p != bottom_block->last_mir_insn) {
247 p = p->next;
248 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700249 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700250 int opcode = p->dalvikInsn.opcode;
251 /*
252 * Some messiness here to ensure that we only enter real opcodes and only the
253 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000254 * CHECK and work portions. Since the 2nd half of a split operation is always
255 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700256 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700257 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Marko4376c872014-01-23 12:39:29 +0000258 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700259 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
260 }
buzbeeb48819d2013-09-14 16:15:25 -0700261 }
262
buzbee311ca162013-02-28 15:56:43 -0800263 return bottom_block;
264}
265
266/*
267 * Given a code offset, find out the block that starts with it. If the offset
268 * is in the middle of an existing block, split it into two. If immed_pred_block_p
269 * is not non-null and is the block being split, update *immed_pred_block_p to
270 * point to the bottom block so that outgoing edges can be set up properly
271 * (by the caller)
272 * Utilizes a map for fast lookup of the typical cases.
273 */
buzbee0d829482013-10-11 15:24:55 -0700274BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700275 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700276 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800277 return NULL;
278 }
buzbeeb48819d2013-09-14 16:15:25 -0700279
280 int block_id = dex_pc_to_block_map_.Get(code_offset);
281 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
282
283 if ((bb != NULL) && (bb->start_offset == code_offset)) {
284 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700285 return bb;
286 }
buzbee311ca162013-02-28 15:56:43 -0800287
buzbeeb48819d2013-09-14 16:15:25 -0700288 // No direct hit.
289 if (!create) {
290 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800291 }
292
buzbeeb48819d2013-09-14 16:15:25 -0700293 if (bb != NULL) {
294 // The target exists somewhere in an existing block.
295 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
296 }
297
298 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700299 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
300 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800301 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700302 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800303 return bb;
304}
305
buzbeeb48819d2013-09-14 16:15:25 -0700306
buzbee311ca162013-02-28 15:56:43 -0800307/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700308void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800309 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700310 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800311
312 if (tries_size == 0) {
313 return;
314 }
315
316 for (int i = 0; i < tries_size; i++) {
317 const DexFile::TryItem* pTry =
318 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700319 DexOffset start_offset = pTry->start_addr_;
320 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800321 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700322 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800323 }
324 }
325
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700326 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800327 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
328 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
329 for (uint32_t idx = 0; idx < handlers_size; idx++) {
330 CatchHandlerIterator iterator(handlers_ptr);
331 for (; iterator.HasNext(); iterator.Next()) {
332 uint32_t address = iterator.GetHandlerAddress();
333 FindBlock(address, false /* split */, true /*create*/,
334 /* immed_pred_block_p */ NULL);
335 }
336 handlers_ptr = iterator.EndDataPointer();
337 }
338}
339
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100340bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
341 NarrowDexOffset catch_offset) {
342 // Catches for monitor-exit during stack unwinding have the pattern
343 // move-exception (move)* (goto)? monitor-exit throw
344 // In the currently generated dex bytecode we see these catching a bytecode range including
345 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
346 // it's the case for a given monitor-exit and catch block so that we can ignore it.
347 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
348 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
349 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700350 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100351 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
352 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700353 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100354 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
355 if (check_insn->VRegA_11x() == monitor_reg) {
356 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
357 return false;
358 }
359 check_insn = check_insn->Next();
360 while (true) {
361 int dest = -1;
362 bool wide = false;
363 switch (check_insn->Opcode()) {
364 case Instruction::MOVE_WIDE:
365 wide = true;
366 // Intentional fall-through.
367 case Instruction::MOVE_OBJECT:
368 case Instruction::MOVE:
369 dest = check_insn->VRegA_12x();
370 break;
371
372 case Instruction::MOVE_WIDE_FROM16:
373 wide = true;
374 // Intentional fall-through.
375 case Instruction::MOVE_OBJECT_FROM16:
376 case Instruction::MOVE_FROM16:
377 dest = check_insn->VRegA_22x();
378 break;
379
380 case Instruction::MOVE_WIDE_16:
381 wide = true;
382 // Intentional fall-through.
383 case Instruction::MOVE_OBJECT_16:
384 case Instruction::MOVE_16:
385 dest = check_insn->VRegA_32x();
386 break;
387
388 case Instruction::GOTO:
389 case Instruction::GOTO_16:
390 case Instruction::GOTO_32:
391 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
392 // Intentional fall-through.
393 default:
394 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
395 check_insn->VRegA_11x() == monitor_reg;
396 }
397
398 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
399 return false;
400 }
401
402 check_insn = check_insn->Next();
403 }
404}
405
buzbee311ca162013-02-28 15:56:43 -0800406/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700407BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
408 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700409 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700410 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800411 switch (insn->dalvikInsn.opcode) {
412 case Instruction::GOTO:
413 case Instruction::GOTO_16:
414 case Instruction::GOTO_32:
415 target += insn->dalvikInsn.vA;
416 break;
417 case Instruction::IF_EQ:
418 case Instruction::IF_NE:
419 case Instruction::IF_LT:
420 case Instruction::IF_GE:
421 case Instruction::IF_GT:
422 case Instruction::IF_LE:
423 cur_block->conditional_branch = true;
424 target += insn->dalvikInsn.vC;
425 break;
426 case Instruction::IF_EQZ:
427 case Instruction::IF_NEZ:
428 case Instruction::IF_LTZ:
429 case Instruction::IF_GEZ:
430 case Instruction::IF_GTZ:
431 case Instruction::IF_LEZ:
432 cur_block->conditional_branch = true;
433 target += insn->dalvikInsn.vB;
434 break;
435 default:
436 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
437 }
buzbeeb48819d2013-09-14 16:15:25 -0700438 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700439 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800440 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700441 cur_block->taken = taken_block->id;
442 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800443
444 /* Always terminate the current block for conditional branches */
445 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700446 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800447 /*
448 * If the method is processed
449 * in sequential order from the
450 * beginning, we don't need to
451 * specify split for continue
452 * blocks. However, this
453 * routine can be called by
454 * compileLoop, which starts
455 * parsing the method from an
456 * arbitrary address in the
457 * method body.
458 */
459 true,
460 /* create */
461 true,
462 /* immed_pred_block_p */
463 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700464 cur_block->fall_through = fallthrough_block->id;
465 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800466 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700467 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800468 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800469 }
470 return cur_block;
471}
472
473/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800474BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
475 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800476 const uint16_t* switch_data =
477 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
478 int size;
479 const int* keyTable;
480 const int* target_table;
481 int i;
482 int first_key;
483
484 /*
485 * Packed switch data format:
486 * ushort ident = 0x0100 magic value
487 * ushort size number of entries in the table
488 * int first_key first (and lowest) switch case value
489 * int targets[size] branch targets, relative to switch opcode
490 *
491 * Total size is (4+size*2) 16-bit code units.
492 */
493 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
494 DCHECK_EQ(static_cast<int>(switch_data[0]),
495 static_cast<int>(Instruction::kPackedSwitchSignature));
496 size = switch_data[1];
497 first_key = switch_data[2] | (switch_data[3] << 16);
498 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700499 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800500 /*
501 * Sparse switch data format:
502 * ushort ident = 0x0200 magic value
503 * ushort size number of entries in the table; > 0
504 * int keys[size] keys, sorted low-to-high; 32-bit aligned
505 * int targets[size] branch targets, relative to switch opcode
506 *
507 * Total size is (2+size*4) 16-bit code units.
508 */
509 } else {
510 DCHECK_EQ(static_cast<int>(switch_data[0]),
511 static_cast<int>(Instruction::kSparseSwitchSignature));
512 size = switch_data[1];
513 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
514 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700515 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800516 }
517
buzbee0d829482013-10-11 15:24:55 -0700518 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800519 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700520 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800521 }
buzbee0d829482013-10-11 15:24:55 -0700522 cur_block->successor_block_list_type =
523 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
524 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700525 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800526
527 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700528 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800529 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700530 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700531 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000532 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700533 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800534 successor_block_info->key =
535 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
536 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700537 cur_block->successor_blocks->Insert(successor_block_info);
538 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800539 }
540
541 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700542 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
543 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700544 cur_block->fall_through = fallthrough_block->id;
545 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800546 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800547}
548
549/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700550BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
551 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700552 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700553 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800554 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
555 bool build_all_edges =
556 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800557
558 /* In try block */
559 if (in_try_block) {
560 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
561
buzbee0d829482013-10-11 15:24:55 -0700562 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800563 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
564 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700565 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800566 }
567
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700568 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700569 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800570 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100571 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
572 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
573 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
574 continue;
575 }
576 if (cur_block->successor_block_list_type == kNotUsed) {
577 cur_block->successor_block_list_type = kCatch;
578 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
579 arena_, 2, kGrowableArraySuccessorBlocks);
580 }
buzbee311ca162013-02-28 15:56:43 -0800581 catch_block->catch_entry = true;
582 if (kIsDebugBuild) {
583 catches_.insert(catch_block->start_offset);
584 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700585 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000586 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700587 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800588 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700589 cur_block->successor_blocks->Insert(successor_block_info);
590 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800591 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100592 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
593 }
594 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700595 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700596 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700597 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800598 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700599 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800600 }
601
buzbee17189ac2013-11-08 11:07:02 -0800602 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800603 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700604 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700605 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800606 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
607 /* immed_pred_block_p */ NULL);
608 }
609 if (!in_try_block) {
610 // Don't split a THROW that can't rethrow - we're done.
611 return cur_block;
612 }
613 }
614
buzbee17189ac2013-11-08 11:07:02 -0800615 if (!build_all_edges) {
616 /*
617 * Even though there is an exception edge here, control cannot return to this
618 * method. Thus, for the purposes of dataflow analysis and optimization, we can
619 * ignore the edge. Doing this reduces compile time, and increases the scope
620 * of the basic-block level optimization pass.
621 */
622 return cur_block;
623 }
624
buzbee311ca162013-02-28 15:56:43 -0800625 /*
626 * Split the potentially-throwing instruction into two parts.
627 * The first half will be a pseudo-op that captures the exception
628 * edges and terminates the basic block. It always falls through.
629 * Then, create a new basic block that begins with the throwing instruction
630 * (minus exceptions). Note: this new basic block must NOT be entered into
631 * the block_map. If the potentially-throwing instruction is the target of a
632 * future branch, we need to find the check psuedo half. The new
633 * basic block containing the work portion of the instruction should
634 * only be entered via fallthrough from the block containing the
635 * pseudo exception edge MIR. Note also that this new block is
636 * not automatically terminated after the work portion, and may
637 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700638 *
639 * Note also that the dex_pc_to_block_map_ entry for the potentially
640 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800641 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700642 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700643 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800644 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700645 cur_block->fall_through = new_block->id;
646 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700647 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800648 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700649 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700650 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800651 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700652 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800653 return new_block;
654}
655
656/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
657void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700658 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700659 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800660 current_code_item_ = code_item;
661 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
662 current_method_ = m_units_.size();
663 current_offset_ = 0;
664 // TODO: will need to snapshot stack image and use that as the mir context identification.
665 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000666 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
667 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800668 const uint16_t* code_ptr = current_code_item_->insns_;
669 const uint16_t* code_end =
670 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
671
672 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700673 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700674 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700675 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 -0700676
buzbee311ca162013-02-28 15:56:43 -0800677 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700678 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
679 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800680
681 // If this is the first method, set up default entry and exit blocks.
682 if (current_method_ == 0) {
683 DCHECK(entry_block_ == NULL);
684 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700685 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700686 // Use id 0 to represent a null block.
687 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
688 DCHECK_EQ(null_block->id, NullBasicBlockId);
689 null_block->hidden = true;
690 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700691 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700692 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700693 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700694 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800695 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
696 cu_->dex_file = &dex_file;
697 cu_->class_def_idx = class_def_idx;
698 cu_->method_idx = method_idx;
699 cu_->access_flags = access_flags;
700 cu_->invoke_type = invoke_type;
701 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
702 cu_->num_ins = current_code_item_->ins_size_;
703 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
704 cu_->num_outs = current_code_item_->outs_size_;
705 cu_->num_dalvik_registers = current_code_item_->registers_size_;
706 cu_->insns = current_code_item_->insns_;
707 cu_->code_item = current_code_item_;
708 } else {
709 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
710 /*
711 * Will need to manage storage for ins & outs, push prevous state and update
712 * insert point.
713 */
714 }
715
716 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700717 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700718 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800719 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700720 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700721 // TODO: for inlining support, insert at the insert point rather than entry block.
722 entry_block_->fall_through = cur_block->id;
723 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800724
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000725 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800726 ProcessTryCatchBlocks();
727
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000728 uint64_t merged_df_flags = 0u;
729
buzbee311ca162013-02-28 15:56:43 -0800730 /* Parse all instructions and put them into containing basic blocks */
731 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700732 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800733 insn->offset = current_offset_;
734 insn->m_unit_index = current_method_;
735 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800736 Instruction::Code opcode = insn->dalvikInsn.opcode;
737 if (opcode_count_ != NULL) {
738 opcode_count_[static_cast<int>(opcode)]++;
739 }
740
buzbee311ca162013-02-28 15:56:43 -0800741 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800742 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800743
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700744 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000745 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800746
747 if (df_flags & DF_HAS_DEFS) {
748 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
749 }
750
buzbee1da1e2f2013-11-15 13:37:01 -0800751 if (df_flags & DF_LVN) {
752 cur_block->use_lvn = true; // Run local value numbering on this basic block.
753 }
754
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700755 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700756 if (opcode == Instruction::NOP) {
757 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
758 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
759 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
760 uint16_t following_raw_instruction = code_ptr[1];
761 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
762 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
763 (following_raw_instruction == Instruction::kArrayDataSignature)) {
764 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
765 }
766 }
767 if (width == 1) {
768 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700769 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700770 } else {
buzbee0d829482013-10-11 15:24:55 -0700771 DCHECK(cur_block->fall_through == NullBasicBlockId);
772 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700773 // Unreachable instruction, mark for no continuation.
774 flags &= ~Instruction::kContinue;
775 }
776 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700777 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700778 }
779
buzbeeb48819d2013-09-14 16:15:25 -0700780 // Associate the starting dex_pc for this opcode with its containing basic block.
781 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
782
buzbee27247762013-07-28 12:03:58 -0700783 code_ptr += width;
784
buzbee311ca162013-02-28 15:56:43 -0800785 if (flags & Instruction::kBranch) {
786 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
787 width, flags, code_ptr, code_end);
788 } else if (flags & Instruction::kReturn) {
789 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700790 cur_block->fall_through = exit_block_->id;
791 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800792 /*
793 * Terminate the current block if there are instructions
794 * afterwards.
795 */
796 if (code_ptr < code_end) {
797 /*
798 * Create a fallthrough block for real instructions
799 * (incl. NOP).
800 */
buzbee27247762013-07-28 12:03:58 -0700801 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
802 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800803 }
804 } else if (flags & Instruction::kThrow) {
805 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
806 code_ptr, code_end);
807 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800808 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800809 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700810 if (verify_flags & Instruction::kVerifyVarArgRange ||
811 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800812 /*
813 * The Quick backend's runtime model includes a gap between a method's
814 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
815 * which spans the gap is somewhat complicated, and should not happen
816 * in normal usage of dx. Punt to the interpreter.
817 */
818 int first_reg_in_range = insn->dalvikInsn.vC;
819 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
820 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
821 punt_to_interpreter_ = true;
822 }
823 }
buzbee311ca162013-02-28 15:56:43 -0800824 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700825 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800826 false, /* immed_pred_block_p */ NULL);
827 if (next_block) {
828 /*
829 * The next instruction could be the target of a previously parsed
830 * forward branch so a block is already created. If the current
831 * instruction is not an unconditional branch, connect them through
832 * the fall-through link.
833 */
buzbee0d829482013-10-11 15:24:55 -0700834 DCHECK(cur_block->fall_through == NullBasicBlockId ||
835 GetBasicBlock(cur_block->fall_through) == next_block ||
836 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800837
buzbee0d829482013-10-11 15:24:55 -0700838 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
839 cur_block->fall_through = next_block->id;
840 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800841 }
842 cur_block = next_block;
843 }
844 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000845 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000846
buzbee311ca162013-02-28 15:56:43 -0800847 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
848 DumpCFG("/sdcard/1_post_parse_cfg/", true);
849 }
850
851 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700852 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800853 }
854}
855
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700856void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800857 DCHECK(opcode_count_ != NULL);
858 LOG(INFO) << "Opcode Count";
859 for (int i = 0; i < kNumPackedOpcodes; i++) {
860 if (opcode_count_[i] != 0) {
861 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
862 << " " << opcode_count_[i];
863 }
864 }
865}
866
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700867uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
868 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
869 return oat_data_flow_attributes_[opcode];
870}
871
872uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
873 DCHECK(mir != nullptr);
874 Instruction::Code opcode = mir->dalvikInsn.opcode;
875 return GetDataFlowAttributes(opcode);
876}
877
buzbee311ca162013-02-28 15:56:43 -0800878// TODO: use a configurable base prefix, and adjust callers to supply pass name.
879/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800880void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800881 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700882 static AtomicInteger cnt(0);
883
884 // Increment counter to get a unique file number.
885 cnt++;
886
buzbee311ca162013-02-28 15:56:43 -0800887 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
888 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700889 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800890 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700891 suffix == nullptr ? "" : suffix,
892 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800893 file = fopen(fname.c_str(), "w");
894 if (file == NULL) {
895 return;
896 }
897 fprintf(file, "digraph G {\n");
898
899 fprintf(file, " rankdir=TB\n");
900
901 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
902 int idx;
903
904 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700905 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700906 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700907 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800908 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700909 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800910 if (bb->block_type == kEntryBlock) {
911 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
912 } else if (bb->block_type == kExitBlock) {
913 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
914 } else if (bb->block_type == kDalvikByteCode) {
915 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
916 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700917 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800918 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
919 bb->first_mir_insn ? " | " : " ");
920 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
921 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400922 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
923 if (opcode == kMirOpConstVector) {
924 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
925 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
926 mir->dalvikInsn.vA,
927 mir->dalvikInsn.vB,
928 mir->dalvikInsn.arg[0],
929 mir->dalvikInsn.arg[1],
930 mir->dalvikInsn.arg[2],
931 mir->dalvikInsn.arg[3],
932 mir->next ? " | " : " ");
933 } else {
934 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
935 extended_mir_op_names_[opcode - kMirOpFirst],
936 mir->dalvikInsn.vA,
937 mir->dalvikInsn.vB,
938 mir->dalvikInsn.vC,
939 mir->next ? " | " : " ");
940 }
941 } else {
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700942 fprintf(file, " {%04x %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400943 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700944 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
945 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400946 extended_mir_op_names_[opcode - kMirOpFirst],
947 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
948 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700949 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400950 mir->next ? " | " : " ");
951 }
buzbee311ca162013-02-28 15:56:43 -0800952 }
953 fprintf(file, " }\"];\n\n");
954 } else if (bb->block_type == kExceptionHandling) {
955 char block_name[BLOCK_NAME_LEN];
956
957 GetBlockName(bb, block_name);
958 fprintf(file, " %s [shape=invhouse];\n", block_name);
959 }
960
961 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
962
buzbee0d829482013-10-11 15:24:55 -0700963 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800964 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700965 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800966 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
967 block_name1, block_name2);
968 }
buzbee0d829482013-10-11 15:24:55 -0700969 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800970 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700971 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800972 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
973 }
974
buzbee0d829482013-10-11 15:24:55 -0700975 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800976 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
977 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700978 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
979 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700980 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800981
982 int succ_id = 0;
983 while (true) {
984 if (successor_block_info == NULL) break;
985
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700986 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700987 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800988
989 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
990 succ_id++,
991 successor_block_info->key,
992 dest_block->start_offset,
993 (next_successor_block_info != NULL) ? " | " : " ");
994
995 successor_block_info = next_successor_block_info;
996 }
997 fprintf(file, " }\"];\n\n");
998
999 GetBlockName(bb, block_name1);
1000 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1001 block_name1, bb->start_offset, bb->id);
1002
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001003 // Link the successor pseudo-block with all of its potential targets.
1004 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -08001005
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001006 succ_id = 0;
1007 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001008 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001009 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -08001010
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001011 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001012
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001013 GetBlockName(dest_block, block_name2);
1014 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1015 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001016 }
1017 }
1018 fprintf(file, "\n");
1019
1020 if (cu_->verbose) {
1021 /* Display the dominator tree */
1022 GetBlockName(bb, block_name1);
1023 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1024 block_name1, block_name1);
1025 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001026 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001027 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1028 }
1029 }
1030 }
1031 fprintf(file, "}\n");
1032 fclose(file);
1033}
1034
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001035/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001036void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001037 // Insert it after the last MIR.
1038 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001039}
1040
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001041void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1042 // Insert it after the last MIR.
1043 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1044}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001045
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001046void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1047 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1048 MIR* new_mir = *it;
1049
1050 // Add a copy of each MIR.
1051 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1052 }
buzbee1fd33462013-03-25 13:40:45 -07001053}
1054
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001055/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001056void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001057 InsertMIRListAfter(current_mir, new_mir, new_mir);
1058}
buzbee1fd33462013-03-25 13:40:45 -07001059
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001060void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1061 // If no MIR, we are done.
1062 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1063 return;
buzbee1fd33462013-03-25 13:40:45 -07001064 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001065
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001066 // If insert_after is null, assume BB is empty.
1067 if (insert_after == nullptr) {
1068 first_mir_insn = first_list_mir;
1069 last_mir_insn = last_list_mir;
1070 last_list_mir->next = nullptr;
1071 } else {
1072 MIR* after_list = insert_after->next;
1073 insert_after->next = first_list_mir;
1074 last_list_mir->next = after_list;
1075 if (after_list == nullptr) {
1076 last_mir_insn = last_list_mir;
1077 }
1078 }
1079
1080 // Set this BB to be the basic block of the MIRs.
1081 MIR* last = last_list_mir->next;
1082 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1083 mir->bb = id;
1084 }
1085}
1086
1087/* Insert an MIR instruction to the head of a basic block. */
1088void BasicBlock::PrependMIR(MIR* mir) {
1089 InsertMIRListBefore(first_mir_insn, mir, mir);
1090}
1091
1092void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1093 // Insert it before the first MIR.
1094 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1095}
1096
1097void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1098 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1099 MIR* mir = *it;
1100
1101 InsertMIRListBefore(first_mir_insn, mir, mir);
1102 }
1103}
1104
1105/* Insert a MIR instruction before the specified MIR. */
1106void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1107 // Insert as a single element list.
1108 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001109}
1110
1111MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1112 MIR* current = first_mir_insn;
1113
1114 while (current != nullptr) {
1115 MIR* next = current->next;
1116
1117 if (next == mir) {
1118 return current;
1119 }
1120
1121 current = next;
1122 }
1123
1124 return nullptr;
1125}
1126
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001127void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1128 // If no MIR, we are done.
1129 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1130 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001131 }
1132
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001133 // If insert_before is null, assume BB is empty.
1134 if (insert_before == nullptr) {
1135 first_mir_insn = first_list_mir;
1136 last_mir_insn = last_list_mir;
1137 last_list_mir->next = nullptr;
1138 } else {
1139 if (first_mir_insn == insert_before) {
1140 last_list_mir->next = first_mir_insn;
1141 first_mir_insn = first_list_mir;
1142 } else {
1143 // Find the preceding MIR.
1144 MIR* before_list = FindPreviousMIR(insert_before);
1145 DCHECK(before_list != nullptr);
1146 before_list->next = first_list_mir;
1147 last_list_mir->next = insert_before;
1148 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001149 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001150
1151 // Set this BB to be the basic block of the MIRs.
1152 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1153 mir->bb = id;
1154 }
1155}
1156
1157bool BasicBlock::RemoveMIR(MIR* mir) {
1158 // Remove as a single element list.
1159 return RemoveMIRList(mir, mir);
1160}
1161
1162bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1163 if (first_list_mir == nullptr) {
1164 return false;
1165 }
1166
1167 // Try to find the MIR.
1168 MIR* before_list = nullptr;
1169 MIR* after_list = nullptr;
1170
1171 // If we are removing from the beginning of the MIR list.
1172 if (first_mir_insn == first_list_mir) {
1173 before_list = nullptr;
1174 } else {
1175 before_list = FindPreviousMIR(first_list_mir);
1176 if (before_list == nullptr) {
1177 // We did not find the mir.
1178 return false;
1179 }
1180 }
1181
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001182 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001183 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1184 mir->bb = NullBasicBlockId;
1185 }
1186
1187 after_list = last_list_mir->next;
1188
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001189 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001190 if (before_list == nullptr) {
1191 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001192 } else {
1193 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001194 }
1195
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001196 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001197 if (after_list == nullptr) {
1198 last_mir_insn = before_list;
1199 }
1200
1201 return true;
buzbee1fd33462013-03-25 13:40:45 -07001202}
1203
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001204MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001205 MIR* next_mir = nullptr;
1206
1207 if (current != nullptr) {
1208 next_mir = current->next;
1209 }
1210
1211 if (next_mir == nullptr) {
1212 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001213 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1214 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001215 }
1216 }
1217
1218 return next_mir;
1219}
1220
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001221char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001222 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001223 std::string str;
1224 int flags = 0;
1225 int opcode = insn.opcode;
1226 char* ret;
1227 bool nop = false;
1228 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001229 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001230 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1231 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1232
1233 // Handle special cases.
1234 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1235 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1236 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001237 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001238 insn = mir->meta.throw_insn->dalvikInsn;
1239 ssa_rep = mir->meta.throw_insn->ssa_rep;
1240 defs = ssa_rep->num_defs;
1241 uses = ssa_rep->num_uses;
1242 opcode = insn.opcode;
1243 } else if (opcode == kMirOpNop) {
1244 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001245 // Recover original opcode.
1246 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1247 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001248 nop = true;
1249 }
1250
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001251 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001252 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1253 } else {
1254 dalvik_format = Instruction::FormatOf(insn.opcode);
1255 flags = Instruction::FlagsOf(insn.opcode);
1256 str.append(Instruction::Name(insn.opcode));
1257 }
1258
1259 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001260 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001261 str.append(StringPrintf(" %s = (%s",
1262 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1263 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001264 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001265 int i;
1266 for (i = 1; i < uses; i++) {
1267 str.append(StringPrintf(", %s:%d",
1268 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1269 incoming[i]));
1270 }
1271 str.append(")");
1272 } else if ((flags & Instruction::kBranch) != 0) {
1273 // For branches, decode the instructions to print out the branch targets.
1274 int offset = 0;
1275 switch (dalvik_format) {
1276 case Instruction::k21t:
1277 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1278 offset = insn.vB;
1279 break;
1280 case Instruction::k22t:
1281 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1282 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1283 offset = insn.vC;
1284 break;
1285 case Instruction::k10t:
1286 case Instruction::k20t:
1287 case Instruction::k30t:
1288 offset = insn.vA;
1289 break;
1290 default:
1291 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1292 }
1293 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1294 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1295 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001296 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001297 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1298 (dalvik_format == Instruction::k3rc));
1299 if (defs != 0) {
1300 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1301 if (uses != 0) {
1302 str.append(", ");
1303 }
1304 }
1305 for (int i = 0; i < uses; i++) {
1306 str.append(
1307 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1308 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1309 // For the listing, skip the high sreg.
1310 i++;
1311 }
1312 if (i != (uses -1)) {
1313 str.append(",");
1314 }
1315 }
1316 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001317 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001318 case Instruction::k21s:
1319 case Instruction::k31i:
1320 case Instruction::k21h:
1321 str.append(StringPrintf(", #%d", insn.vB));
1322 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001323 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001324 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001325 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001326 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001327 case Instruction::k31c:
1328 str.append(StringPrintf(", index #%d", insn.vB));
1329 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001330 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001331 str.append(StringPrintf(", index #%d", insn.vC));
1332 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001333 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001334 case Instruction::k22b:
1335 str.append(StringPrintf(", #%d", insn.vC));
1336 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001337 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001338 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001339 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001340 }
buzbee1fd33462013-03-25 13:40:45 -07001341 }
1342 if (nop) {
1343 str.append("]--optimized away");
1344 }
1345 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001346 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001347 strncpy(ret, str.c_str(), length);
1348 return ret;
1349}
1350
1351/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001352void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001353 static const struct { const char before; const char after; } match[] = {
1354 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1355 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1356 };
buzbee1fd33462013-03-25 13:40:45 -07001357 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1358 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1359 }
1360}
1361
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001362std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001363 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1364 // the arena. We should be smarter and just place straight into the arena, or compute the
1365 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001366 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1367}
1368
1369// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001370std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001371 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001372 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001373 return GetSSAName(ssa_reg);
1374 }
1375 if (IsConst(reg_location_[ssa_reg])) {
1376 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001377 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001378 ConstantValueWide(reg_location_[ssa_reg]));
1379 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001380 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001381 ConstantValue(reg_location_[ssa_reg]));
1382 }
1383 } else {
1384 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1385 }
1386}
1387
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001388void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001389 switch (bb->block_type) {
1390 case kEntryBlock:
1391 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1392 break;
1393 case kExitBlock:
1394 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1395 break;
1396 case kDalvikByteCode:
1397 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1398 break;
1399 case kExceptionHandling:
1400 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1401 bb->id);
1402 break;
1403 default:
1404 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1405 break;
1406 }
1407}
1408
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001409const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001410 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001411 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1412 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1413}
1414
1415/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001416void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001417 BasicBlock* bb;
1418 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001419 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001420 "Entry Block",
1421 "Code Block",
1422 "Exit Block",
1423 "Exception Handling",
1424 "Catch Block"
1425 };
1426
1427 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1428 LOG(INFO) << cu_->insns << " insns";
1429 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001430 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001431
1432 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001433 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001434 if (bb == NULL) break;
1435 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1436 bb->id,
1437 block_type_names[bb->block_type],
1438 bb->start_offset,
1439 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1440 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001441 if (bb->taken != NullBasicBlockId) {
1442 LOG(INFO) << " Taken branch: block " << bb->taken
1443 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001444 }
buzbee0d829482013-10-11 15:24:55 -07001445 if (bb->fall_through != NullBasicBlockId) {
1446 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1447 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001448 }
1449 }
1450}
1451
1452/*
1453 * Build an array of location records for the incoming arguments.
1454 * Note: one location record per word of arguments, with dummy
1455 * high-word loc for wide arguments. Also pull up any following
1456 * MOVE_RESULT and incorporate it into the invoke.
1457 */
1458CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001459 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001460 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001461 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001462 MIR* move_result_mir = FindMoveResult(bb, mir);
1463 if (move_result_mir == NULL) {
1464 info->result.location = kLocInvalid;
1465 } else {
1466 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001467 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1468 }
1469 info->num_arg_words = mir->ssa_rep->num_uses;
1470 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001471 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001472 for (int i = 0; i < info->num_arg_words; i++) {
1473 info->args[i] = GetRawSrc(mir, i);
1474 }
1475 info->opt_flags = mir->optimization_flags;
1476 info->type = type;
1477 info->is_range = is_range;
1478 info->index = mir->dalvikInsn.vB;
1479 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001480 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001481 return info;
1482}
1483
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001484// Allocate a new MIR.
1485MIR* MIRGraph::NewMIR() {
1486 MIR* mir = new (arena_) MIR();
1487 return mir;
1488}
1489
buzbee862a7602013-04-05 10:58:54 -07001490// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001491BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001492 BasicBlock* bb = new (arena_) BasicBlock();
1493
buzbee862a7602013-04-05 10:58:54 -07001494 bb->block_type = block_type;
1495 bb->id = block_id;
1496 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001497 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001498 (block_type == kExitBlock) ? 2048 : 2,
1499 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001500 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001501 block_id_map_.Put(block_id, block_id);
1502 return bb;
1503}
buzbee1fd33462013-03-25 13:40:45 -07001504
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001505void MIRGraph::InitializeConstantPropagation() {
1506 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001507 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001508}
1509
1510void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001511 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001512 int num_ssa_regs = GetNumSSARegs();
1513 use_counts_.Resize(num_ssa_regs + 32);
1514 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001515 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001516 for (int i = 0; i < num_ssa_regs; i++) {
1517 use_counts_.Insert(0);
1518 raw_use_counts_.Insert(0);
1519 }
1520}
1521
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001522void MIRGraph::SSATransformationStart() {
1523 DCHECK(temp_scoped_alloc_.get() == nullptr);
1524 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1525 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1526 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1527 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1528
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001529 // Update the maximum number of reachable blocks.
1530 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001531}
1532
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001533void MIRGraph::SSATransformationEnd() {
1534 // Verify the dataflow information after the pass.
1535 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1536 VerifyDataflow();
1537 }
1538
1539 temp_bit_vector_size_ = 0u;
1540 temp_bit_vector_ = nullptr;
1541 DCHECK(temp_scoped_alloc_.get() != nullptr);
1542 temp_scoped_alloc_.reset();
1543}
1544
Vladimir Marko55fff042014-07-10 12:42:52 +01001545static BasicBlock* SelectTopologicalSortOrderFallBack(
1546 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1547 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1548 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1549 // No true loop head has been found but there may be true loop heads after the mess we need
1550 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1551 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1552 BasicBlock* fall_back = nullptr;
1553 size_t fall_back_num_reachable = 0u;
1554 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1555 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1556 AllNodesIterator iter(mir_graph);
1557 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1558 if (candidate->hidden || // Hidden, or
1559 candidate->visited || // already processed, or
1560 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1561 (current_loop != nullptr && // outside current loop.
1562 !current_loop->IsBitSet(candidate->id))) {
1563 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001564 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001565 DCHECK(tmp_stack->empty());
1566 tmp_stack->push_back(candidate->id);
1567 candidate_reachable.ClearAllBits();
1568 size_t num_reachable = 0u;
1569 while (!tmp_stack->empty()) {
1570 BasicBlockId current_id = tmp_stack->back();
1571 tmp_stack->pop_back();
1572 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1573 DCHECK(current_bb != nullptr);
1574 ChildBlockIterator child_iter(current_bb, mir_graph);
1575 BasicBlock* child_bb = child_iter.Next();
1576 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1577 DCHECK(!child_bb->hidden);
1578 if (child_bb->visited || // Already processed, or
1579 (current_loop != nullptr && // outside current loop.
1580 !current_loop->IsBitSet(child_bb->id))) {
1581 continue;
1582 }
1583 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1584 candidate_reachable.SetBit(child_bb->id);
1585 tmp_stack->push_back(child_bb->id);
1586 num_reachable += 1u;
1587 }
1588 }
1589 }
1590 if (fall_back_num_reachable < num_reachable) {
1591 fall_back_num_reachable = num_reachable;
1592 fall_back = candidate;
1593 }
1594 }
1595 return fall_back;
1596}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001597
Vladimir Marko55fff042014-07-10 12:42:52 +01001598// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1599static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1600 ArenaBitVector* reachable,
1601 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1602 // NOTE: Loop heads indicated by the "visited" flag.
1603 DCHECK(tmp_stack->empty());
1604 reachable->ClearAllBits();
1605 tmp_stack->push_back(bb_id);
1606 while (!tmp_stack->empty()) {
1607 BasicBlockId current_id = tmp_stack->back();
1608 tmp_stack->pop_back();
1609 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1610 DCHECK(current_bb != nullptr);
1611 GrowableArray<BasicBlockId>::Iterator iter(current_bb->predecessors);
1612 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iter.Next());
1613 for ( ; pred_bb != nullptr; pred_bb = mir_graph->GetBasicBlock(iter.Next())) {
1614 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1615 reachable->SetBit(pred_bb->id);
1616 tmp_stack->push_back(pred_bb->id);
1617 }
1618 }
1619 }
1620}
1621
1622void MIRGraph::ComputeTopologicalSortOrder() {
1623 ScopedArenaAllocator allocator(&cu_->arena_stack);
1624 unsigned int num_blocks = GetNumBlocks();
1625
1626 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1627 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1628 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1629 size_t max_nested_loops = 0u;
1630 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1631 loop_exit_blocks.ClearAllBits();
1632
1633 // Count the number of blocks to process and add the entry block(s).
1634 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1635 unsigned int num_blocks_to_process = 0u;
1636 for (BasicBlock* bb = iterator.Next(); bb != nullptr; bb = iterator.Next()) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001637 if (bb->hidden == true) {
1638 continue;
1639 }
1640
Vladimir Marko55fff042014-07-10 12:42:52 +01001641 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001642
Vladimir Marko55fff042014-07-10 12:42:52 +01001643 if (bb->predecessors->Size() == 0u) {
1644 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001645 q.push(bb);
1646 }
1647 }
1648
Vladimir Marko55fff042014-07-10 12:42:52 +01001649 // Create the topological order if need be.
1650 if (topological_order_ == nullptr) {
1651 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, num_blocks);
1652 topological_order_loop_ends_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1653 topological_order_indexes_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1654 }
1655 topological_order_->Reset();
1656 topological_order_loop_ends_->Reset();
1657 topological_order_indexes_->Reset();
1658 topological_order_loop_ends_->Resize(num_blocks);
1659 topological_order_indexes_->Resize(num_blocks);
1660 for (BasicBlockId i = 0; i != num_blocks; ++i) {
1661 topological_order_loop_ends_->Insert(0u);
1662 topological_order_indexes_->Insert(static_cast<uint16_t>(-1));
1663 }
1664
1665 // Mark all blocks as unvisited.
1666 ClearAllVisitedFlags();
1667
1668 // For loop heads, keep track from which blocks they are reachable not going through other
1669 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1670 // in this set go into the loop body, the other children are jumping over the loop.
1671 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1672 loop_head_reachable_from.resize(num_blocks, nullptr);
1673 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1674 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1675
1676 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001677 BasicBlock* bb = nullptr;
1678 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001679 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001680 // Get top.
1681 bb = q.front();
1682 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001683 if (bb->visited) {
1684 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1685 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1686 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1687 topological_order_loop_ends_->Put(topological_order_indexes_->Get(bb->id), idx);
1688 DCHECK_EQ(loop_head_stack.back(), bb->id);
1689 loop_head_stack.pop_back();
1690 ArenaBitVector* reachable =
1691 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1692 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1693 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1694 q.push(GetBasicBlock(candidate_id));
1695 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1696 // so clearing the bit has no effect on the iterator.
1697 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001698 }
1699 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001700 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001701 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001702 } else {
1703 // Find the new loop head.
1704 AllNodesIterator iter(this);
1705 while (true) {
1706 BasicBlock* candidate = iter.Next();
1707 if (candidate == nullptr) {
1708 // We did not find a true loop head, fall back to a reachable block in any loop.
1709 ArenaBitVector* current_loop =
1710 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1711 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1712 &allocator, &tmp_stack);
1713 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1714 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1715 LOG(INFO) << "Topological sort order: Using fall-back in "
1716 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1717 << " @0x" << std::hex << bb->start_offset
1718 << ", num_blocks = " << std::dec << num_blocks;
1719 }
1720 break;
1721 }
1722 if (candidate->hidden || // Hidden, or
1723 candidate->visited || // already processed, or
1724 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1725 (!loop_head_stack.empty() && // outside current loop.
1726 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1727 continue;
1728 }
1729
1730 GrowableArray<BasicBlockId>::Iterator pred_iter(candidate->predecessors);
1731 BasicBlock* pred_bb = GetBasicBlock(pred_iter.Next());
1732 for ( ; pred_bb != nullptr; pred_bb = GetBasicBlock(pred_iter.Next())) {
1733 if (pred_bb != candidate && !pred_bb->visited &&
1734 !pred_bb->dominators->IsBitSet(candidate->id)) {
1735 break; // Keep non-null pred_bb to indicate failure.
1736 }
1737 }
1738 if (pred_bb == nullptr) {
1739 bb = candidate;
1740 break;
1741 }
1742 }
1743 // Compute blocks from which the loop head is reachable and process those blocks first.
1744 ArenaBitVector* reachable =
1745 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1746 loop_head_reachable_from[bb->id] = reachable;
1747 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1748 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1749 loop_head_stack.push_back(bb->id);
1750 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001751 }
1752
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001753 DCHECK_EQ(bb->hidden, false);
1754 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001755 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001756
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001757 // Now add the basic block.
Vladimir Marko55fff042014-07-10 12:42:52 +01001758 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1759 topological_order_indexes_->Put(bb->id, idx);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001760 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001761
Vladimir Marko55fff042014-07-10 12:42:52 +01001762 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001763 ChildBlockIterator succIter(bb, this);
1764 BasicBlock* successor = succIter.Next();
1765 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001766 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001767 continue;
1768 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001769
Vladimir Marko55fff042014-07-10 12:42:52 +01001770 // One more predecessor was visited.
1771 visited_cnt_values[successor->id] += 1u;
1772 if (visited_cnt_values[successor->id] == successor->predecessors->Size()) {
1773 if (loop_head_stack.empty() ||
1774 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1775 q.push(successor);
1776 } else {
1777 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1778 loop_exit_blocks.SetBit(successor->id);
1779 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001780 }
1781 }
1782 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001783
1784 // Prepare the loop head stack for iteration.
1785 topological_order_loop_head_stack_ =
1786 new (arena_) GrowableArray<std::pair<uint16_t, bool>>(arena_, max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001787}
1788
1789bool BasicBlock::IsExceptionBlock() const {
1790 if (block_type == kExceptionHandling) {
1791 return true;
1792 }
1793 return false;
1794}
1795
Wei Jin04f4d8a2014-05-29 18:04:29 -07001796bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1797 BasicBlock* target = GetBasicBlock(target_id);
1798
1799 if (source == nullptr || target == nullptr)
1800 return false;
1801
1802 int idx;
1803 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1804 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1805 if (bb == source)
1806 return true; // The block has been inserted by a suspend check before.
1807 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1808 return true;
1809 }
1810
1811 return false;
1812}
1813
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001814ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1815 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1816 visited_taken_(false), have_successors_(false) {
1817 // Check if we actually do have successors.
1818 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1819 have_successors_ = true;
1820 successor_iter_.Reset(basic_block_->successor_blocks);
1821 }
1822}
1823
1824BasicBlock* ChildBlockIterator::Next() {
1825 // We check if we have a basic block. If we don't we cannot get next child.
1826 if (basic_block_ == nullptr) {
1827 return nullptr;
1828 }
1829
1830 // If we haven't visited fallthrough, return that.
1831 if (visited_fallthrough_ == false) {
1832 visited_fallthrough_ = true;
1833
1834 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1835 if (result != nullptr) {
1836 return result;
1837 }
1838 }
1839
1840 // If we haven't visited taken, return that.
1841 if (visited_taken_ == false) {
1842 visited_taken_ = true;
1843
1844 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1845 if (result != nullptr) {
1846 return result;
1847 }
1848 }
1849
1850 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1851 if (have_successors_ == true) {
1852 // Get information about next successor block.
Niranjan Kumar989367a2014-06-12 12:15:48 -07001853 for (SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1854 successor_block_info != nullptr;
1855 successor_block_info = successor_iter_.Next()) {
1856 // If block was replaced by zero block, take next one.
1857 if (successor_block_info->block != NullBasicBlockId) {
1858 return mir_graph_->GetBasicBlock(successor_block_info->block);
1859 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001860 }
1861 }
1862
1863 // We do not have anything.
1864 return nullptr;
1865}
1866
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001867BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1868 MIRGraph* mir_graph = c_unit->mir_graph.get();
1869 return Copy(mir_graph);
1870}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001871
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001872BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1873 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001874
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001875 // We don't do a memcpy style copy here because it would lead to a lot of things
1876 // to clean up. Let us do it by hand instead.
1877 // Copy in taken and fallthrough.
1878 result_bb->fall_through = fall_through;
1879 result_bb->taken = taken;
1880
1881 // Copy successor links if needed.
1882 ArenaAllocator* arena = mir_graph->GetArena();
1883
1884 result_bb->successor_block_list_type = successor_block_list_type;
1885 if (result_bb->successor_block_list_type != kNotUsed) {
1886 size_t size = successor_blocks->Size();
1887 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1888 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1889 while (true) {
1890 SuccessorBlockInfo* sbi_old = iterator.Next();
1891 if (sbi_old == nullptr) {
1892 break;
1893 }
1894 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1895 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1896 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001897 }
1898 }
1899
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001900 // Copy offset, method.
1901 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001902
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001903 // Now copy instructions.
1904 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1905 // Get a copy first.
1906 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001907
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001908 // Append it.
1909 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001910 }
1911
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001912 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001913}
1914
1915MIR* MIR::Copy(MIRGraph* mir_graph) {
1916 MIR* res = mir_graph->NewMIR();
1917 *res = *this;
1918
1919 // Remove links
1920 res->next = nullptr;
1921 res->bb = NullBasicBlockId;
1922 res->ssa_rep = nullptr;
1923
1924 return res;
1925}
1926
1927MIR* MIR::Copy(CompilationUnit* c_unit) {
1928 return Copy(c_unit->mir_graph.get());
1929}
1930
1931uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1932 // Default result.
1933 int res = 0;
1934
1935 // We are basically setting the iputs to their igets counterparts.
1936 switch (opcode) {
1937 case Instruction::IPUT:
1938 case Instruction::IPUT_OBJECT:
1939 case Instruction::IPUT_BOOLEAN:
1940 case Instruction::IPUT_BYTE:
1941 case Instruction::IPUT_CHAR:
1942 case Instruction::IPUT_SHORT:
1943 case Instruction::IPUT_QUICK:
1944 case Instruction::IPUT_OBJECT_QUICK:
1945 case Instruction::APUT:
1946 case Instruction::APUT_OBJECT:
1947 case Instruction::APUT_BOOLEAN:
1948 case Instruction::APUT_BYTE:
1949 case Instruction::APUT_CHAR:
1950 case Instruction::APUT_SHORT:
1951 case Instruction::SPUT:
1952 case Instruction::SPUT_OBJECT:
1953 case Instruction::SPUT_BOOLEAN:
1954 case Instruction::SPUT_BYTE:
1955 case Instruction::SPUT_CHAR:
1956 case Instruction::SPUT_SHORT:
1957 // Skip the VR containing what to store.
1958 res = 1;
1959 break;
1960 case Instruction::IPUT_WIDE:
1961 case Instruction::IPUT_WIDE_QUICK:
1962 case Instruction::APUT_WIDE:
1963 case Instruction::SPUT_WIDE:
1964 // Skip the two VRs containing what to store.
1965 res = 2;
1966 break;
1967 default:
1968 // Do nothing in the general case.
1969 break;
1970 }
1971
1972 return res;
1973}
1974
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001975/**
1976 * @brief Given a decoded instruction, it checks whether the instruction
1977 * sets a constant and if it does, more information is provided about the
1978 * constant being set.
1979 * @param ptr_value pointer to a 64-bit holder for the constant.
1980 * @param wide Updated by function whether a wide constant is being set by bytecode.
1981 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1982 */
1983bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1984 bool sets_const = true;
1985 int64_t value = vB;
1986
1987 DCHECK(ptr_value != nullptr);
1988 DCHECK(wide != nullptr);
1989
1990 switch (opcode) {
1991 case Instruction::CONST_4:
1992 case Instruction::CONST_16:
1993 case Instruction::CONST:
1994 *wide = false;
1995 value <<= 32; // In order to get the sign extend.
1996 value >>= 32;
1997 break;
1998 case Instruction::CONST_HIGH16:
1999 *wide = false;
2000 value <<= 48; // In order to get the sign extend.
2001 value >>= 32;
2002 break;
2003 case Instruction::CONST_WIDE_16:
2004 case Instruction::CONST_WIDE_32:
2005 *wide = true;
2006 value <<= 32; // In order to get the sign extend.
2007 value >>= 32;
2008 break;
2009 case Instruction::CONST_WIDE:
2010 *wide = true;
2011 value = vB_wide;
2012 break;
2013 case Instruction::CONST_WIDE_HIGH16:
2014 *wide = true;
2015 value <<= 48; // In order to get the sign extend.
2016 break;
2017 default:
2018 sets_const = false;
2019 break;
2020 }
2021
2022 if (sets_const) {
2023 *ptr_value = value;
2024 }
2025
2026 return sets_const;
2027}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002028
2029void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2030 // Reset flags for all MIRs in bb.
2031 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2032 mir->optimization_flags &= (~reset_flags);
2033 }
2034}
2035
2036void BasicBlock::Hide(CompilationUnit* c_unit) {
2037 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2038 block_type = kDalvikByteCode;
2039
2040 // Mark it as hidden.
2041 hidden = true;
2042
2043 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2044 // are updated to know that they no longer have a parent.
2045 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2046 mir->bb = NullBasicBlockId;
2047 }
2048 first_mir_insn = nullptr;
2049 last_mir_insn = nullptr;
2050
2051 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2052
2053 MIRGraph* mir_graph = c_unit->mir_graph.get();
2054 while (true) {
2055 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
2056 if (pred_bb == nullptr) {
2057 break;
2058 }
2059
2060 // Sadly we have to go through the children by hand here.
2061 pred_bb->ReplaceChild(id, NullBasicBlockId);
2062 }
2063
2064 // Iterate through children of bb we are hiding.
2065 ChildBlockIterator successorChildIter(this, mir_graph);
2066
2067 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
2068 // Replace child with null child.
2069 childPtr->predecessors->Delete(id);
2070 }
2071}
2072
2073bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2074 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2075 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2076 // then it is not live out of this BB.
2077 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2078
2079 int last_ssa_reg = -1;
2080
2081 // Walk through the MIRs backwards.
2082 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2083 // Get ssa rep.
2084 SSARepresentation *ssa_rep = mir->ssa_rep;
2085
2086 // Go through the defines for this MIR.
2087 for (int i = 0; i < ssa_rep->num_defs; i++) {
2088 DCHECK(ssa_rep->defs != nullptr);
2089
2090 // Get the ssa reg.
2091 int def_ssa_reg = ssa_rep->defs[i];
2092
2093 // Get dalvik reg.
2094 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2095
2096 // Compare dalvik regs.
2097 if (dalvik_reg == def_dalvik_reg) {
2098 // We found a def of the register that we are being asked about.
2099 // Remember it.
2100 last_ssa_reg = def_ssa_reg;
2101 }
2102 }
2103 }
2104
2105 if (last_ssa_reg == -1) {
2106 // If we get to this point we couldn't find a define of register user asked about.
2107 // Let's assume the user knows what he's doing so we can be safe and say that if we
2108 // couldn't find a def, it is live out.
2109 return true;
2110 }
2111
2112 // If it is not -1, we found a match, is it ssa_reg?
2113 return (ssa_reg == last_ssa_reg);
2114}
2115
2116bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2117 // We need to check taken, fall_through, and successor_blocks to replace.
2118 bool found = false;
2119 if (taken == old_bb) {
2120 taken = new_bb;
2121 found = true;
2122 }
2123
2124 if (fall_through == old_bb) {
2125 fall_through = new_bb;
2126 found = true;
2127 }
2128
2129 if (successor_block_list_type != kNotUsed) {
2130 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2131 while (true) {
2132 SuccessorBlockInfo* successor_block_info = iterator.Next();
2133 if (successor_block_info == nullptr) {
2134 break;
2135 }
2136 if (successor_block_info->block == old_bb) {
2137 successor_block_info->block = new_bb;
2138 found = true;
2139 }
2140 }
2141 }
2142
2143 return found;
2144}
2145
2146void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
2147 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2148 bool found = false;
2149
2150 while (true) {
2151 BasicBlockId pred_bb_id = iterator.Next();
2152
2153 if (pred_bb_id == NullBasicBlockId) {
2154 break;
2155 }
2156
2157 if (pred_bb_id == old_parent) {
2158 size_t idx = iterator.GetIndex() - 1;
2159 predecessors->Put(idx, new_parent);
2160 found = true;
2161 break;
2162 }
2163 }
2164
2165 // If not found, add it.
2166 if (found == false) {
2167 predecessors->Insert(new_parent);
2168 }
2169}
2170
2171// Create a new basic block with block_id as num_blocks_ that is
2172// post-incremented.
2173BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2174 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2175 block_list_.Insert(res);
2176 return res;
2177}
2178
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002179void MIRGraph::CalculateBasicBlockInformation() {
2180 PassDriverMEPostOpt driver(cu_);
2181 driver.Launch();
2182}
2183
2184void MIRGraph::InitializeBasicBlockData() {
2185 num_blocks_ = block_list_.Size();
2186}
2187
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002188} // namespace art