blob: 3ef1dbfac362d7ad947aa3fee7d0c235f4e960fc [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000017#include "mir_graph.h"
18
19#include <inttypes.h>
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070020#include <queue>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000021
Ian Rogers6282dc12013-04-18 15:54:02 -070022#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080023#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070025#include "dex_instruction-inl.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000026#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000028#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070029#include "pass_driver_me_post_opt.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000030
buzbee311ca162013-02-28 15:56:43 -080031namespace art {
32
33#define MAX_PATTERN_LEN 5
34
buzbee1fd33462013-03-25 13:40:45 -070035const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
36 "Phi",
37 "Copy",
38 "FusedCmplFloat",
39 "FusedCmpgFloat",
40 "FusedCmplDouble",
41 "FusedCmpgDouble",
42 "FusedCmpLong",
43 "Nop",
44 "OpNullCheck",
45 "OpRangeCheck",
46 "OpDivZeroCheck",
47 "Check1",
48 "Check2",
49 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040050 "ConstVector",
51 "MoveVector",
52 "PackedMultiply",
53 "PackedAddition",
54 "PackedSubtract",
55 "PackedShiftLeft",
56 "PackedSignedShiftRight",
57 "PackedUnsignedShiftRight",
58 "PackedAnd",
59 "PackedOr",
60 "PackedXor",
61 "PackedAddReduce",
62 "PackedReduce",
63 "PackedSet",
buzbee1fd33462013-03-25 13:40:45 -070064};
65
buzbee862a7602013-04-05 10:58:54 -070066MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070067 : reg_location_(NULL),
68 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080069 ssa_base_vregs_(NULL),
70 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080071 vreg_to_ssa_map_(NULL),
72 ssa_last_defs_(NULL),
73 is_constant_v_(NULL),
74 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070075 use_counts_(arena, 256, kGrowableArrayMisc),
76 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080077 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070078 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070079 dfs_order_(NULL),
80 dfs_post_order_(NULL),
81 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070082 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080083 i_dom_list_(NULL),
84 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000085 temp_scoped_alloc_(),
86 temp_insn_data_(nullptr),
87 temp_bit_vector_size_(0u),
88 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070089 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080090 try_block_addr_(NULL),
91 entry_block_(NULL),
92 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080093 num_blocks_(0),
94 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070095 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080096 current_method_(kInvalidEntry),
97 current_offset_(kInvalidEntry),
98 def_count_(0),
99 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700100 num_ssa_regs_(0),
101 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700102 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
103 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700104 arena_(arena),
105 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800106 forward_branches_(0),
107 compiler_temps_(arena, 6, kGrowableArrayMisc),
108 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800109 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000110 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000111 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000112 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000113 sfield_lowering_infos_(arena, 0u),
114 method_lowering_infos_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700115 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800116 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
117 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800118}
119
Ian Rogers6282dc12013-04-18 15:54:02 -0700120MIRGraph::~MIRGraph() {
121 STLDeleteElements(&m_units_);
122}
123
buzbee311ca162013-02-28 15:56:43 -0800124/*
125 * Parse an instruction, return the length of the instruction
126 */
Ian Rogers29a26482014-05-02 15:27:29 -0700127int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
128 const Instruction* inst = Instruction::At(code_ptr);
129 decoded_instruction->opcode = inst->Opcode();
130 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
131 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
132 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
133 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
134 if (inst->HasVarArgs()) {
135 inst->GetVarArgs(decoded_instruction->arg);
136 }
137 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800138}
139
140
141/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700142BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700143 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700144 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800145 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700146 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800147 while (insn) {
148 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700149 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800150 insn = insn->next;
151 }
152 if (insn == NULL) {
153 LOG(FATAL) << "Break split failed";
154 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700155 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700156 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800157
158 bottom_block->start_offset = code_offset;
159 bottom_block->first_mir_insn = insn;
160 bottom_block->last_mir_insn = orig_block->last_mir_insn;
161
162 /* If this block was terminated by a return, the flag needs to go with the bottom block */
163 bottom_block->terminated_by_return = orig_block->terminated_by_return;
164 orig_block->terminated_by_return = false;
165
buzbee311ca162013-02-28 15:56:43 -0800166 /* Handle the taken path */
167 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700168 if (bottom_block->taken != NullBasicBlockId) {
169 orig_block->taken = NullBasicBlockId;
170 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
171 bb_taken->predecessors->Delete(orig_block->id);
172 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800173 }
174
175 /* Handle the fallthrough path */
176 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700177 orig_block->fall_through = bottom_block->id;
178 bottom_block->predecessors->Insert(orig_block->id);
179 if (bottom_block->fall_through != NullBasicBlockId) {
180 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
181 bb_fall_through->predecessors->Delete(orig_block->id);
182 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800183 }
184
185 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700186 if (orig_block->successor_block_list_type != kNotUsed) {
187 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
188 bottom_block->successor_blocks = orig_block->successor_blocks;
189 orig_block->successor_block_list_type = kNotUsed;
190 orig_block->successor_blocks = NULL;
191 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800192 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700193 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800194 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700195 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700196 bb->predecessors->Delete(orig_block->id);
197 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800198 }
199 }
200
buzbee0d829482013-10-11 15:24:55 -0700201 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700202 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800203
buzbee311ca162013-02-28 15:56:43 -0800204 /*
205 * Update the immediate predecessor block pointer so that outgoing edges
206 * can be applied to the proper block.
207 */
208 if (immed_pred_block_p) {
209 DCHECK_EQ(*immed_pred_block_p, orig_block);
210 *immed_pred_block_p = bottom_block;
211 }
buzbeeb48819d2013-09-14 16:15:25 -0700212
213 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000214 DCHECK(insn != nullptr);
215 DCHECK(insn != orig_block->first_mir_insn);
216 DCHECK(insn == bottom_block->first_mir_insn);
217 DCHECK_EQ(insn->offset, bottom_block->start_offset);
218 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
219 !IsPseudoMirOp(insn->dalvikInsn.opcode));
220 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
221 MIR* p = insn;
222 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
223 while (p != bottom_block->last_mir_insn) {
224 p = p->next;
225 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700226 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700227 int opcode = p->dalvikInsn.opcode;
228 /*
229 * Some messiness here to ensure that we only enter real opcodes and only the
230 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000231 * CHECK and work portions. Since the 2nd half of a split operation is always
232 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700233 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000234 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
235 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700236 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
237 }
buzbeeb48819d2013-09-14 16:15:25 -0700238 }
239
buzbee311ca162013-02-28 15:56:43 -0800240 return bottom_block;
241}
242
243/*
244 * Given a code offset, find out the block that starts with it. If the offset
245 * is in the middle of an existing block, split it into two. If immed_pred_block_p
246 * is not non-null and is the block being split, update *immed_pred_block_p to
247 * point to the bottom block so that outgoing edges can be set up properly
248 * (by the caller)
249 * Utilizes a map for fast lookup of the typical cases.
250 */
buzbee0d829482013-10-11 15:24:55 -0700251BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700252 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700253 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800254 return NULL;
255 }
buzbeeb48819d2013-09-14 16:15:25 -0700256
257 int block_id = dex_pc_to_block_map_.Get(code_offset);
258 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
259
260 if ((bb != NULL) && (bb->start_offset == code_offset)) {
261 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700262 return bb;
263 }
buzbee311ca162013-02-28 15:56:43 -0800264
buzbeeb48819d2013-09-14 16:15:25 -0700265 // No direct hit.
266 if (!create) {
267 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800268 }
269
buzbeeb48819d2013-09-14 16:15:25 -0700270 if (bb != NULL) {
271 // The target exists somewhere in an existing block.
272 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
273 }
274
275 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700276 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
277 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800278 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700279 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800280 return bb;
281}
282
buzbeeb48819d2013-09-14 16:15:25 -0700283
buzbee311ca162013-02-28 15:56:43 -0800284/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700285void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800286 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700287 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800288
289 if (tries_size == 0) {
290 return;
291 }
292
293 for (int i = 0; i < tries_size; i++) {
294 const DexFile::TryItem* pTry =
295 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700296 DexOffset start_offset = pTry->start_addr_;
297 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800298 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700299 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800300 }
301 }
302
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700303 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800304 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
305 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
306 for (uint32_t idx = 0; idx < handlers_size; idx++) {
307 CatchHandlerIterator iterator(handlers_ptr);
308 for (; iterator.HasNext(); iterator.Next()) {
309 uint32_t address = iterator.GetHandlerAddress();
310 FindBlock(address, false /* split */, true /*create*/,
311 /* immed_pred_block_p */ NULL);
312 }
313 handlers_ptr = iterator.EndDataPointer();
314 }
315}
316
317/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700318BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
319 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700320 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700321 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800322 switch (insn->dalvikInsn.opcode) {
323 case Instruction::GOTO:
324 case Instruction::GOTO_16:
325 case Instruction::GOTO_32:
326 target += insn->dalvikInsn.vA;
327 break;
328 case Instruction::IF_EQ:
329 case Instruction::IF_NE:
330 case Instruction::IF_LT:
331 case Instruction::IF_GE:
332 case Instruction::IF_GT:
333 case Instruction::IF_LE:
334 cur_block->conditional_branch = true;
335 target += insn->dalvikInsn.vC;
336 break;
337 case Instruction::IF_EQZ:
338 case Instruction::IF_NEZ:
339 case Instruction::IF_LTZ:
340 case Instruction::IF_GEZ:
341 case Instruction::IF_GTZ:
342 case Instruction::IF_LEZ:
343 cur_block->conditional_branch = true;
344 target += insn->dalvikInsn.vB;
345 break;
346 default:
347 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
348 }
buzbeeb48819d2013-09-14 16:15:25 -0700349 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700350 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800351 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700352 cur_block->taken = taken_block->id;
353 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800354
355 /* Always terminate the current block for conditional branches */
356 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700357 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800358 /*
359 * If the method is processed
360 * in sequential order from the
361 * beginning, we don't need to
362 * specify split for continue
363 * blocks. However, this
364 * routine can be called by
365 * compileLoop, which starts
366 * parsing the method from an
367 * arbitrary address in the
368 * method body.
369 */
370 true,
371 /* create */
372 true,
373 /* immed_pred_block_p */
374 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700375 cur_block->fall_through = fallthrough_block->id;
376 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800377 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700378 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800379 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800380 }
381 return cur_block;
382}
383
384/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800385BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
386 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800387 const uint16_t* switch_data =
388 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
389 int size;
390 const int* keyTable;
391 const int* target_table;
392 int i;
393 int first_key;
394
395 /*
396 * Packed switch data format:
397 * ushort ident = 0x0100 magic value
398 * ushort size number of entries in the table
399 * int first_key first (and lowest) switch case value
400 * int targets[size] branch targets, relative to switch opcode
401 *
402 * Total size is (4+size*2) 16-bit code units.
403 */
404 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
405 DCHECK_EQ(static_cast<int>(switch_data[0]),
406 static_cast<int>(Instruction::kPackedSwitchSignature));
407 size = switch_data[1];
408 first_key = switch_data[2] | (switch_data[3] << 16);
409 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700410 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800411 /*
412 * Sparse switch data format:
413 * ushort ident = 0x0200 magic value
414 * ushort size number of entries in the table; > 0
415 * int keys[size] keys, sorted low-to-high; 32-bit aligned
416 * int targets[size] branch targets, relative to switch opcode
417 *
418 * Total size is (2+size*4) 16-bit code units.
419 */
420 } else {
421 DCHECK_EQ(static_cast<int>(switch_data[0]),
422 static_cast<int>(Instruction::kSparseSwitchSignature));
423 size = switch_data[1];
424 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
425 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700426 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800427 }
428
buzbee0d829482013-10-11 15:24:55 -0700429 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800430 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700431 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800432 }
buzbee0d829482013-10-11 15:24:55 -0700433 cur_block->successor_block_list_type =
434 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
435 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700436 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800437
438 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700439 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800440 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700441 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700442 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000443 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700444 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800445 successor_block_info->key =
446 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
447 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700448 cur_block->successor_blocks->Insert(successor_block_info);
449 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800450 }
451
452 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700453 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
454 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700455 cur_block->fall_through = fallthrough_block->id;
456 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800457 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800458}
459
460/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700461BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
462 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700463 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700464 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800465 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
466 bool build_all_edges =
467 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800468
469 /* In try block */
470 if (in_try_block) {
471 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
472
buzbee0d829482013-10-11 15:24:55 -0700473 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800474 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
475 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700476 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800477 }
478
buzbee0d829482013-10-11 15:24:55 -0700479 cur_block->successor_block_list_type = kCatch;
480 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700481 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800482
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700483 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700484 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800485 false /* creat */, NULL /* immed_pred_block_p */);
486 catch_block->catch_entry = true;
487 if (kIsDebugBuild) {
488 catches_.insert(catch_block->start_offset);
489 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700490 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000491 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700492 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800493 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700494 cur_block->successor_blocks->Insert(successor_block_info);
495 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800496 }
buzbee17189ac2013-11-08 11:07:02 -0800497 } else if (build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700498 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700499 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700500 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800501 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700502 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800503 }
504
buzbee17189ac2013-11-08 11:07:02 -0800505 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800506 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700507 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700508 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800509 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
510 /* immed_pred_block_p */ NULL);
511 }
512 if (!in_try_block) {
513 // Don't split a THROW that can't rethrow - we're done.
514 return cur_block;
515 }
516 }
517
buzbee17189ac2013-11-08 11:07:02 -0800518 if (!build_all_edges) {
519 /*
520 * Even though there is an exception edge here, control cannot return to this
521 * method. Thus, for the purposes of dataflow analysis and optimization, we can
522 * ignore the edge. Doing this reduces compile time, and increases the scope
523 * of the basic-block level optimization pass.
524 */
525 return cur_block;
526 }
527
buzbee311ca162013-02-28 15:56:43 -0800528 /*
529 * Split the potentially-throwing instruction into two parts.
530 * The first half will be a pseudo-op that captures the exception
531 * edges and terminates the basic block. It always falls through.
532 * Then, create a new basic block that begins with the throwing instruction
533 * (minus exceptions). Note: this new basic block must NOT be entered into
534 * the block_map. If the potentially-throwing instruction is the target of a
535 * future branch, we need to find the check psuedo half. The new
536 * basic block containing the work portion of the instruction should
537 * only be entered via fallthrough from the block containing the
538 * pseudo exception edge MIR. Note also that this new block is
539 * not automatically terminated after the work portion, and may
540 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700541 *
542 * Note also that the dex_pc_to_block_map_ entry for the potentially
543 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800544 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700545 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700546 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800547 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700548 cur_block->fall_through = new_block->id;
549 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700550 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800551 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700552 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700553 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800554 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700555 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800556 return new_block;
557}
558
559/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
560void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700561 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700562 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800563 current_code_item_ = code_item;
564 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
565 current_method_ = m_units_.size();
566 current_offset_ = 0;
567 // TODO: will need to snapshot stack image and use that as the mir context identification.
568 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000569 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
570 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800571 const uint16_t* code_ptr = current_code_item_->insns_;
572 const uint16_t* code_end =
573 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
574
575 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700576 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700577 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700578 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 -0700579
buzbee311ca162013-02-28 15:56:43 -0800580 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700581 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
582 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800583
584 // If this is the first method, set up default entry and exit blocks.
585 if (current_method_ == 0) {
586 DCHECK(entry_block_ == NULL);
587 DCHECK(exit_block_ == NULL);
Brian Carlstrom42748892013-07-18 18:04:08 -0700588 DCHECK_EQ(num_blocks_, 0);
buzbee0d829482013-10-11 15:24:55 -0700589 // Use id 0 to represent a null block.
590 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
591 DCHECK_EQ(null_block->id, NullBasicBlockId);
592 null_block->hidden = true;
593 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700594 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700595 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700596 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700597 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800598 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
599 cu_->dex_file = &dex_file;
600 cu_->class_def_idx = class_def_idx;
601 cu_->method_idx = method_idx;
602 cu_->access_flags = access_flags;
603 cu_->invoke_type = invoke_type;
604 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
605 cu_->num_ins = current_code_item_->ins_size_;
606 cu_->num_regs = current_code_item_->registers_size_ - cu_->num_ins;
607 cu_->num_outs = current_code_item_->outs_size_;
608 cu_->num_dalvik_registers = current_code_item_->registers_size_;
609 cu_->insns = current_code_item_->insns_;
610 cu_->code_item = current_code_item_;
611 } else {
612 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
613 /*
614 * Will need to manage storage for ins & outs, push prevous state and update
615 * insert point.
616 */
617 }
618
619 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700620 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700621 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800622 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700623 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700624 // TODO: for inlining support, insert at the insert point rather than entry block.
625 entry_block_->fall_through = cur_block->id;
626 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800627
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000628 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800629 ProcessTryCatchBlocks();
630
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000631 uint64_t merged_df_flags = 0u;
632
buzbee311ca162013-02-28 15:56:43 -0800633 /* Parse all instructions and put them into containing basic blocks */
634 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700635 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800636 insn->offset = current_offset_;
637 insn->m_unit_index = current_method_;
638 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800639 Instruction::Code opcode = insn->dalvikInsn.opcode;
640 if (opcode_count_ != NULL) {
641 opcode_count_[static_cast<int>(opcode)]++;
642 }
643
buzbee311ca162013-02-28 15:56:43 -0800644 int flags = Instruction::FlagsOf(insn->dalvikInsn.opcode);
buzbeeb1f1d642014-02-27 12:55:32 -0800645 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800646
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700647 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000648 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800649
650 if (df_flags & DF_HAS_DEFS) {
651 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
652 }
653
buzbee1da1e2f2013-11-15 13:37:01 -0800654 if (df_flags & DF_LVN) {
655 cur_block->use_lvn = true; // Run local value numbering on this basic block.
656 }
657
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700658 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700659 if (opcode == Instruction::NOP) {
660 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
661 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
662 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
663 uint16_t following_raw_instruction = code_ptr[1];
664 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
665 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
666 (following_raw_instruction == Instruction::kArrayDataSignature)) {
667 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
668 }
669 }
670 if (width == 1) {
671 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700672 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700673 } else {
buzbee0d829482013-10-11 15:24:55 -0700674 DCHECK(cur_block->fall_through == NullBasicBlockId);
675 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700676 // Unreachable instruction, mark for no continuation.
677 flags &= ~Instruction::kContinue;
678 }
679 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700680 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700681 }
682
buzbeeb48819d2013-09-14 16:15:25 -0700683 // Associate the starting dex_pc for this opcode with its containing basic block.
684 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
685
buzbee27247762013-07-28 12:03:58 -0700686 code_ptr += width;
687
buzbee311ca162013-02-28 15:56:43 -0800688 if (flags & Instruction::kBranch) {
689 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
690 width, flags, code_ptr, code_end);
691 } else if (flags & Instruction::kReturn) {
692 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700693 cur_block->fall_through = exit_block_->id;
694 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800695 /*
696 * Terminate the current block if there are instructions
697 * afterwards.
698 */
699 if (code_ptr < code_end) {
700 /*
701 * Create a fallthrough block for real instructions
702 * (incl. NOP).
703 */
buzbee27247762013-07-28 12:03:58 -0700704 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
705 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800706 }
707 } else if (flags & Instruction::kThrow) {
708 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
709 code_ptr, code_end);
710 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800711 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800712 }
buzbeeb1f1d642014-02-27 12:55:32 -0800713 if (verify_flags & Instruction::kVerifyVarArgRange) {
714 /*
715 * The Quick backend's runtime model includes a gap between a method's
716 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
717 * which spans the gap is somewhat complicated, and should not happen
718 * in normal usage of dx. Punt to the interpreter.
719 */
720 int first_reg_in_range = insn->dalvikInsn.vC;
721 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
722 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
723 punt_to_interpreter_ = true;
724 }
725 }
buzbee311ca162013-02-28 15:56:43 -0800726 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700727 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800728 false, /* immed_pred_block_p */ NULL);
729 if (next_block) {
730 /*
731 * The next instruction could be the target of a previously parsed
732 * forward branch so a block is already created. If the current
733 * instruction is not an unconditional branch, connect them through
734 * the fall-through link.
735 */
buzbee0d829482013-10-11 15:24:55 -0700736 DCHECK(cur_block->fall_through == NullBasicBlockId ||
737 GetBasicBlock(cur_block->fall_through) == next_block ||
738 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800739
buzbee0d829482013-10-11 15:24:55 -0700740 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
741 cur_block->fall_through = next_block->id;
742 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800743 }
744 cur_block = next_block;
745 }
746 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000747 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000748
buzbee311ca162013-02-28 15:56:43 -0800749 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
750 DumpCFG("/sdcard/1_post_parse_cfg/", true);
751 }
752
753 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700754 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800755 }
756}
757
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700758void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800759 DCHECK(opcode_count_ != NULL);
760 LOG(INFO) << "Opcode Count";
761 for (int i = 0; i < kNumPackedOpcodes; i++) {
762 if (opcode_count_[i] != 0) {
763 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
764 << " " << opcode_count_[i];
765 }
766 }
767}
768
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700769uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
770 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
771 return oat_data_flow_attributes_[opcode];
772}
773
774uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
775 DCHECK(mir != nullptr);
776 Instruction::Code opcode = mir->dalvikInsn.opcode;
777 return GetDataFlowAttributes(opcode);
778}
779
buzbee311ca162013-02-28 15:56:43 -0800780// TODO: use a configurable base prefix, and adjust callers to supply pass name.
781/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800782void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800783 FILE* file;
784 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
785 ReplaceSpecialChars(fname);
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800786 fname = StringPrintf("%s%s%x%s.dot", dir_prefix, fname.c_str(),
787 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
788 suffix == nullptr ? "" : suffix);
buzbee311ca162013-02-28 15:56:43 -0800789 file = fopen(fname.c_str(), "w");
790 if (file == NULL) {
791 return;
792 }
793 fprintf(file, "digraph G {\n");
794
795 fprintf(file, " rankdir=TB\n");
796
797 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
798 int idx;
799
800 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700801 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700802 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700803 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800804 if (bb->block_type == kDead) continue;
805 if (bb->block_type == kEntryBlock) {
806 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
807 } else if (bb->block_type == kExitBlock) {
808 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
809 } else if (bb->block_type == kDalvikByteCode) {
810 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
811 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700812 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800813 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
814 bb->first_mir_insn ? " | " : " ");
815 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
816 int opcode = mir->dalvikInsn.opcode;
Mark Mendelld65c51a2014-04-29 16:55:20 -0400817 if (opcode > kMirOpSelect && opcode < kMirOpLast) {
818 if (opcode == kMirOpConstVector) {
819 fprintf(file, " {%04x %s %d %d %d %d %d %d\\l}%s\\\n", mir->offset,
820 extended_mir_op_names_[kMirOpConstVector - kMirOpFirst],
821 mir->dalvikInsn.vA,
822 mir->dalvikInsn.vB,
823 mir->dalvikInsn.arg[0],
824 mir->dalvikInsn.arg[1],
825 mir->dalvikInsn.arg[2],
826 mir->dalvikInsn.arg[3],
827 mir->next ? " | " : " ");
828 } else {
829 fprintf(file, " {%04x %s %d %d %d\\l}%s\\\n", mir->offset,
830 extended_mir_op_names_[opcode - kMirOpFirst],
831 mir->dalvikInsn.vA,
832 mir->dalvikInsn.vB,
833 mir->dalvikInsn.vC,
834 mir->next ? " | " : " ");
835 }
836 } else {
837 fprintf(file, " {%04x %s %s %s\\l}%s\\\n", mir->offset,
838 mir->ssa_rep ? GetDalvikDisassembly(mir) :
buzbee35ba7f32014-05-31 08:59:01 -0700839 !IsPseudoMirOp(opcode) ? Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400840 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
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001075 // Remove the BB information and also find the after_list.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001076 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
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001082 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001083 if (before_list == nullptr) {
1084 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001085 } else {
1086 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001087 }
1088
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001089 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001090 if (after_list == nullptr) {
1091 last_mir_insn = before_list;
1092 }
1093
1094 return true;
buzbee1fd33462013-03-25 13:40:45 -07001095}
1096
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001097MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001098 MIR* next_mir = nullptr;
1099
1100 if (current != nullptr) {
1101 next_mir = current->next;
1102 }
1103
1104 if (next_mir == nullptr) {
1105 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001106 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1107 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001108 }
1109 }
1110
1111 return next_mir;
1112}
1113
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001114char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001115 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001116 std::string str;
1117 int flags = 0;
1118 int opcode = insn.opcode;
1119 char* ret;
1120 bool nop = false;
1121 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001122 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001123 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1124 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1125
1126 // Handle special cases.
1127 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1128 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1129 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001130 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001131 insn = mir->meta.throw_insn->dalvikInsn;
1132 ssa_rep = mir->meta.throw_insn->ssa_rep;
1133 defs = ssa_rep->num_defs;
1134 uses = ssa_rep->num_uses;
1135 opcode = insn.opcode;
1136 } else if (opcode == kMirOpNop) {
1137 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001138 // Recover original opcode.
1139 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1140 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001141 nop = true;
1142 }
1143
buzbee35ba7f32014-05-31 08:59:01 -07001144 if (IsPseudoMirOp(opcode)) {
buzbee1fd33462013-03-25 13:40:45 -07001145 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1146 } else {
1147 dalvik_format = Instruction::FormatOf(insn.opcode);
1148 flags = Instruction::FlagsOf(insn.opcode);
1149 str.append(Instruction::Name(insn.opcode));
1150 }
1151
1152 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001153 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001154 str.append(StringPrintf(" %s = (%s",
1155 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1156 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001157 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001158 int i;
1159 for (i = 1; i < uses; i++) {
1160 str.append(StringPrintf(", %s:%d",
1161 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1162 incoming[i]));
1163 }
1164 str.append(")");
1165 } else if ((flags & Instruction::kBranch) != 0) {
1166 // For branches, decode the instructions to print out the branch targets.
1167 int offset = 0;
1168 switch (dalvik_format) {
1169 case Instruction::k21t:
1170 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1171 offset = insn.vB;
1172 break;
1173 case Instruction::k22t:
1174 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1175 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1176 offset = insn.vC;
1177 break;
1178 case Instruction::k10t:
1179 case Instruction::k20t:
1180 case Instruction::k30t:
1181 offset = insn.vA;
1182 break;
1183 default:
1184 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1185 }
1186 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1187 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1188 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001189 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001190 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1191 (dalvik_format == Instruction::k3rc));
1192 if (defs != 0) {
1193 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1194 if (uses != 0) {
1195 str.append(", ");
1196 }
1197 }
1198 for (int i = 0; i < uses; i++) {
1199 str.append(
1200 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1201 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1202 // For the listing, skip the high sreg.
1203 i++;
1204 }
1205 if (i != (uses -1)) {
1206 str.append(",");
1207 }
1208 }
1209 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001210 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001211 case Instruction::k21s:
1212 case Instruction::k31i:
1213 case Instruction::k21h:
1214 str.append(StringPrintf(", #%d", insn.vB));
1215 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001216 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001217 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001218 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001219 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001220 case Instruction::k31c:
1221 str.append(StringPrintf(", index #%d", insn.vB));
1222 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001223 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001224 str.append(StringPrintf(", index #%d", insn.vC));
1225 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001226 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001227 case Instruction::k22b:
1228 str.append(StringPrintf(", #%d", insn.vC));
1229 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001230 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001231 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001232 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001233 }
buzbee1fd33462013-03-25 13:40:45 -07001234 }
1235 if (nop) {
1236 str.append("]--optimized away");
1237 }
1238 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001239 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001240 strncpy(ret, str.c_str(), length);
1241 return ret;
1242}
1243
1244/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001245void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001246 static const struct { const char before; const char after; } match[] = {
1247 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1248 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1249 };
buzbee1fd33462013-03-25 13:40:45 -07001250 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1251 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1252 }
1253}
1254
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001255std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001256 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1257 // the arena. We should be smarter and just place straight into the arena, or compute the
1258 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001259 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1260}
1261
1262// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001263std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001264 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001265 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001266 return GetSSAName(ssa_reg);
1267 }
1268 if (IsConst(reg_location_[ssa_reg])) {
1269 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001270 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001271 ConstantValueWide(reg_location_[ssa_reg]));
1272 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001273 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001274 ConstantValue(reg_location_[ssa_reg]));
1275 }
1276 } else {
1277 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1278 }
1279}
1280
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001281void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001282 switch (bb->block_type) {
1283 case kEntryBlock:
1284 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1285 break;
1286 case kExitBlock:
1287 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1288 break;
1289 case kDalvikByteCode:
1290 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1291 break;
1292 case kExceptionHandling:
1293 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1294 bb->id);
1295 break;
1296 default:
1297 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1298 break;
1299 }
1300}
1301
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001302const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001303 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001304 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1305 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1306}
1307
1308/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001309void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001310 BasicBlock* bb;
1311 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001312 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001313 "Entry Block",
1314 "Code Block",
1315 "Exit Block",
1316 "Exception Handling",
1317 "Catch Block"
1318 };
1319
1320 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1321 LOG(INFO) << cu_->insns << " insns";
1322 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001323 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001324
1325 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001326 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001327 if (bb == NULL) break;
1328 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1329 bb->id,
1330 block_type_names[bb->block_type],
1331 bb->start_offset,
1332 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1333 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001334 if (bb->taken != NullBasicBlockId) {
1335 LOG(INFO) << " Taken branch: block " << bb->taken
1336 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001337 }
buzbee0d829482013-10-11 15:24:55 -07001338 if (bb->fall_through != NullBasicBlockId) {
1339 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1340 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001341 }
1342 }
1343}
1344
1345/*
1346 * Build an array of location records for the incoming arguments.
1347 * Note: one location record per word of arguments, with dummy
1348 * high-word loc for wide arguments. Also pull up any following
1349 * MOVE_RESULT and incorporate it into the invoke.
1350 */
1351CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001352 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001353 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001354 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001355 MIR* move_result_mir = FindMoveResult(bb, mir);
1356 if (move_result_mir == NULL) {
1357 info->result.location = kLocInvalid;
1358 } else {
1359 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001360 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1361 }
1362 info->num_arg_words = mir->ssa_rep->num_uses;
1363 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001364 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001365 for (int i = 0; i < info->num_arg_words; i++) {
1366 info->args[i] = GetRawSrc(mir, i);
1367 }
1368 info->opt_flags = mir->optimization_flags;
1369 info->type = type;
1370 info->is_range = is_range;
1371 info->index = mir->dalvikInsn.vB;
1372 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001373 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001374 return info;
1375}
1376
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001377// Allocate a new MIR.
1378MIR* MIRGraph::NewMIR() {
1379 MIR* mir = new (arena_) MIR();
1380 return mir;
1381}
1382
buzbee862a7602013-04-05 10:58:54 -07001383// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001384BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001385 BasicBlock* bb = new (arena_) BasicBlock();
1386
buzbee862a7602013-04-05 10:58:54 -07001387 bb->block_type = block_type;
1388 bb->id = block_id;
1389 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001390 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001391 (block_type == kExitBlock) ? 2048 : 2,
1392 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001393 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001394 block_id_map_.Put(block_id, block_id);
1395 return bb;
1396}
buzbee1fd33462013-03-25 13:40:45 -07001397
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001398void MIRGraph::InitializeConstantPropagation() {
1399 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001400 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001401}
1402
1403void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001404 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001405 int num_ssa_regs = GetNumSSARegs();
1406 use_counts_.Resize(num_ssa_regs + 32);
1407 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001408 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001409 for (int i = 0; i < num_ssa_regs; i++) {
1410 use_counts_.Insert(0);
1411 raw_use_counts_.Insert(0);
1412 }
1413}
1414
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001415void MIRGraph::SSATransformationStart() {
1416 DCHECK(temp_scoped_alloc_.get() == nullptr);
1417 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1418 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1419 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1420 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1421
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001422 // Update the maximum number of reachable blocks.
1423 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001424}
1425
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001426void MIRGraph::SSATransformationEnd() {
1427 // Verify the dataflow information after the pass.
1428 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1429 VerifyDataflow();
1430 }
1431
1432 temp_bit_vector_size_ = 0u;
1433 temp_bit_vector_ = nullptr;
1434 DCHECK(temp_scoped_alloc_.get() != nullptr);
1435 temp_scoped_alloc_.reset();
1436}
1437
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001438void MIRGraph::ComputeTopologicalSortOrder() {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001439 std::queue<BasicBlock*> q;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001440 std::map<int, int> visited_cnt_values;
1441
1442 // Clear the nodes.
1443 ClearAllVisitedFlags();
1444
1445 // Create the topological order if need be.
1446 if (topological_order_ != nullptr) {
1447 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, 0);
1448 }
1449 topological_order_->Reset();
1450
1451 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1452 // also fill initial queue.
1453 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1454
1455 while (true) {
1456 BasicBlock* bb = iterator.Next();
1457
1458 if (bb == nullptr) {
1459 break;
1460 }
1461
1462 if (bb->hidden == true) {
1463 continue;
1464 }
1465
1466 visited_cnt_values[bb->id] = bb->predecessors->Size();
1467
1468 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1469 // To process loops we should not wait for dominators.
1470 while (true) {
1471 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1472
1473 if (pred_bb == nullptr) {
1474 break;
1475 }
1476
1477 if (pred_bb->dominators == nullptr || pred_bb->hidden == true) {
1478 continue;
1479 }
1480
1481 // Skip the backward branch.
1482 if (pred_bb->dominators->IsBitSet(bb->id) != 0) {
1483 visited_cnt_values[bb->id]--;
1484 }
1485 }
1486
1487 // Add entry block to queue.
1488 if (visited_cnt_values[bb->id] == 0) {
1489 q.push(bb);
1490 }
1491 }
1492
1493 while (q.size() > 0) {
1494 // Get top.
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001495 BasicBlock* bb = q.front();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001496 q.pop();
1497
1498 DCHECK_EQ(bb->hidden, false);
1499
1500 if (bb->IsExceptionBlock() == true) {
1501 continue;
1502 }
1503
1504 // We've visited all the predecessors. So, we can visit bb.
1505 if (bb->visited == false) {
1506 bb->visited = true;
1507
1508 // Now add the basic block.
1509 topological_order_->Insert(bb->id);
1510
1511 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1512 ChildBlockIterator succIter(bb, this);
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001513 BasicBlock* successor = succIter.Next();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001514 while (successor != nullptr) {
1515 // one more predecessor was visited.
1516 visited_cnt_values[successor->id]--;
1517
1518 if (visited_cnt_values[successor->id] <= 0 && successor->visited == false && successor->hidden == false) {
1519 q.push(successor);
1520 }
1521
1522 // Take next successor.
1523 successor = succIter.Next();
1524 }
1525 }
1526 }
1527}
1528
1529bool BasicBlock::IsExceptionBlock() const {
1530 if (block_type == kExceptionHandling) {
1531 return true;
1532 }
1533 return false;
1534}
1535
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001536ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1537 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1538 visited_taken_(false), have_successors_(false) {
1539 // Check if we actually do have successors.
1540 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1541 have_successors_ = true;
1542 successor_iter_.Reset(basic_block_->successor_blocks);
1543 }
1544}
1545
1546BasicBlock* ChildBlockIterator::Next() {
1547 // We check if we have a basic block. If we don't we cannot get next child.
1548 if (basic_block_ == nullptr) {
1549 return nullptr;
1550 }
1551
1552 // If we haven't visited fallthrough, return that.
1553 if (visited_fallthrough_ == false) {
1554 visited_fallthrough_ = true;
1555
1556 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1557 if (result != nullptr) {
1558 return result;
1559 }
1560 }
1561
1562 // If we haven't visited taken, return that.
1563 if (visited_taken_ == false) {
1564 visited_taken_ = true;
1565
1566 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1567 if (result != nullptr) {
1568 return result;
1569 }
1570 }
1571
1572 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1573 if (have_successors_ == true) {
1574 // Get information about next successor block.
1575 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1576
1577 // If we don't have anymore successors, return nullptr.
1578 if (successor_block_info != nullptr) {
1579 return mir_graph_->GetBasicBlock(successor_block_info->block);
1580 }
1581 }
1582
1583 // We do not have anything.
1584 return nullptr;
1585}
1586
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001587BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1588 MIRGraph* mir_graph = c_unit->mir_graph.get();
1589 return Copy(mir_graph);
1590}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001591
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001592BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1593 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001594
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001595 // We don't do a memcpy style copy here because it would lead to a lot of things
1596 // to clean up. Let us do it by hand instead.
1597 // Copy in taken and fallthrough.
1598 result_bb->fall_through = fall_through;
1599 result_bb->taken = taken;
1600
1601 // Copy successor links if needed.
1602 ArenaAllocator* arena = mir_graph->GetArena();
1603
1604 result_bb->successor_block_list_type = successor_block_list_type;
1605 if (result_bb->successor_block_list_type != kNotUsed) {
1606 size_t size = successor_blocks->Size();
1607 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1608 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1609 while (true) {
1610 SuccessorBlockInfo* sbi_old = iterator.Next();
1611 if (sbi_old == nullptr) {
1612 break;
1613 }
1614 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1615 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1616 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001617 }
1618 }
1619
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001620 // Copy offset, method.
1621 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001622
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001623 // Now copy instructions.
1624 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1625 // Get a copy first.
1626 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001627
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001628 // Append it.
1629 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001630 }
1631
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001632 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001633}
1634
1635MIR* MIR::Copy(MIRGraph* mir_graph) {
1636 MIR* res = mir_graph->NewMIR();
1637 *res = *this;
1638
1639 // Remove links
1640 res->next = nullptr;
1641 res->bb = NullBasicBlockId;
1642 res->ssa_rep = nullptr;
1643
1644 return res;
1645}
1646
1647MIR* MIR::Copy(CompilationUnit* c_unit) {
1648 return Copy(c_unit->mir_graph.get());
1649}
1650
1651uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1652 // Default result.
1653 int res = 0;
1654
1655 // We are basically setting the iputs to their igets counterparts.
1656 switch (opcode) {
1657 case Instruction::IPUT:
1658 case Instruction::IPUT_OBJECT:
1659 case Instruction::IPUT_BOOLEAN:
1660 case Instruction::IPUT_BYTE:
1661 case Instruction::IPUT_CHAR:
1662 case Instruction::IPUT_SHORT:
1663 case Instruction::IPUT_QUICK:
1664 case Instruction::IPUT_OBJECT_QUICK:
1665 case Instruction::APUT:
1666 case Instruction::APUT_OBJECT:
1667 case Instruction::APUT_BOOLEAN:
1668 case Instruction::APUT_BYTE:
1669 case Instruction::APUT_CHAR:
1670 case Instruction::APUT_SHORT:
1671 case Instruction::SPUT:
1672 case Instruction::SPUT_OBJECT:
1673 case Instruction::SPUT_BOOLEAN:
1674 case Instruction::SPUT_BYTE:
1675 case Instruction::SPUT_CHAR:
1676 case Instruction::SPUT_SHORT:
1677 // Skip the VR containing what to store.
1678 res = 1;
1679 break;
1680 case Instruction::IPUT_WIDE:
1681 case Instruction::IPUT_WIDE_QUICK:
1682 case Instruction::APUT_WIDE:
1683 case Instruction::SPUT_WIDE:
1684 // Skip the two VRs containing what to store.
1685 res = 2;
1686 break;
1687 default:
1688 // Do nothing in the general case.
1689 break;
1690 }
1691
1692 return res;
1693}
1694
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001695/**
1696 * @brief Given a decoded instruction, it checks whether the instruction
1697 * sets a constant and if it does, more information is provided about the
1698 * constant being set.
1699 * @param ptr_value pointer to a 64-bit holder for the constant.
1700 * @param wide Updated by function whether a wide constant is being set by bytecode.
1701 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1702 */
1703bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1704 bool sets_const = true;
1705 int64_t value = vB;
1706
1707 DCHECK(ptr_value != nullptr);
1708 DCHECK(wide != nullptr);
1709
1710 switch (opcode) {
1711 case Instruction::CONST_4:
1712 case Instruction::CONST_16:
1713 case Instruction::CONST:
1714 *wide = false;
1715 value <<= 32; // In order to get the sign extend.
1716 value >>= 32;
1717 break;
1718 case Instruction::CONST_HIGH16:
1719 *wide = false;
1720 value <<= 48; // In order to get the sign extend.
1721 value >>= 32;
1722 break;
1723 case Instruction::CONST_WIDE_16:
1724 case Instruction::CONST_WIDE_32:
1725 *wide = true;
1726 value <<= 32; // In order to get the sign extend.
1727 value >>= 32;
1728 break;
1729 case Instruction::CONST_WIDE:
1730 *wide = true;
1731 value = vB_wide;
1732 break;
1733 case Instruction::CONST_WIDE_HIGH16:
1734 *wide = true;
1735 value <<= 48; // In order to get the sign extend.
1736 break;
1737 default:
1738 sets_const = false;
1739 break;
1740 }
1741
1742 if (sets_const) {
1743 *ptr_value = value;
1744 }
1745
1746 return sets_const;
1747}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001748
1749void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1750 // Reset flags for all MIRs in bb.
1751 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1752 mir->optimization_flags &= (~reset_flags);
1753 }
1754}
1755
1756void BasicBlock::Hide(CompilationUnit* c_unit) {
1757 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1758 block_type = kDalvikByteCode;
1759
1760 // Mark it as hidden.
1761 hidden = true;
1762
1763 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1764 // are updated to know that they no longer have a parent.
1765 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1766 mir->bb = NullBasicBlockId;
1767 }
1768 first_mir_insn = nullptr;
1769 last_mir_insn = nullptr;
1770
1771 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1772
1773 MIRGraph* mir_graph = c_unit->mir_graph.get();
1774 while (true) {
1775 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1776 if (pred_bb == nullptr) {
1777 break;
1778 }
1779
1780 // Sadly we have to go through the children by hand here.
1781 pred_bb->ReplaceChild(id, NullBasicBlockId);
1782 }
1783
1784 // Iterate through children of bb we are hiding.
1785 ChildBlockIterator successorChildIter(this, mir_graph);
1786
1787 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1788 // Replace child with null child.
1789 childPtr->predecessors->Delete(id);
1790 }
1791}
1792
1793bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1794 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1795 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1796 // then it is not live out of this BB.
1797 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1798
1799 int last_ssa_reg = -1;
1800
1801 // Walk through the MIRs backwards.
1802 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1803 // Get ssa rep.
1804 SSARepresentation *ssa_rep = mir->ssa_rep;
1805
1806 // Go through the defines for this MIR.
1807 for (int i = 0; i < ssa_rep->num_defs; i++) {
1808 DCHECK(ssa_rep->defs != nullptr);
1809
1810 // Get the ssa reg.
1811 int def_ssa_reg = ssa_rep->defs[i];
1812
1813 // Get dalvik reg.
1814 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1815
1816 // Compare dalvik regs.
1817 if (dalvik_reg == def_dalvik_reg) {
1818 // We found a def of the register that we are being asked about.
1819 // Remember it.
1820 last_ssa_reg = def_ssa_reg;
1821 }
1822 }
1823 }
1824
1825 if (last_ssa_reg == -1) {
1826 // If we get to this point we couldn't find a define of register user asked about.
1827 // Let's assume the user knows what he's doing so we can be safe and say that if we
1828 // couldn't find a def, it is live out.
1829 return true;
1830 }
1831
1832 // If it is not -1, we found a match, is it ssa_reg?
1833 return (ssa_reg == last_ssa_reg);
1834}
1835
1836bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1837 // We need to check taken, fall_through, and successor_blocks to replace.
1838 bool found = false;
1839 if (taken == old_bb) {
1840 taken = new_bb;
1841 found = true;
1842 }
1843
1844 if (fall_through == old_bb) {
1845 fall_through = new_bb;
1846 found = true;
1847 }
1848
1849 if (successor_block_list_type != kNotUsed) {
1850 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1851 while (true) {
1852 SuccessorBlockInfo* successor_block_info = iterator.Next();
1853 if (successor_block_info == nullptr) {
1854 break;
1855 }
1856 if (successor_block_info->block == old_bb) {
1857 successor_block_info->block = new_bb;
1858 found = true;
1859 }
1860 }
1861 }
1862
1863 return found;
1864}
1865
1866void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1867 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1868 bool found = false;
1869
1870 while (true) {
1871 BasicBlockId pred_bb_id = iterator.Next();
1872
1873 if (pred_bb_id == NullBasicBlockId) {
1874 break;
1875 }
1876
1877 if (pred_bb_id == old_parent) {
1878 size_t idx = iterator.GetIndex() - 1;
1879 predecessors->Put(idx, new_parent);
1880 found = true;
1881 break;
1882 }
1883 }
1884
1885 // If not found, add it.
1886 if (found == false) {
1887 predecessors->Insert(new_parent);
1888 }
1889}
1890
1891// Create a new basic block with block_id as num_blocks_ that is
1892// post-incremented.
1893BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
1894 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
1895 block_list_.Insert(res);
1896 return res;
1897}
1898
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07001899void MIRGraph::CalculateBasicBlockInformation() {
1900 PassDriverMEPostOpt driver(cu_);
1901 driver.Launch();
1902}
1903
1904void MIRGraph::InitializeBasicBlockData() {
1905 num_blocks_ = block_list_.Size();
1906}
1907
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001908} // namespace art