blob: 24fea71a614f289e9e15836bcde47bd16e2815f7 [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogers6282dc12013-04-18 15:54:02 -070022#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070025#include "dex_instruction-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000026#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000028#include "leb128.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000029
buzbee311ca162013-02-28 15:56:43 -080030namespace art {
31
32#define MAX_PATTERN_LEN 5
33
buzbee1fd33462013-03-25 13:40:45 -070034const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
35 "Phi",
36 "Copy",
37 "FusedCmplFloat",
38 "FusedCmpgFloat",
39 "FusedCmplDouble",
40 "FusedCmpgDouble",
41 "FusedCmpLong",
42 "Nop",
43 "OpNullCheck",
44 "OpRangeCheck",
45 "OpDivZeroCheck",
46 "Check1",
47 "Check2",
48 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040049 "ConstVector",
50 "MoveVector",
51 "PackedMultiply",
52 "PackedAddition",
53 "PackedSubtract",
54 "PackedShiftLeft",
55 "PackedSignedShiftRight",
56 "PackedUnsignedShiftRight",
57 "PackedAnd",
58 "PackedOr",
59 "PackedXor",
60 "PackedAddReduce",
61 "PackedReduce",
62 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070063};
64
buzbee862a7602013-04-05 10:58:54 -070065MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070066 : reg_location_(NULL),
67 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080068 ssa_base_vregs_(NULL),
69 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080070 vreg_to_ssa_map_(NULL),
71 ssa_last_defs_(NULL),
72 is_constant_v_(NULL),
73 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070074 use_counts_(arena, 256, kGrowableArrayMisc),
75 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080076 num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070077 dfs_order_(NULL),
78 dfs_post_order_(NULL),
79 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070080 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080081 i_dom_list_(NULL),
82 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000083 temp_scoped_alloc_(),
84 temp_insn_data_(nullptr),
85 temp_bit_vector_size_(0u),
86 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070087 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080088 try_block_addr_(NULL),
89 entry_block_(NULL),
90 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080091 num_blocks_(0),
92 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070093 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080094 current_method_(kInvalidEntry),
95 current_offset_(kInvalidEntry),
96 def_count_(0),
97 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070098 num_ssa_regs_(0),
99 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700100 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
101 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700102 arena_(arena),
103 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800104 forward_branches_(0),
105 compiler_temps_(arena, 6, kGrowableArrayMisc),
106 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800107 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000108 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000109 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000110 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000111 sfield_lowering_infos_(arena, 0u),
112 method_lowering_infos_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700113 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800114 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
115 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800116}
117
Ian Rogers6282dc12013-04-18 15:54:02 -0700118MIRGraph::~MIRGraph() {
119 STLDeleteElements(&m_units_);
120}
121
buzbee311ca162013-02-28 15:56:43 -0800122/*
123 * Parse an instruction, return the length of the instruction
124 */
Ian Rogers29a26482014-05-02 15:27:29 -0700125int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
126 const Instruction* inst = Instruction::At(code_ptr);
127 decoded_instruction->opcode = inst->Opcode();
128 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
129 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
130 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
131 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
132 if (inst->HasVarArgs()) {
133 inst->GetVarArgs(decoded_instruction->arg);
134 }
135 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800136}
137
138
139/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700140BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700141 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700142 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800143 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700144 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800145 while (insn) {
146 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700147 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800148 insn = insn->next;
149 }
150 if (insn == NULL) {
151 LOG(FATAL) << "Break split failed";
152 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700153 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700154 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800155
156 bottom_block->start_offset = code_offset;
157 bottom_block->first_mir_insn = insn;
158 bottom_block->last_mir_insn = orig_block->last_mir_insn;
159
160 /* If this block was terminated by a return, the flag needs to go with the bottom block */
161 bottom_block->terminated_by_return = orig_block->terminated_by_return;
162 orig_block->terminated_by_return = false;
163
buzbee311ca162013-02-28 15:56:43 -0800164 /* Handle the taken path */
165 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700166 if (bottom_block->taken != NullBasicBlockId) {
167 orig_block->taken = NullBasicBlockId;
168 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
169 bb_taken->predecessors->Delete(orig_block->id);
170 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800171 }
172
173 /* Handle the fallthrough path */
174 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700175 orig_block->fall_through = bottom_block->id;
176 bottom_block->predecessors->Insert(orig_block->id);
177 if (bottom_block->fall_through != NullBasicBlockId) {
178 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
179 bb_fall_through->predecessors->Delete(orig_block->id);
180 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800181 }
182
183 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700184 if (orig_block->successor_block_list_type != kNotUsed) {
185 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
186 bottom_block->successor_blocks = orig_block->successor_blocks;
187 orig_block->successor_block_list_type = kNotUsed;
188 orig_block->successor_blocks = NULL;
189 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800190 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700191 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800192 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700193 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700194 bb->predecessors->Delete(orig_block->id);
195 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800196 }
197 }
198
buzbee0d829482013-10-11 15:24:55 -0700199 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700200 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800201
buzbee311ca162013-02-28 15:56:43 -0800202 /*
203 * Update the immediate predecessor block pointer so that outgoing edges
204 * can be applied to the proper block.
205 */
206 if (immed_pred_block_p) {
207 DCHECK_EQ(*immed_pred_block_p, orig_block);
208 *immed_pred_block_p = bottom_block;
209 }
buzbeeb48819d2013-09-14 16:15:25 -0700210
211 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000212 DCHECK(insn != nullptr);
213 DCHECK(insn != orig_block->first_mir_insn);
214 DCHECK(insn == bottom_block->first_mir_insn);
215 DCHECK_EQ(insn->offset, bottom_block->start_offset);
216 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
217 !IsPseudoMirOp(insn->dalvikInsn.opcode));
218 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
219 MIR* p = insn;
220 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
221 while (p != bottom_block->last_mir_insn) {
222 p = p->next;
223 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700224 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700225 int opcode = p->dalvikInsn.opcode;
226 /*
227 * Some messiness here to ensure that we only enter real opcodes and only the
228 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000229 * CHECK and work portions. Since the 2nd half of a split operation is always
230 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700231 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000232 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
233 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700234 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
235 }
buzbeeb48819d2013-09-14 16:15:25 -0700236 }
237
buzbee311ca162013-02-28 15:56:43 -0800238 return bottom_block;
239}
240
241/*
242 * Given a code offset, find out the block that starts with it. If the offset
243 * is in the middle of an existing block, split it into two. If immed_pred_block_p
244 * is not non-null and is the block being split, update *immed_pred_block_p to
245 * point to the bottom block so that outgoing edges can be set up properly
246 * (by the caller)
247 * Utilizes a map for fast lookup of the typical cases.
248 */
buzbee0d829482013-10-11 15:24:55 -0700249BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700250 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700251 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800252 return NULL;
253 }
buzbeeb48819d2013-09-14 16:15:25 -0700254
255 int block_id = dex_pc_to_block_map_.Get(code_offset);
256 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
257
258 if ((bb != NULL) && (bb->start_offset == code_offset)) {
259 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700260 return bb;
261 }
buzbee311ca162013-02-28 15:56:43 -0800262
buzbeeb48819d2013-09-14 16:15:25 -0700263 // No direct hit.
264 if (!create) {
265 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800266 }
267
buzbeeb48819d2013-09-14 16:15:25 -0700268 if (bb != NULL) {
269 // The target exists somewhere in an existing block.
270 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
271 }
272
273 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700274 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
275 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800276 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700277 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800278 return bb;
279}
280
buzbeeb48819d2013-09-14 16:15:25 -0700281
buzbee311ca162013-02-28 15:56:43 -0800282/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700283void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800284 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700285 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800286
287 if (tries_size == 0) {
288 return;
289 }
290
291 for (int i = 0; i < tries_size; i++) {
292 const DexFile::TryItem* pTry =
293 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700294 DexOffset start_offset = pTry->start_addr_;
295 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800296 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700297 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800298 }
299 }
300
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700301 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800302 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
303 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
304 for (uint32_t idx = 0; idx < handlers_size; idx++) {
305 CatchHandlerIterator iterator(handlers_ptr);
306 for (; iterator.HasNext(); iterator.Next()) {
307 uint32_t address = iterator.GetHandlerAddress();
308 FindBlock(address, false /* split */, true /*create*/,
309 /* immed_pred_block_p */ NULL);
310 }
311 handlers_ptr = iterator.EndDataPointer();
312 }
313}
314
315/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700316BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
317 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700318 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700319 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800320 switch (insn->dalvikInsn.opcode) {
321 case Instruction::GOTO:
322 case Instruction::GOTO_16:
323 case Instruction::GOTO_32:
324 target += insn->dalvikInsn.vA;
325 break;
326 case Instruction::IF_EQ:
327 case Instruction::IF_NE:
328 case Instruction::IF_LT:
329 case Instruction::IF_GE:
330 case Instruction::IF_GT:
331 case Instruction::IF_LE:
332 cur_block->conditional_branch = true;
333 target += insn->dalvikInsn.vC;
334 break;
335 case Instruction::IF_EQZ:
336 case Instruction::IF_NEZ:
337 case Instruction::IF_LTZ:
338 case Instruction::IF_GEZ:
339 case Instruction::IF_GTZ:
340 case Instruction::IF_LEZ:
341 cur_block->conditional_branch = true;
342 target += insn->dalvikInsn.vB;
343 break;
344 default:
345 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
346 }
buzbeeb48819d2013-09-14 16:15:25 -0700347 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700348 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800349 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700350 cur_block->taken = taken_block->id;
351 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800352
353 /* Always terminate the current block for conditional branches */
354 if (flags & Instruction::kContinue) {
355 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
356 /*
357 * If the method is processed
358 * in sequential order from the
359 * beginning, we don't need to
360 * specify split for continue
361 * blocks. However, this
362 * routine can be called by
363 * compileLoop, which starts
364 * parsing the method from an
365 * arbitrary address in the
366 * method body.
367 */
368 true,
369 /* create */
370 true,
371 /* immed_pred_block_p */
372 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700373 cur_block->fall_through = fallthrough_block->id;
374 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800375 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700376 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800377 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800378 }
379 return cur_block;
380}
381
382/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800383BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
384 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800385 const uint16_t* switch_data =
386 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
387 int size;
388 const int* keyTable;
389 const int* target_table;
390 int i;
391 int first_key;
392
393 /*
394 * Packed switch data format:
395 * ushort ident = 0x0100 magic value
396 * ushort size number of entries in the table
397 * int first_key first (and lowest) switch case value
398 * int targets[size] branch targets, relative to switch opcode
399 *
400 * Total size is (4+size*2) 16-bit code units.
401 */
402 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
403 DCHECK_EQ(static_cast<int>(switch_data[0]),
404 static_cast<int>(Instruction::kPackedSwitchSignature));
405 size = switch_data[1];
406 first_key = switch_data[2] | (switch_data[3] << 16);
407 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700408 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800409 /*
410 * Sparse switch data format:
411 * ushort ident = 0x0200 magic value
412 * ushort size number of entries in the table; > 0
413 * int keys[size] keys, sorted low-to-high; 32-bit aligned
414 * int targets[size] branch targets, relative to switch opcode
415 *
416 * Total size is (2+size*4) 16-bit code units.
417 */
418 } else {
419 DCHECK_EQ(static_cast<int>(switch_data[0]),
420 static_cast<int>(Instruction::kSparseSwitchSignature));
421 size = switch_data[1];
422 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
423 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700424 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800425 }
426
buzbee0d829482013-10-11 15:24:55 -0700427 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800428 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700429 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800430 }
buzbee0d829482013-10-11 15:24:55 -0700431 cur_block->successor_block_list_type =
432 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
433 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700434 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800435
436 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700437 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800438 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700439 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700440 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000441 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700442 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800443 successor_block_info->key =
444 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
445 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700446 cur_block->successor_blocks->Insert(successor_block_info);
447 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800448 }
449
450 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700451 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
452 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700453 cur_block->fall_through = fallthrough_block->id;
454 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800455 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800456}
457
458/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700459BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
460 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700461 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700462 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800463 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
464 bool build_all_edges =
465 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800466
467 /* In try block */
468 if (in_try_block) {
469 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
470
buzbee0d829482013-10-11 15:24:55 -0700471 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800472 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
473 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700474 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800475 }
476
buzbee0d829482013-10-11 15:24:55 -0700477 cur_block->successor_block_list_type = kCatch;
478 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700479 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800480
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700481 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700482 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800483 false /* creat */, NULL /* immed_pred_block_p */);
484 catch_block->catch_entry = true;
485 if (kIsDebugBuild) {
486 catches_.insert(catch_block->start_offset);
487 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700488 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000489 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700490 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800491 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700492 cur_block->successor_blocks->Insert(successor_block_info);
493 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800494 }
buzbee17189ac2013-11-08 11:07:02 -0800495 } else if (build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700496 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700497 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700498 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800499 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700500 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800501 }
502
buzbee17189ac2013-11-08 11:07:02 -0800503 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800504 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700505 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700506 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800507 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
508 /* immed_pred_block_p */ NULL);
509 }
510 if (!in_try_block) {
511 // Don't split a THROW that can't rethrow - we're done.
512 return cur_block;
513 }
514 }
515
buzbee17189ac2013-11-08 11:07:02 -0800516 if (!build_all_edges) {
517 /*
518 * Even though there is an exception edge here, control cannot return to this
519 * method. Thus, for the purposes of dataflow analysis and optimization, we can
520 * ignore the edge. Doing this reduces compile time, and increases the scope
521 * of the basic-block level optimization pass.
522 */
523 return cur_block;
524 }
525
buzbee311ca162013-02-28 15:56:43 -0800526 /*
527 * Split the potentially-throwing instruction into two parts.
528 * The first half will be a pseudo-op that captures the exception
529 * edges and terminates the basic block. It always falls through.
530 * Then, create a new basic block that begins with the throwing instruction
531 * (minus exceptions). Note: this new basic block must NOT be entered into
532 * the block_map. If the potentially-throwing instruction is the target of a
533 * future branch, we need to find the check psuedo half. The new
534 * basic block containing the work portion of the instruction should
535 * only be entered via fallthrough from the block containing the
536 * pseudo exception edge MIR. Note also that this new block is
537 * not automatically terminated after the work portion, and may
538 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700539 *
540 * Note also that the dex_pc_to_block_map_ entry for the potentially
541 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800542 */
buzbee862a7602013-04-05 10:58:54 -0700543 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
544 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800545 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700546 cur_block->fall_through = new_block->id;
547 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700548 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800549 *new_insn = *insn;
550 insn->dalvikInsn.opcode =
551 static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700552 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800553 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700554 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800555 return new_block;
556}
557
558/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
559void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700560 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700561 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800562 current_code_item_ = code_item;
563 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
564 current_method_ = m_units_.size();
565 current_offset_ = 0;
566 // TODO: will need to snapshot stack image and use that as the mir context identification.
567 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000568 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
569 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800570 const uint16_t* code_ptr = current_code_item_->insns_;
571 const uint16_t* code_end =
572 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
573
574 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700575 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700576 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700577 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 -0700578
buzbee311ca162013-02-28 15:56:43 -0800579 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700580 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
581 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800582
583 // If this is the first method, set up default entry and exit blocks.
584 if (current_method_ == 0) {
585 DCHECK(entry_block_ == NULL);
586 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700587 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700588 // Use id 0 to represent a null block.
589 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
590 DCHECK_EQ(null_block->id, NullBasicBlockId);
591 null_block->hidden = true;
592 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700593 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700594 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700595 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700596 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800597 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
598 cu_->dex_file = &dex_file;
599 cu_->class_def_idx = class_def_idx;
600 cu_->method_idx = method_idx;
601 cu_->access_flags = access_flags;
602 cu_->invoke_type = invoke_type;
603 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
604 cu_->num_ins = current_code_item_->ins_size_;
605 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
606 cu_->num_outs = current_code_item_->outs_size_;
607 cu_->num_dalvik_registers = current_code_item_->registers_size_;
608 cu_->insns = current_code_item_->insns_;
609 cu_->code_item = current_code_item_;
610 } else {
611 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
612 /*
613 * Will need to manage storage for ins & outs, push prevous state and update
614 * insert point.
615 */
616 }
617
618 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700619 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700620 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800621 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700622 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700623 // TODO: for inlining support, insert at the insert point rather than entry block.
624 entry_block_->fall_through = cur_block->id;
625 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800626
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000627 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800628 ProcessTryCatchBlocks();
629
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000630 uint64_t merged_df_flags = 0u;
631
buzbee311ca162013-02-28 15:56:43 -0800632 /* Parse all instructions and put them into containing basic blocks */
633 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700634 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800635 insn->offset = current_offset_;
636 insn->m_unit_index = current_method_;
637 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800638 Instruction::Code opcode = insn->dalvikInsn.opcode;
639 if (opcode_count_ != NULL) {
640 opcode_count_[static_cast<int>(opcode)]++;
641 }
642
buzbee311ca162013-02-28 15:56:43 -0800643 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800644 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800645
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700646 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000647 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800648
649 if (df_flags & DF_HAS_DEFS) {
650 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
651 }
652
buzbee1da1e2f2013-11-15 13:37:01 -0800653 if (df_flags & DF_LVN) {
654 cur_block->use_lvn = true; // Run local value numbering on this basic block.
655 }
656
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700657 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700658 if (opcode == Instruction::NOP) {
659 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
660 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
661 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
662 uint16_t following_raw_instruction = code_ptr[1];
663 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
664 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
665 (following_raw_instruction == Instruction::kArrayDataSignature)) {
666 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
667 }
668 }
669 if (width == 1) {
670 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700671 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700672 } else {
buzbee0d829482013-10-11 15:24:55 -0700673 DCHECK(cur_block->fall_through == NullBasicBlockId);
674 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700675 // Unreachable instruction, mark for no continuation.
676 flags &= ~Instruction::kContinue;
677 }
678 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700679 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700680 }
681
buzbeeb48819d2013-09-14 16:15:25 -0700682 // Associate the starting dex_pc for this opcode with its containing basic block.
683 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
684
buzbee27247762013-07-28 12:03:58 -0700685 code_ptr += width;
686
buzbee311ca162013-02-28 15:56:43 -0800687 if (flags & Instruction::kBranch) {
688 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
689 width, flags, code_ptr, code_end);
690 } else if (flags & Instruction::kReturn) {
691 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700692 cur_block->fall_through = exit_block_->id;
693 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800694 /*
695 * Terminate the current block if there are instructions
696 * afterwards.
697 */
698 if (code_ptr < code_end) {
699 /*
700 * Create a fallthrough block for real instructions
701 * (incl. NOP).
702 */
buzbee27247762013-07-28 12:03:58 -0700703 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
704 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800705 }
706 } else if (flags & Instruction::kThrow) {
707 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
708 code_ptr, code_end);
709 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800710 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800711 }
buzbeeb1f1d642014-02-27 12:55:32 -0800712 if (verify_flags & Instruction::kVerifyVarArgRange) {
713 /*
714 * The Quick backend's runtime model includes a gap between a method's
715 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
716 * which spans the gap is somewhat complicated, and should not happen
717 * in normal usage of dx. Punt to the interpreter.
718 */
719 int first_reg_in_range = insn->dalvikInsn.vC;
720 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
721 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
722 punt_to_interpreter_ = true;
723 }
724 }
buzbee311ca162013-02-28 15:56:43 -0800725 current_offset_ += width;
726 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
727 false, /* immed_pred_block_p */ NULL);
728 if (next_block) {
729 /*
730 * The next instruction could be the target of a previously parsed
731 * forward branch so a block is already created. If the current
732 * instruction is not an unconditional branch, connect them through
733 * the fall-through link.
734 */
buzbee0d829482013-10-11 15:24:55 -0700735 DCHECK(cur_block->fall_through == NullBasicBlockId ||
736 GetBasicBlock(cur_block->fall_through) == next_block ||
737 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800738
buzbee0d829482013-10-11 15:24:55 -0700739 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
740 cur_block->fall_through = next_block->id;
741 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800742 }
743 cur_block = next_block;
744 }
745 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000746 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000747
buzbee311ca162013-02-28 15:56:43 -0800748 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
749 DumpCFG("/sdcard/1_post_parse_cfg/", true);
750 }
751
752 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700753 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800754 }
755}
756
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700757void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800758 DCHECK(opcode_count_ != NULL);
759 LOG(INFO) << "Opcode Count";
760 for (int i = 0; i < kNumPackedOpcodes; i++) {
761 if (opcode_count_[i] != 0) {
762 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
763 << " " << opcode_count_[i];
764 }
765 }
766}
767
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700768uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
769 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
770 return oat_data_flow_attributes_[opcode];
771}
772
773uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
774 DCHECK(mir != nullptr);
775 Instruction::Code opcode = mir->dalvikInsn.opcode;
776 return GetDataFlowAttributes(opcode);
777}
778
buzbee311ca162013-02-28 15:56:43 -0800779// TODO: use a configurable base prefix, and adjust callers to supply pass name.
780/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800781void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800782 FILE* file;
783 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
784 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800785 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
786 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
787 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800788 file = fopen(fname.c_str(), "w");
789 if (file == NULL) {
790 return;
791 }
792 fprintf(file, "digraph G {\n");
793
794 fprintf(file, " rankdir=TB\n");
795
796 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
797 int idx;
798
799 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700800 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700801 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700802 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800803 if (bb->block_type == kDead) continue;
804 if (bb->block_type == kEntryBlock) {
805 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
806 } else if (bb->block_type == kExitBlock) {
807 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
808 } else if (bb->block_type == kDalvikByteCode) {
809 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
810 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700811 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800812 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
813 bb->first_mir_insn ? " | " : " ");
814 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
815 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400816 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
817 if (opcode == kMirOpConstVector) {
818 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
819 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
820 mir->dalvikInsn.vA,
821 mir->dalvikInsn.vB,
822 mir->dalvikInsn.arg[0],
823 mir->dalvikInsn.arg[1],
824 mir->dalvikInsn.arg[2],
825 mir->dalvikInsn.arg[3],
826 mir->next ? " | " : " ");
827 } else {
828 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
829 extended_mir_op_names_[opcode - kMirOpFirst],
830 mir->dalvikInsn.vA,
831 mir->dalvikInsn.vB,
832 mir->dalvikInsn.vC,
833 mir->next ? " | " : " ");
834 }
835 } else {
836 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
837 mir->ssa_rep ? GetDalvikDisassembly(mir) :
838 (opcode < kMirOpFirst) ?
839 Instruction::Name(mir->dalvikInsn.opcode) :
840 extended_mir_op_names_[opcode - kMirOpFirst],
841 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
842 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
843 mir->next ? " | " : " ");
844 }
buzbee311ca162013-02-28 15:56:43 -0800845 }
846 fprintf(file, " }\"];\n\n");
847 } else if (bb->block_type == kExceptionHandling) {
848 char block_name[BLOCK_NAME_LEN];
849
850 GetBlockName(bb, block_name);
851 fprintf(file, " %s [shape=invhouse];\n", block_name);
852 }
853
854 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
855
buzbee0d829482013-10-11 15:24:55 -0700856 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800857 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700858 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800859 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
860 block_name1, block_name2);
861 }
buzbee0d829482013-10-11 15:24:55 -0700862 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800863 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700864 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800865 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
866 }
867
buzbee0d829482013-10-11 15:24:55 -0700868 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800869 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
870 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700871 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
872 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700873 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800874
875 int succ_id = 0;
876 while (true) {
877 if (successor_block_info == NULL) break;
878
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700879 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700880 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800881
882 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
883 succ_id++,
884 successor_block_info->key,
885 dest_block->start_offset,
886 (next_successor_block_info != NULL) ? " | " : " ");
887
888 successor_block_info = next_successor_block_info;
889 }
890 fprintf(file, " }\"];\n\n");
891
892 GetBlockName(bb, block_name1);
893 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
894 block_name1, bb->start_offset, bb->id);
895
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700896 // Link the successor pseudo-block with all of its potential targets.
897 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800898
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700899 succ_id = 0;
900 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700901 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700902 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800903
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700904 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800905
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700906 GetBlockName(dest_block, block_name2);
907 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
908 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800909 }
910 }
911 fprintf(file, "\n");
912
913 if (cu_->verbose) {
914 /* Display the dominator tree */
915 GetBlockName(bb, block_name1);
916 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
917 block_name1, block_name1);
918 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700919 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800920 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
921 }
922 }
923 }
924 fprintf(file, "}\n");
925 fclose(file);
926}
927
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700928/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700929void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700930 // Insert it after the last MIR.
931 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -0700932}
933
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700934void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
935 // Insert it after the last MIR.
936 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
937}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700938
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700939void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
940 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
941 MIR* new_mir = *it;
942
943 // Add a copy of each MIR.
944 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
945 }
buzbee1fd33462013-03-25 13:40:45 -0700946}
947
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700948/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700949void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700950 InsertMIRListAfter(current_mir, new_mir, new_mir);
951}
buzbee1fd33462013-03-25 13:40:45 -0700952
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700953void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
954 // If no MIR, we are done.
955 if (first_list_mir == nullptr || last_list_mir == nullptr) {
956 return;
buzbee1fd33462013-03-25 13:40:45 -0700957 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700958
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700959 // If insert_after is null, assume BB is empty.
960 if (insert_after == nullptr) {
961 first_mir_insn = first_list_mir;
962 last_mir_insn = last_list_mir;
963 last_list_mir->next = nullptr;
964 } else {
965 MIR* after_list = insert_after->next;
966 insert_after->next = first_list_mir;
967 last_list_mir->next = after_list;
968 if (after_list == nullptr) {
969 last_mir_insn = last_list_mir;
970 }
971 }
972
973 // Set this BB to be the basic block of the MIRs.
974 MIR* last = last_list_mir->next;
975 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
976 mir->bb = id;
977 }
978}
979
980/* Insert an MIR instruction to the head of a basic block. */
981void BasicBlock::PrependMIR(MIR* mir) {
982 InsertMIRListBefore(first_mir_insn, mir, mir);
983}
984
985void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
986 // Insert it before the first MIR.
987 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
988}
989
990void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
991 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
992 MIR* mir = *it;
993
994 InsertMIRListBefore(first_mir_insn, mir, mir);
995 }
996}
997
998/* Insert a MIR instruction before the specified MIR. */
999void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1000 // Insert as a single element list.
1001 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001002}
1003
1004MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1005 MIR* current = first_mir_insn;
1006
1007 while (current != nullptr) {
1008 MIR* next = current->next;
1009
1010 if (next == mir) {
1011 return current;
1012 }
1013
1014 current = next;
1015 }
1016
1017 return nullptr;
1018}
1019
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001020void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1021 // If no MIR, we are done.
1022 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1023 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001024 }
1025
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001026 // If insert_before is null, assume BB is empty.
1027 if (insert_before == nullptr) {
1028 first_mir_insn = first_list_mir;
1029 last_mir_insn = last_list_mir;
1030 last_list_mir->next = nullptr;
1031 } else {
1032 if (first_mir_insn == insert_before) {
1033 last_list_mir->next = first_mir_insn;
1034 first_mir_insn = first_list_mir;
1035 } else {
1036 // Find the preceding MIR.
1037 MIR* before_list = FindPreviousMIR(insert_before);
1038 DCHECK(before_list != nullptr);
1039 before_list->next = first_list_mir;
1040 last_list_mir->next = insert_before;
1041 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001042 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001043
1044 // Set this BB to be the basic block of the MIRs.
1045 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1046 mir->bb = id;
1047 }
1048}
1049
1050bool BasicBlock::RemoveMIR(MIR* mir) {
1051 // Remove as a single element list.
1052 return RemoveMIRList(mir, mir);
1053}
1054
1055bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1056 if (first_list_mir == nullptr) {
1057 return false;
1058 }
1059
1060 // Try to find the MIR.
1061 MIR* before_list = nullptr;
1062 MIR* after_list = nullptr;
1063
1064 // If we are removing from the beginning of the MIR list.
1065 if (first_mir_insn == first_list_mir) {
1066 before_list = nullptr;
1067 } else {
1068 before_list = FindPreviousMIR(first_list_mir);
1069 if (before_list == nullptr) {
1070 // We did not find the mir.
1071 return false;
1072 }
1073 }
1074
1075 // Remove the BB information and also find the after_list
1076 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1077 mir->bb = NullBasicBlockId;
1078 }
1079
1080 after_list = last_list_mir->next;
1081
1082 // If there is nothing before the list, after_list is the first_mir
1083 if (before_list == nullptr) {
1084 first_mir_insn = after_list;
1085 }
1086
1087 // If there is nothing after the list, before_list is last_mir
1088 if (after_list == nullptr) {
1089 last_mir_insn = before_list;
1090 }
1091
1092 return true;
buzbee1fd33462013-03-25 13:40:45 -07001093}
1094
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001095MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001096 MIR* next_mir = nullptr;
1097
1098 if (current != nullptr) {
1099 next_mir = current->next;
1100 }
1101
1102 if (next_mir == nullptr) {
1103 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001104 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1105 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001106 }
1107 }
1108
1109 return next_mir;
1110}
1111
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001112char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001113 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001114 std::string str;
1115 int flags = 0;
1116 int opcode = insn.opcode;
1117 char* ret;
1118 bool nop = false;
1119 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001120 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001121 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1122 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1123
1124 // Handle special cases.
1125 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1126 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1127 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001128 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001129 insn = mir->meta.throw_insn->dalvikInsn;
1130 ssa_rep = mir->meta.throw_insn->ssa_rep;
1131 defs = ssa_rep->num_defs;
1132 uses = ssa_rep->num_uses;
1133 opcode = insn.opcode;
1134 } else if (opcode == kMirOpNop) {
1135 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001136 // Recover original opcode.
1137 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1138 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001139 nop = true;
1140 }
1141
1142 if (opcode >= kMirOpFirst) {
1143 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1144 } else {
1145 dalvik_format = Instruction::FormatOf(insn.opcode);
1146 flags = Instruction::FlagsOf(insn.opcode);
1147 str.append(Instruction::Name(insn.opcode));
1148 }
1149
1150 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001151 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001152 str.append(StringPrintf(" %s = (%s",
1153 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1154 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001155 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001156 int i;
1157 for (i = 1; i < uses; i++) {
1158 str.append(StringPrintf(", %s:%d",
1159 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1160 incoming[i]));
1161 }
1162 str.append(")");
1163 } else if ((flags & Instruction::kBranch) != 0) {
1164 // For branches, decode the instructions to print out the branch targets.
1165 int offset = 0;
1166 switch (dalvik_format) {
1167 case Instruction::k21t:
1168 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1169 offset = insn.vB;
1170 break;
1171 case Instruction::k22t:
1172 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1173 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1174 offset = insn.vC;
1175 break;
1176 case Instruction::k10t:
1177 case Instruction::k20t:
1178 case Instruction::k30t:
1179 offset = insn.vA;
1180 break;
1181 default:
1182 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1183 }
1184 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1185 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1186 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001187 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001188 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1189 (dalvik_format == Instruction::k3rc));
1190 if (defs != 0) {
1191 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1192 if (uses != 0) {
1193 str.append(", ");
1194 }
1195 }
1196 for (int i = 0; i < uses; i++) {
1197 str.append(
1198 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1199 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1200 // For the listing, skip the high sreg.
1201 i++;
1202 }
1203 if (i != (uses -1)) {
1204 str.append(",");
1205 }
1206 }
1207 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001208 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001209 case Instruction::k21s:
1210 case Instruction::k31i:
1211 case Instruction::k21h:
1212 str.append(StringPrintf(", #%d", insn.vB));
1213 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001214 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001215 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001216 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001217 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001218 case Instruction::k31c:
1219 str.append(StringPrintf(", index #%d", insn.vB));
1220 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001221 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001222 str.append(StringPrintf(", index #%d", insn.vC));
1223 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001224 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001225 case Instruction::k22b:
1226 str.append(StringPrintf(", #%d", insn.vC));
1227 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001228 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001229 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001230 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001231 }
buzbee1fd33462013-03-25 13:40:45 -07001232 }
1233 if (nop) {
1234 str.append("]--optimized away");
1235 }
1236 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001237 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001238 strncpy(ret, str.c_str(), length);
1239 return ret;
1240}
1241
1242/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001243void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001244 static const struct { const char before; const char after; } match[] = {
1245 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1246 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1247 };
buzbee1fd33462013-03-25 13:40:45 -07001248 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1249 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1250 }
1251}
1252
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001253std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001254 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1255 // the arena. We should be smarter and just place straight into the arena, or compute the
1256 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001257 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1258}
1259
1260// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001261std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001262 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001263 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001264 return GetSSAName(ssa_reg);
1265 }
1266 if (IsConst(reg_location_[ssa_reg])) {
1267 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001268 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001269 ConstantValueWide(reg_location_[ssa_reg]));
1270 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001271 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001272 ConstantValue(reg_location_[ssa_reg]));
1273 }
1274 } else {
1275 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1276 }
1277}
1278
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001279void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001280 switch (bb->block_type) {
1281 case kEntryBlock:
1282 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1283 break;
1284 case kExitBlock:
1285 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1286 break;
1287 case kDalvikByteCode:
1288 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1289 break;
1290 case kExceptionHandling:
1291 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1292 bb->id);
1293 break;
1294 default:
1295 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1296 break;
1297 }
1298}
1299
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001300const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001301 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001302 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1303 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1304}
1305
1306/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001307void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001308 BasicBlock* bb;
1309 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001310 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001311 "Entry Block",
1312 "Code Block",
1313 "Exit Block",
1314 "Exception Handling",
1315 "Catch Block"
1316 };
1317
1318 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1319 LOG(INFO) << cu_->insns << " insns";
1320 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001321 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001322
1323 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001324 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001325 if (bb == NULL) break;
1326 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1327 bb->id,
1328 block_type_names[bb->block_type],
1329 bb->start_offset,
1330 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1331 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001332 if (bb->taken != NullBasicBlockId) {
1333 LOG(INFO) << " Taken branch: block " << bb->taken
1334 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001335 }
buzbee0d829482013-10-11 15:24:55 -07001336 if (bb->fall_through != NullBasicBlockId) {
1337 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1338 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001339 }
1340 }
1341}
1342
1343/*
1344 * Build an array of location records for the incoming arguments.
1345 * Note: one location record per word of arguments, with dummy
1346 * high-word loc for wide arguments. Also pull up any following
1347 * MOVE_RESULT and incorporate it into the invoke.
1348 */
1349CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001350 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001351 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001352 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001353 MIR* move_result_mir = FindMoveResult(bb, mir);
1354 if (move_result_mir == NULL) {
1355 info->result.location = kLocInvalid;
1356 } else {
1357 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001358 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1359 }
1360 info->num_arg_words = mir->ssa_rep->num_uses;
1361 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001362 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001363 for (int i = 0; i < info->num_arg_words; i++) {
1364 info->args[i] = GetRawSrc(mir, i);
1365 }
1366 info->opt_flags = mir->optimization_flags;
1367 info->type = type;
1368 info->is_range = is_range;
1369 info->index = mir->dalvikInsn.vB;
1370 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001371 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001372 return info;
1373}
1374
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001375// Allocate a new MIR.
1376MIR* MIRGraph::NewMIR() {
1377 MIR* mir = new (arena_) MIR();
1378 return mir;
1379}
1380
buzbee862a7602013-04-05 10:58:54 -07001381// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001382BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001383 BasicBlock* bb = new (arena_) BasicBlock();
1384
buzbee862a7602013-04-05 10:58:54 -07001385 bb->block_type = block_type;
1386 bb->id = block_id;
1387 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001388 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001389 (block_type == kExitBlock) ? 2048 : 2,
1390 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001391 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001392 block_id_map_.Put(block_id, block_id);
1393 return bb;
1394}
buzbee1fd33462013-03-25 13:40:45 -07001395
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001396void MIRGraph::InitializeConstantPropagation() {
1397 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001398 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001399}
1400
1401void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001402 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001403 int num_ssa_regs = GetNumSSARegs();
1404 use_counts_.Resize(num_ssa_regs + 32);
1405 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001406 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001407 for (int i = 0; i < num_ssa_regs; i++) {
1408 use_counts_.Insert(0);
1409 raw_use_counts_.Insert(0);
1410 }
1411}
1412
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001413void MIRGraph::SSATransformationStart() {
1414 DCHECK(temp_scoped_alloc_.get() == nullptr);
1415 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1416 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1417 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1418 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1419
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001420 /* Compute the DFS order */
1421 ComputeDFSOrders();
1422
1423 /* Compute the dominator info */
1424 ComputeDominators();
1425
1426 /* Allocate data structures in preparation for SSA conversion */
1427 CompilerInitializeSSAConversion();
1428
1429 /* Find out the "Dalvik reg def x block" relation */
1430 ComputeDefBlockMatrix();
1431
1432 /* Insert phi nodes to dominance frontiers for all variables */
1433 InsertPhiNodes();
1434
1435 /* Rename register names by local defs and phi nodes */
1436 ClearAllVisitedFlags();
1437 DoDFSPreOrderSSARename(GetEntryBlock());
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001438}
1439
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001440void MIRGraph::SSATransformationEnd() {
1441 // Verify the dataflow information after the pass.
1442 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1443 VerifyDataflow();
1444 }
1445
1446 temp_bit_vector_size_ = 0u;
1447 temp_bit_vector_ = nullptr;
1448 DCHECK(temp_scoped_alloc_.get() != nullptr);
1449 temp_scoped_alloc_.reset();
1450}
1451
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001452void MIRGraph::ComputeTopologicalSortOrder() {
1453 std::queue<BasicBlock *> q;
1454 std::map<int, int> visited_cnt_values;
1455
1456 // Clear the nodes.
1457 ClearAllVisitedFlags();
1458
1459 // Create the topological order if need be.
1460 if (topological_order_ != nullptr) {
1461 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, 0);
1462 }
1463 topological_order_->Reset();
1464
1465 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1466 // also fill initial queue.
1467 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1468
1469 while (true) {
1470 BasicBlock* bb = iterator.Next();
1471
1472 if (bb == nullptr) {
1473 break;
1474 }
1475
1476 if (bb->hidden == true) {
1477 continue;
1478 }
1479
1480 visited_cnt_values[bb->id] = bb->predecessors->Size();
1481
1482 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1483 // To process loops we should not wait for dominators.
1484 while (true) {
1485 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1486
1487 if (pred_bb == nullptr) {
1488 break;
1489 }
1490
1491 if (pred_bb->dominators == nullptr || pred_bb->hidden == true) {
1492 continue;
1493 }
1494
1495 // Skip the backward branch.
1496 if (pred_bb->dominators->IsBitSet(bb->id) != 0) {
1497 visited_cnt_values[bb->id]--;
1498 }
1499 }
1500
1501 // Add entry block to queue.
1502 if (visited_cnt_values[bb->id] == 0) {
1503 q.push(bb);
1504 }
1505 }
1506
1507 while (q.size() > 0) {
1508 // Get top.
1509 BasicBlock *bb = q.front();
1510 q.pop();
1511
1512 DCHECK_EQ(bb->hidden, false);
1513
1514 if (bb->IsExceptionBlock() == true) {
1515 continue;
1516 }
1517
1518 // We've visited all the predecessors. So, we can visit bb.
1519 if (bb->visited == false) {
1520 bb->visited = true;
1521
1522 // Now add the basic block.
1523 topological_order_->Insert(bb->id);
1524
1525 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1526 ChildBlockIterator succIter(bb, this);
1527 BasicBlock *successor = succIter.Next();
1528 while (successor != nullptr) {
1529 // one more predecessor was visited.
1530 visited_cnt_values[successor->id]--;
1531
1532 if (visited_cnt_values[successor->id] <= 0 && successor->visited == false && successor->hidden == false) {
1533 q.push(successor);
1534 }
1535
1536 // Take next successor.
1537 successor = succIter.Next();
1538 }
1539 }
1540 }
1541}
1542
1543bool BasicBlock::IsExceptionBlock() const {
1544 if (block_type == kExceptionHandling) {
1545 return true;
1546 }
1547 return false;
1548}
1549
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001550ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1551 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1552 visited_taken_(false), have_successors_(false) {
1553 // Check if we actually do have successors.
1554 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1555 have_successors_ = true;
1556 successor_iter_.Reset(basic_block_->successor_blocks);
1557 }
1558}
1559
1560BasicBlock* ChildBlockIterator::Next() {
1561 // We check if we have a basic block. If we don't we cannot get next child.
1562 if (basic_block_ == nullptr) {
1563 return nullptr;
1564 }
1565
1566 // If we haven't visited fallthrough, return that.
1567 if (visited_fallthrough_ == false) {
1568 visited_fallthrough_ = true;
1569
1570 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1571 if (result != nullptr) {
1572 return result;
1573 }
1574 }
1575
1576 // If we haven't visited taken, return that.
1577 if (visited_taken_ == false) {
1578 visited_taken_ = true;
1579
1580 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1581 if (result != nullptr) {
1582 return result;
1583 }
1584 }
1585
1586 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1587 if (have_successors_ == true) {
1588 // Get information about next successor block.
1589 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1590
1591 // If we don't have anymore successors, return nullptr.
1592 if (successor_block_info != nullptr) {
1593 return mir_graph_->GetBasicBlock(successor_block_info->block);
1594 }
1595 }
1596
1597 // We do not have anything.
1598 return nullptr;
1599}
1600
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001601BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1602 MIRGraph* mir_graph = c_unit->mir_graph.get();
1603 return Copy(mir_graph);
1604}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001605
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001606BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1607 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001608
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001609 // We don't do a memcpy style copy here because it would lead to a lot of things
1610 // to clean up. Let us do it by hand instead.
1611 // Copy in taken and fallthrough.
1612 result_bb->fall_through = fall_through;
1613 result_bb->taken = taken;
1614
1615 // Copy successor links if needed.
1616 ArenaAllocator* arena = mir_graph->GetArena();
1617
1618 result_bb->successor_block_list_type = successor_block_list_type;
1619 if (result_bb->successor_block_list_type != kNotUsed) {
1620 size_t size = successor_blocks->Size();
1621 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1622 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1623 while (true) {
1624 SuccessorBlockInfo* sbi_old = iterator.Next();
1625 if (sbi_old == nullptr) {
1626 break;
1627 }
1628 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1629 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1630 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001631 }
1632 }
1633
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001634 // Copy offset, method.
1635 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001636
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001637 // Now copy instructions.
1638 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1639 // Get a copy first.
1640 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001641
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001642 // Append it.
1643 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001644 }
1645
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001646 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001647}
1648
1649MIR* MIR::Copy(MIRGraph* mir_graph) {
1650 MIR* res = mir_graph->NewMIR();
1651 *res = *this;
1652
1653 // Remove links
1654 res->next = nullptr;
1655 res->bb = NullBasicBlockId;
1656 res->ssa_rep = nullptr;
1657
1658 return res;
1659}
1660
1661MIR* MIR::Copy(CompilationUnit* c_unit) {
1662 return Copy(c_unit->mir_graph.get());
1663}
1664
1665uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1666 // Default result.
1667 int res = 0;
1668
1669 // We are basically setting the iputs to their igets counterparts.
1670 switch (opcode) {
1671 case Instruction::IPUT:
1672 case Instruction::IPUT_OBJECT:
1673 case Instruction::IPUT_BOOLEAN:
1674 case Instruction::IPUT_BYTE:
1675 case Instruction::IPUT_CHAR:
1676 case Instruction::IPUT_SHORT:
1677 case Instruction::IPUT_QUICK:
1678 case Instruction::IPUT_OBJECT_QUICK:
1679 case Instruction::APUT:
1680 case Instruction::APUT_OBJECT:
1681 case Instruction::APUT_BOOLEAN:
1682 case Instruction::APUT_BYTE:
1683 case Instruction::APUT_CHAR:
1684 case Instruction::APUT_SHORT:
1685 case Instruction::SPUT:
1686 case Instruction::SPUT_OBJECT:
1687 case Instruction::SPUT_BOOLEAN:
1688 case Instruction::SPUT_BYTE:
1689 case Instruction::SPUT_CHAR:
1690 case Instruction::SPUT_SHORT:
1691 // Skip the VR containing what to store.
1692 res = 1;
1693 break;
1694 case Instruction::IPUT_WIDE:
1695 case Instruction::IPUT_WIDE_QUICK:
1696 case Instruction::APUT_WIDE:
1697 case Instruction::SPUT_WIDE:
1698 // Skip the two VRs containing what to store.
1699 res = 2;
1700 break;
1701 default:
1702 // Do nothing in the general case.
1703 break;
1704 }
1705
1706 return res;
1707}
1708
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001709/**
1710 * @brief Given a decoded instruction, it checks whether the instruction
1711 * sets a constant and if it does, more information is provided about the
1712 * constant being set.
1713 * @param ptr_value pointer to a 64-bit holder for the constant.
1714 * @param wide Updated by function whether a wide constant is being set by bytecode.
1715 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1716 */
1717bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1718 bool sets_const = true;
1719 int64_t value = vB;
1720
1721 DCHECK(ptr_value != nullptr);
1722 DCHECK(wide != nullptr);
1723
1724 switch (opcode) {
1725 case Instruction::CONST_4:
1726 case Instruction::CONST_16:
1727 case Instruction::CONST:
1728 *wide = false;
1729 value <<= 32; // In order to get the sign extend.
1730 value >>= 32;
1731 break;
1732 case Instruction::CONST_HIGH16:
1733 *wide = false;
1734 value <<= 48; // In order to get the sign extend.
1735 value >>= 32;
1736 break;
1737 case Instruction::CONST_WIDE_16:
1738 case Instruction::CONST_WIDE_32:
1739 *wide = true;
1740 value <<= 32; // In order to get the sign extend.
1741 value >>= 32;
1742 break;
1743 case Instruction::CONST_WIDE:
1744 *wide = true;
1745 value = vB_wide;
1746 break;
1747 case Instruction::CONST_WIDE_HIGH16:
1748 *wide = true;
1749 value <<= 48; // In order to get the sign extend.
1750 break;
1751 default:
1752 sets_const = false;
1753 break;
1754 }
1755
1756 if (sets_const) {
1757 *ptr_value = value;
1758 }
1759
1760 return sets_const;
1761}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001762
1763void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1764 // Reset flags for all MIRs in bb.
1765 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1766 mir->optimization_flags &= (~reset_flags);
1767 }
1768}
1769
1770void BasicBlock::Hide(CompilationUnit* c_unit) {
1771 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1772 block_type = kDalvikByteCode;
1773
1774 // Mark it as hidden.
1775 hidden = true;
1776
1777 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1778 // are updated to know that they no longer have a parent.
1779 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1780 mir->bb = NullBasicBlockId;
1781 }
1782 first_mir_insn = nullptr;
1783 last_mir_insn = nullptr;
1784
1785 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1786
1787 MIRGraph* mir_graph = c_unit->mir_graph.get();
1788 while (true) {
1789 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1790 if (pred_bb == nullptr) {
1791 break;
1792 }
1793
1794 // Sadly we have to go through the children by hand here.
1795 pred_bb->ReplaceChild(id, NullBasicBlockId);
1796 }
1797
1798 // Iterate through children of bb we are hiding.
1799 ChildBlockIterator successorChildIter(this, mir_graph);
1800
1801 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1802 // Replace child with null child.
1803 childPtr->predecessors->Delete(id);
1804 }
1805}
1806
1807bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1808 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1809 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1810 // then it is not live out of this BB.
1811 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1812
1813 int last_ssa_reg = -1;
1814
1815 // Walk through the MIRs backwards.
1816 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1817 // Get ssa rep.
1818 SSARepresentation *ssa_rep = mir->ssa_rep;
1819
1820 // Go through the defines for this MIR.
1821 for (int i = 0; i < ssa_rep->num_defs; i++) {
1822 DCHECK(ssa_rep->defs != nullptr);
1823
1824 // Get the ssa reg.
1825 int def_ssa_reg = ssa_rep->defs[i];
1826
1827 // Get dalvik reg.
1828 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1829
1830 // Compare dalvik regs.
1831 if (dalvik_reg == def_dalvik_reg) {
1832 // We found a def of the register that we are being asked about.
1833 // Remember it.
1834 last_ssa_reg = def_ssa_reg;
1835 }
1836 }
1837 }
1838
1839 if (last_ssa_reg == -1) {
1840 // If we get to this point we couldn't find a define of register user asked about.
1841 // Let's assume the user knows what he's doing so we can be safe and say that if we
1842 // couldn't find a def, it is live out.
1843 return true;
1844 }
1845
1846 // If it is not -1, we found a match, is it ssa_reg?
1847 return (ssa_reg == last_ssa_reg);
1848}
1849
1850bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1851 // We need to check taken, fall_through, and successor_blocks to replace.
1852 bool found = false;
1853 if (taken == old_bb) {
1854 taken = new_bb;
1855 found = true;
1856 }
1857
1858 if (fall_through == old_bb) {
1859 fall_through = new_bb;
1860 found = true;
1861 }
1862
1863 if (successor_block_list_type != kNotUsed) {
1864 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1865 while (true) {
1866 SuccessorBlockInfo* successor_block_info = iterator.Next();
1867 if (successor_block_info == nullptr) {
1868 break;
1869 }
1870 if (successor_block_info->block == old_bb) {
1871 successor_block_info->block = new_bb;
1872 found = true;
1873 }
1874 }
1875 }
1876
1877 return found;
1878}
1879
1880void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1881 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1882 bool found = false;
1883
1884 while (true) {
1885 BasicBlockId pred_bb_id = iterator.Next();
1886
1887 if (pred_bb_id == NullBasicBlockId) {
1888 break;
1889 }
1890
1891 if (pred_bb_id == old_parent) {
1892 size_t idx = iterator.GetIndex() - 1;
1893 predecessors->Put(idx, new_parent);
1894 found = true;
1895 break;
1896 }
1897 }
1898
1899 // If not found, add it.
1900 if (found == false) {
1901 predecessors->Insert(new_parent);
1902 }
1903}
1904
1905// Create a new basic block with block_id as num_blocks_ that is
1906// post-incremented.
1907BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
1908 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
1909 block_list_.Insert(res);
1910 return res;
1911}
1912
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001913} // namespace art