blob: 0fffa01350d0f03411489d88489651c7ff426b96 [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),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070077 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070078 dfs_order_(NULL),
79 dfs_post_order_(NULL),
80 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070081 topological_order_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080082 i_dom_list_(NULL),
83 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000084 temp_scoped_alloc_(),
85 temp_insn_data_(nullptr),
86 temp_bit_vector_size_(0u),
87 temp_bit_vector_(nullptr),
buzbee862a7602013-04-05 10:58:54 -070088 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -080089 try_block_addr_(NULL),
90 entry_block_(NULL),
91 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -080092 num_blocks_(0),
93 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -070094 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080095 current_method_(kInvalidEntry),
96 current_offset_(kInvalidEntry),
97 def_count_(0),
98 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -070099 num_ssa_regs_(0),
100 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700101 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
102 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700103 arena_(arena),
104 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800105 forward_branches_(0),
106 compiler_temps_(arena, 6, kGrowableArrayMisc),
107 num_non_special_compiler_temps_(0),
buzbeeb1f1d642014-02-27 12:55:32 -0800108 max_available_non_special_compiler_temps_(0),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000109 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000110 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000111 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000112 sfield_lowering_infos_(arena, 0u),
113 method_lowering_infos_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700114 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800115 max_available_special_compiler_temps_ = std::abs(static_cast<int>(kVRegNonSpecialTempBaseReg))
116 - std::abs(static_cast<int>(kVRegTempBaseReg));
buzbee311ca162013-02-28 15:56:43 -0800117}
118
Ian Rogers6282dc12013-04-18 15:54:02 -0700119MIRGraph::~MIRGraph() {
120 STLDeleteElements(&m_units_);
121}
122
buzbee311ca162013-02-28 15:56:43 -0800123/*
124 * Parse an instruction, return the length of the instruction
125 */
Ian Rogers29a26482014-05-02 15:27:29 -0700126int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
127 const Instruction* inst = Instruction::At(code_ptr);
128 decoded_instruction->opcode = inst->Opcode();
129 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
130 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
131 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
132 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
133 if (inst->HasVarArgs()) {
134 inst->GetVarArgs(decoded_instruction->arg);
135 }
136 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800137}
138
139
140/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700141BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700142 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700143 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800144 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700145 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800146 while (insn) {
147 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700148 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800149 insn = insn->next;
150 }
151 if (insn == NULL) {
152 LOG(FATAL) << "Break split failed";
153 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700154 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700155 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800156
157 bottom_block->start_offset = code_offset;
158 bottom_block->first_mir_insn = insn;
159 bottom_block->last_mir_insn = orig_block->last_mir_insn;
160
161 /* If this block was terminated by a return, the flag needs to go with the bottom block */
162 bottom_block->terminated_by_return = orig_block->terminated_by_return;
163 orig_block->terminated_by_return = false;
164
buzbee311ca162013-02-28 15:56:43 -0800165 /* Handle the taken path */
166 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700167 if (bottom_block->taken != NullBasicBlockId) {
168 orig_block->taken = NullBasicBlockId;
169 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
170 bb_taken->predecessors->Delete(orig_block->id);
171 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800172 }
173
174 /* Handle the fallthrough path */
175 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700176 orig_block->fall_through = bottom_block->id;
177 bottom_block->predecessors->Insert(orig_block->id);
178 if (bottom_block->fall_through != NullBasicBlockId) {
179 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
180 bb_fall_through->predecessors->Delete(orig_block->id);
181 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800182 }
183
184 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700185 if (orig_block->successor_block_list_type != kNotUsed) {
186 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
187 bottom_block->successor_blocks = orig_block->successor_blocks;
188 orig_block->successor_block_list_type = kNotUsed;
189 orig_block->successor_blocks = NULL;
190 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800191 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700192 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800193 if (successor_block_info == NULL) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700194 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
buzbee0d829482013-10-11 15:24:55 -0700195 bb->predecessors->Delete(orig_block->id);
196 bb->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800197 }
198 }
199
buzbee0d829482013-10-11 15:24:55 -0700200 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700201 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800202
buzbee311ca162013-02-28 15:56:43 -0800203 /*
204 * Update the immediate predecessor block pointer so that outgoing edges
205 * can be applied to the proper block.
206 */
207 if (immed_pred_block_p) {
208 DCHECK_EQ(*immed_pred_block_p, orig_block);
209 *immed_pred_block_p = bottom_block;
210 }
buzbeeb48819d2013-09-14 16:15:25 -0700211
212 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000213 DCHECK(insn != nullptr);
214 DCHECK(insn != orig_block->first_mir_insn);
215 DCHECK(insn == bottom_block->first_mir_insn);
216 DCHECK_EQ(insn->offset, bottom_block->start_offset);
217 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
218 !IsPseudoMirOp(insn->dalvikInsn.opcode));
219 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
220 MIR* p = insn;
221 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
222 while (p != bottom_block->last_mir_insn) {
223 p = p->next;
224 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700225 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700226 int opcode = p->dalvikInsn.opcode;
227 /*
228 * Some messiness here to ensure that we only enter real opcodes and only the
229 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000230 * CHECK and work portions. Since the 2nd half of a split operation is always
231 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700232 */
Vladimir Marko4376c872014-01-23 12:39:29 +0000233 if ((opcode == kMirOpCheck) || !IsPseudoMirOp(opcode)) {
234 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700235 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
236 }
buzbeeb48819d2013-09-14 16:15:25 -0700237 }
238
buzbee311ca162013-02-28 15:56:43 -0800239 return bottom_block;
240}
241
242/*
243 * Given a code offset, find out the block that starts with it. If the offset
244 * is in the middle of an existing block, split it into two. If immed_pred_block_p
245 * is not non-null and is the block being split, update *immed_pred_block_p to
246 * point to the bottom block so that outgoing edges can be set up properly
247 * (by the caller)
248 * Utilizes a map for fast lookup of the typical cases.
249 */
buzbee0d829482013-10-11 15:24:55 -0700250BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700251 BasicBlock** immed_pred_block_p) {
buzbeebd663de2013-09-10 15:41:31 -0700252 if (code_offset >= cu_->code_item->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800253 return NULL;
254 }
buzbeeb48819d2013-09-14 16:15:25 -0700255
256 int block_id = dex_pc_to_block_map_.Get(code_offset);
257 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
258
259 if ((bb != NULL) && (bb->start_offset == code_offset)) {
260 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700261 return bb;
262 }
buzbee311ca162013-02-28 15:56:43 -0800263
buzbeeb48819d2013-09-14 16:15:25 -0700264 // No direct hit.
265 if (!create) {
266 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800267 }
268
buzbeeb48819d2013-09-14 16:15:25 -0700269 if (bb != NULL) {
270 // The target exists somewhere in an existing block.
271 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
272 }
273
274 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700275 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
276 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800277 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700278 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800279 return bb;
280}
281
buzbeeb48819d2013-09-14 16:15:25 -0700282
buzbee311ca162013-02-28 15:56:43 -0800283/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700284void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800285 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700286 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800287
288 if (tries_size == 0) {
289 return;
290 }
291
292 for (int i = 0; i < tries_size; i++) {
293 const DexFile::TryItem* pTry =
294 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700295 DexOffset start_offset = pTry->start_addr_;
296 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800297 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700298 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800299 }
300 }
301
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700302 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800303 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
304 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
305 for (uint32_t idx = 0; idx < handlers_size; idx++) {
306 CatchHandlerIterator iterator(handlers_ptr);
307 for (; iterator.HasNext(); iterator.Next()) {
308 uint32_t address = iterator.GetHandlerAddress();
309 FindBlock(address, false /* split */, true /*create*/,
310 /* immed_pred_block_p */ NULL);
311 }
312 handlers_ptr = iterator.EndDataPointer();
313 }
314}
315
316/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700317BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
318 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700319 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700320 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800321 switch (insn->dalvikInsn.opcode) {
322 case Instruction::GOTO:
323 case Instruction::GOTO_16:
324 case Instruction::GOTO_32:
325 target += insn->dalvikInsn.vA;
326 break;
327 case Instruction::IF_EQ:
328 case Instruction::IF_NE:
329 case Instruction::IF_LT:
330 case Instruction::IF_GE:
331 case Instruction::IF_GT:
332 case Instruction::IF_LE:
333 cur_block->conditional_branch = true;
334 target += insn->dalvikInsn.vC;
335 break;
336 case Instruction::IF_EQZ:
337 case Instruction::IF_NEZ:
338 case Instruction::IF_LTZ:
339 case Instruction::IF_GEZ:
340 case Instruction::IF_GTZ:
341 case Instruction::IF_LEZ:
342 cur_block->conditional_branch = true;
343 target += insn->dalvikInsn.vB;
344 break;
345 default:
346 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
347 }
buzbeeb48819d2013-09-14 16:15:25 -0700348 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700349 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800350 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700351 cur_block->taken = taken_block->id;
352 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800353
354 /* Always terminate the current block for conditional branches */
355 if (flags & Instruction::kContinue) {
356 BasicBlock *fallthrough_block = FindBlock(cur_offset + width,
357 /*
358 * If the method is processed
359 * in sequential order from the
360 * beginning, we don't need to
361 * specify split for continue
362 * blocks. However, this
363 * routine can be called by
364 * compileLoop, which starts
365 * parsing the method from an
366 * arbitrary address in the
367 * method body.
368 */
369 true,
370 /* create */
371 true,
372 /* immed_pred_block_p */
373 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700374 cur_block->fall_through = fallthrough_block->id;
375 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800376 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700377 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800378 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800379 }
380 return cur_block;
381}
382
383/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800384BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
385 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800386 const uint16_t* switch_data =
387 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
388 int size;
389 const int* keyTable;
390 const int* target_table;
391 int i;
392 int first_key;
393
394 /*
395 * Packed switch data format:
396 * ushort ident = 0x0100 magic value
397 * ushort size number of entries in the table
398 * int first_key first (and lowest) switch case value
399 * int targets[size] branch targets, relative to switch opcode
400 *
401 * Total size is (4+size*2) 16-bit code units.
402 */
403 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
404 DCHECK_EQ(static_cast<int>(switch_data[0]),
405 static_cast<int>(Instruction::kPackedSwitchSignature));
406 size = switch_data[1];
407 first_key = switch_data[2] | (switch_data[3] << 16);
408 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700409 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800410 /*
411 * Sparse switch data format:
412 * ushort ident = 0x0200 magic value
413 * ushort size number of entries in the table; > 0
414 * int keys[size] keys, sorted low-to-high; 32-bit aligned
415 * int targets[size] branch targets, relative to switch opcode
416 *
417 * Total size is (2+size*4) 16-bit code units.
418 */
419 } else {
420 DCHECK_EQ(static_cast<int>(switch_data[0]),
421 static_cast<int>(Instruction::kSparseSwitchSignature));
422 size = switch_data[1];
423 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
424 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700425 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800426 }
427
buzbee0d829482013-10-11 15:24:55 -0700428 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800429 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700430 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800431 }
buzbee0d829482013-10-11 15:24:55 -0700432 cur_block->successor_block_list_type =
433 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
434 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700435 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800436
437 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700438 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800439 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700440 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700441 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000442 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700443 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800444 successor_block_info->key =
445 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
446 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700447 cur_block->successor_blocks->Insert(successor_block_info);
448 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800449 }
450
451 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700452 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
453 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700454 cur_block->fall_through = fallthrough_block->id;
455 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800456 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800457}
458
459/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700460BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
461 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700462 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700463 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800464 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
465 bool build_all_edges =
466 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800467
468 /* In try block */
469 if (in_try_block) {
470 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
471
buzbee0d829482013-10-11 15:24:55 -0700472 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800473 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
474 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700475 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800476 }
477
buzbee0d829482013-10-11 15:24:55 -0700478 cur_block->successor_block_list_type = kCatch;
479 cur_block->successor_blocks =
buzbee862a7602013-04-05 10:58:54 -0700480 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, 2, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800481
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700482 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700483 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800484 false /* creat */, NULL /* immed_pred_block_p */);
485 catch_block->catch_entry = true;
486 if (kIsDebugBuild) {
487 catches_.insert(catch_block->start_offset);
488 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700489 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000490 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700491 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800492 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700493 cur_block->successor_blocks->Insert(successor_block_info);
494 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800495 }
buzbee17189ac2013-11-08 11:07:02 -0800496 } else if (build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700497 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700498 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700499 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800500 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700501 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800502 }
503
buzbee17189ac2013-11-08 11:07:02 -0800504 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800505 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700506 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700507 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800508 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
509 /* immed_pred_block_p */ NULL);
510 }
511 if (!in_try_block) {
512 // Don't split a THROW that can't rethrow - we're done.
513 return cur_block;
514 }
515 }
516
buzbee17189ac2013-11-08 11:07:02 -0800517 if (!build_all_edges) {
518 /*
519 * Even though there is an exception edge here, control cannot return to this
520 * method. Thus, for the purposes of dataflow analysis and optimization, we can
521 * ignore the edge. Doing this reduces compile time, and increases the scope
522 * of the basic-block level optimization pass.
523 */
524 return cur_block;
525 }
526
buzbee311ca162013-02-28 15:56:43 -0800527 /*
528 * Split the potentially-throwing instruction into two parts.
529 * The first half will be a pseudo-op that captures the exception
530 * edges and terminates the basic block. It always falls through.
531 * Then, create a new basic block that begins with the throwing instruction
532 * (minus exceptions). Note: this new basic block must NOT be entered into
533 * the block_map. If the potentially-throwing instruction is the target of a
534 * future branch, we need to find the check psuedo half. The new
535 * basic block containing the work portion of the instruction should
536 * only be entered via fallthrough from the block containing the
537 * pseudo exception edge MIR. Note also that this new block is
538 * not automatically terminated after the work portion, and may
539 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700540 *
541 * Note also that the dex_pc_to_block_map_ entry for the potentially
542 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800543 */
buzbee862a7602013-04-05 10:58:54 -0700544 BasicBlock *new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
545 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800546 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700547 cur_block->fall_through = new_block->id;
548 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700549 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800550 *new_insn = *insn;
551 insn->dalvikInsn.opcode =
552 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;
727 BasicBlock *next_block = FindBlock(current_offset_, /* split */ false, /* create */
728 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) :
839 (opcode < kMirOpFirst) ?
840 Instruction::Name(mir->dalvikInsn.opcode) :
841 extended_mir_op_names_[opcode - kMirOpFirst],
842 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
843 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
844 mir->next ? " | " : " ");
845 }
buzbee311ca162013-02-28 15:56:43 -0800846 }
847 fprintf(file, " }\"];\n\n");
848 } else if (bb->block_type == kExceptionHandling) {
849 char block_name[BLOCK_NAME_LEN];
850
851 GetBlockName(bb, block_name);
852 fprintf(file, " %s [shape=invhouse];\n", block_name);
853 }
854
855 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
856
buzbee0d829482013-10-11 15:24:55 -0700857 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800858 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700859 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800860 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
861 block_name1, block_name2);
862 }
buzbee0d829482013-10-11 15:24:55 -0700863 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800864 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700865 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800866 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
867 }
868
buzbee0d829482013-10-11 15:24:55 -0700869 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800870 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
871 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700872 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
873 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700874 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800875
876 int succ_id = 0;
877 while (true) {
878 if (successor_block_info == NULL) break;
879
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700880 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700881 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800882
883 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
884 succ_id++,
885 successor_block_info->key,
886 dest_block->start_offset,
887 (next_successor_block_info != NULL) ? " | " : " ");
888
889 successor_block_info = next_successor_block_info;
890 }
891 fprintf(file, " }\"];\n\n");
892
893 GetBlockName(bb, block_name1);
894 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
895 block_name1, bb->start_offset, bb->id);
896
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700897 // Link the successor pseudo-block with all of its potential targets.
898 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800899
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700900 succ_id = 0;
901 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700902 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700903 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -0800904
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700905 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800906
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700907 GetBlockName(dest_block, block_name2);
908 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
909 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800910 }
911 }
912 fprintf(file, "\n");
913
914 if (cu_->verbose) {
915 /* Display the dominator tree */
916 GetBlockName(bb, block_name1);
917 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
918 block_name1, block_name1);
919 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700920 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800921 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
922 }
923 }
924 }
925 fprintf(file, "}\n");
926 fclose(file);
927}
928
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700929/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700930void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700931 // Insert it after the last MIR.
932 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -0700933}
934
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700935void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
936 // Insert it after the last MIR.
937 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
938}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700939
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700940void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
941 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
942 MIR* new_mir = *it;
943
944 // Add a copy of each MIR.
945 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
946 }
buzbee1fd33462013-03-25 13:40:45 -0700947}
948
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700949/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700950void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700951 InsertMIRListAfter(current_mir, new_mir, new_mir);
952}
buzbee1fd33462013-03-25 13:40:45 -0700953
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700954void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
955 // If no MIR, we are done.
956 if (first_list_mir == nullptr || last_list_mir == nullptr) {
957 return;
buzbee1fd33462013-03-25 13:40:45 -0700958 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700959
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700960 // If insert_after is null, assume BB is empty.
961 if (insert_after == nullptr) {
962 first_mir_insn = first_list_mir;
963 last_mir_insn = last_list_mir;
964 last_list_mir->next = nullptr;
965 } else {
966 MIR* after_list = insert_after->next;
967 insert_after->next = first_list_mir;
968 last_list_mir->next = after_list;
969 if (after_list == nullptr) {
970 last_mir_insn = last_list_mir;
971 }
972 }
973
974 // Set this BB to be the basic block of the MIRs.
975 MIR* last = last_list_mir->next;
976 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
977 mir->bb = id;
978 }
979}
980
981/* Insert an MIR instruction to the head of a basic block. */
982void BasicBlock::PrependMIR(MIR* mir) {
983 InsertMIRListBefore(first_mir_insn, mir, mir);
984}
985
986void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
987 // Insert it before the first MIR.
988 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
989}
990
991void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
992 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
993 MIR* mir = *it;
994
995 InsertMIRListBefore(first_mir_insn, mir, mir);
996 }
997}
998
999/* Insert a MIR instruction before the specified MIR. */
1000void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1001 // Insert as a single element list.
1002 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001003}
1004
1005MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1006 MIR* current = first_mir_insn;
1007
1008 while (current != nullptr) {
1009 MIR* next = current->next;
1010
1011 if (next == mir) {
1012 return current;
1013 }
1014
1015 current = next;
1016 }
1017
1018 return nullptr;
1019}
1020
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001021void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1022 // If no MIR, we are done.
1023 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1024 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001025 }
1026
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001027 // If insert_before is null, assume BB is empty.
1028 if (insert_before == nullptr) {
1029 first_mir_insn = first_list_mir;
1030 last_mir_insn = last_list_mir;
1031 last_list_mir->next = nullptr;
1032 } else {
1033 if (first_mir_insn == insert_before) {
1034 last_list_mir->next = first_mir_insn;
1035 first_mir_insn = first_list_mir;
1036 } else {
1037 // Find the preceding MIR.
1038 MIR* before_list = FindPreviousMIR(insert_before);
1039 DCHECK(before_list != nullptr);
1040 before_list->next = first_list_mir;
1041 last_list_mir->next = insert_before;
1042 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001043 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001044
1045 // Set this BB to be the basic block of the MIRs.
1046 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1047 mir->bb = id;
1048 }
1049}
1050
1051bool BasicBlock::RemoveMIR(MIR* mir) {
1052 // Remove as a single element list.
1053 return RemoveMIRList(mir, mir);
1054}
1055
1056bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1057 if (first_list_mir == nullptr) {
1058 return false;
1059 }
1060
1061 // Try to find the MIR.
1062 MIR* before_list = nullptr;
1063 MIR* after_list = nullptr;
1064
1065 // If we are removing from the beginning of the MIR list.
1066 if (first_mir_insn == first_list_mir) {
1067 before_list = nullptr;
1068 } else {
1069 before_list = FindPreviousMIR(first_list_mir);
1070 if (before_list == nullptr) {
1071 // We did not find the mir.
1072 return false;
1073 }
1074 }
1075
1076 // Remove the BB information and also find the after_list
1077 for (MIR* mir = first_list_mir; mir != last_list_mir; mir = mir->next) {
1078 mir->bb = NullBasicBlockId;
1079 }
1080
1081 after_list = last_list_mir->next;
1082
1083 // If there is nothing before the list, after_list is the first_mir
1084 if (before_list == nullptr) {
1085 first_mir_insn = after_list;
1086 }
1087
1088 // If there is nothing after the list, before_list is last_mir
1089 if (after_list == nullptr) {
1090 last_mir_insn = before_list;
1091 }
1092
1093 return true;
buzbee1fd33462013-03-25 13:40:45 -07001094}
1095
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001096MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001097 MIR* next_mir = nullptr;
1098
1099 if (current != nullptr) {
1100 next_mir = current->next;
1101 }
1102
1103 if (next_mir == nullptr) {
1104 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001105 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1106 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001107 }
1108 }
1109
1110 return next_mir;
1111}
1112
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001113char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001114 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001115 std::string str;
1116 int flags = 0;
1117 int opcode = insn.opcode;
1118 char* ret;
1119 bool nop = false;
1120 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001121 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001122 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1123 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
1124
1125 // Handle special cases.
1126 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1127 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1128 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001129 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001130 insn = mir->meta.throw_insn->dalvikInsn;
1131 ssa_rep = mir->meta.throw_insn->ssa_rep;
1132 defs = ssa_rep->num_defs;
1133 uses = ssa_rep->num_uses;
1134 opcode = insn.opcode;
1135 } else if (opcode == kMirOpNop) {
1136 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001137 // Recover original opcode.
1138 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1139 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001140 nop = true;
1141 }
1142
1143 if (opcode >= kMirOpFirst) {
1144 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1145 } else {
1146 dalvik_format = Instruction::FormatOf(insn.opcode);
1147 flags = Instruction::FlagsOf(insn.opcode);
1148 str.append(Instruction::Name(insn.opcode));
1149 }
1150
1151 if (opcode == kMirOpPhi) {
buzbee0d829482013-10-11 15:24:55 -07001152 BasicBlockId* incoming = mir->meta.phi_incoming;
buzbee1fd33462013-03-25 13:40:45 -07001153 str.append(StringPrintf(" %s = (%s",
1154 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1155 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
Brian Carlstromb1eba212013-07-17 18:07:19 -07001156 str.append(StringPrintf(":%d", incoming[0]));
buzbee1fd33462013-03-25 13:40:45 -07001157 int i;
1158 for (i = 1; i < uses; i++) {
1159 str.append(StringPrintf(", %s:%d",
1160 GetSSANameWithConst(ssa_rep->uses[i], true).c_str(),
1161 incoming[i]));
1162 }
1163 str.append(")");
1164 } else if ((flags & Instruction::kBranch) != 0) {
1165 // For branches, decode the instructions to print out the branch targets.
1166 int offset = 0;
1167 switch (dalvik_format) {
1168 case Instruction::k21t:
1169 str.append(StringPrintf(" %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1170 offset = insn.vB;
1171 break;
1172 case Instruction::k22t:
1173 str.append(StringPrintf(" %s, %s,", GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1174 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1175 offset = insn.vC;
1176 break;
1177 case Instruction::k10t:
1178 case Instruction::k20t:
1179 case Instruction::k30t:
1180 offset = insn.vA;
1181 break;
1182 default:
1183 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
1184 }
1185 str.append(StringPrintf(" 0x%x (%c%x)", mir->offset + offset,
1186 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1187 } else {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001188 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001189 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1190 (dalvik_format == Instruction::k3rc));
1191 if (defs != 0) {
1192 str.append(StringPrintf(" %s", GetSSANameWithConst(ssa_rep->defs[0], false).c_str()));
1193 if (uses != 0) {
1194 str.append(", ");
1195 }
1196 }
1197 for (int i = 0; i < uses; i++) {
1198 str.append(
1199 StringPrintf(" %s", GetSSANameWithConst(ssa_rep->uses[i], show_singles).c_str()));
1200 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1201 // For the listing, skip the high sreg.
1202 i++;
1203 }
1204 if (i != (uses -1)) {
1205 str.append(",");
1206 }
1207 }
1208 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001209 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001210 case Instruction::k21s:
1211 case Instruction::k31i:
1212 case Instruction::k21h:
1213 str.append(StringPrintf(", #%d", insn.vB));
1214 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001215 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001216 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001217 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001218 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001219 case Instruction::k31c:
1220 str.append(StringPrintf(", index #%d", insn.vB));
1221 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001222 case Instruction::k22c: // Two registers, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001223 str.append(StringPrintf(", index #%d", insn.vC));
1224 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001225 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001226 case Instruction::k22b:
1227 str.append(StringPrintf(", #%d", insn.vC));
1228 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001229 default: {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001230 // Nothing left to print.
buzbee1fd33462013-03-25 13:40:45 -07001231 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001232 }
buzbee1fd33462013-03-25 13:40:45 -07001233 }
1234 if (nop) {
1235 str.append("]--optimized away");
1236 }
1237 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001238 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001239 strncpy(ret, str.c_str(), length);
1240 return ret;
1241}
1242
1243/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001244void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001245 static const struct { const char before; const char after; } match[] = {
1246 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1247 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1248 };
buzbee1fd33462013-03-25 13:40:45 -07001249 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1250 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1251 }
1252}
1253
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001254std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001255 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1256 // the arena. We should be smarter and just place straight into the arena, or compute the
1257 // value more lazily.
buzbee1fd33462013-03-25 13:40:45 -07001258 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1259}
1260
1261// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001262std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001263 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001264 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001265 return GetSSAName(ssa_reg);
1266 }
1267 if (IsConst(reg_location_[ssa_reg])) {
1268 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001269 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001270 ConstantValueWide(reg_location_[ssa_reg]));
1271 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001272 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001273 ConstantValue(reg_location_[ssa_reg]));
1274 }
1275 } else {
1276 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1277 }
1278}
1279
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001280void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001281 switch (bb->block_type) {
1282 case kEntryBlock:
1283 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1284 break;
1285 case kExitBlock:
1286 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1287 break;
1288 case kDalvikByteCode:
1289 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1290 break;
1291 case kExceptionHandling:
1292 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1293 bb->id);
1294 break;
1295 default:
1296 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1297 break;
1298 }
1299}
1300
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001301const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001302 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001303 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1304 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1305}
1306
1307/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001308void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001309 BasicBlock* bb;
1310 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001311 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001312 "Entry Block",
1313 "Code Block",
1314 "Exit Block",
1315 "Exception Handling",
1316 "Catch Block"
1317 };
1318
1319 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1320 LOG(INFO) << cu_->insns << " insns";
1321 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001322 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001323
1324 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001325 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001326 if (bb == NULL) break;
1327 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1328 bb->id,
1329 block_type_names[bb->block_type],
1330 bb->start_offset,
1331 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1332 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001333 if (bb->taken != NullBasicBlockId) {
1334 LOG(INFO) << " Taken branch: block " << bb->taken
1335 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001336 }
buzbee0d829482013-10-11 15:24:55 -07001337 if (bb->fall_through != NullBasicBlockId) {
1338 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1339 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001340 }
1341 }
1342}
1343
1344/*
1345 * Build an array of location records for the incoming arguments.
1346 * Note: one location record per word of arguments, with dummy
1347 * high-word loc for wide arguments. Also pull up any following
1348 * MOVE_RESULT and incorporate it into the invoke.
1349 */
1350CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001351 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001352 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001353 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001354 MIR* move_result_mir = FindMoveResult(bb, mir);
1355 if (move_result_mir == NULL) {
1356 info->result.location = kLocInvalid;
1357 } else {
1358 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001359 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1360 }
1361 info->num_arg_words = mir->ssa_rep->num_uses;
1362 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001363 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001364 for (int i = 0; i < info->num_arg_words; i++) {
1365 info->args[i] = GetRawSrc(mir, i);
1366 }
1367 info->opt_flags = mir->optimization_flags;
1368 info->type = type;
1369 info->is_range = is_range;
1370 info->index = mir->dalvikInsn.vB;
1371 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001372 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001373 return info;
1374}
1375
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001376// Allocate a new MIR.
1377MIR* MIRGraph::NewMIR() {
1378 MIR* mir = new (arena_) MIR();
1379 return mir;
1380}
1381
buzbee862a7602013-04-05 10:58:54 -07001382// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001383BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001384 BasicBlock* bb = new (arena_) BasicBlock();
1385
buzbee862a7602013-04-05 10:58:54 -07001386 bb->block_type = block_type;
1387 bb->id = block_id;
1388 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001389 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001390 (block_type == kExitBlock) ? 2048 : 2,
1391 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001392 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001393 block_id_map_.Put(block_id, block_id);
1394 return bb;
1395}
buzbee1fd33462013-03-25 13:40:45 -07001396
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001397void MIRGraph::InitializeConstantPropagation() {
1398 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001399 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001400}
1401
1402void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001403 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001404 int num_ssa_regs = GetNumSSARegs();
1405 use_counts_.Resize(num_ssa_regs + 32);
1406 raw_use_counts_.Resize(num_ssa_regs + 32);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001407 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001408 for (int i = 0; i < num_ssa_regs; i++) {
1409 use_counts_.Insert(0);
1410 raw_use_counts_.Insert(0);
1411 }
1412}
1413
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001414void MIRGraph::SSATransformationStart() {
1415 DCHECK(temp_scoped_alloc_.get() == nullptr);
1416 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1417 temp_bit_vector_size_ = cu_->num_dalvik_registers;
1418 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1419 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1420
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001421 /* Compute the DFS order */
1422 ComputeDFSOrders();
1423
1424 /* Compute the dominator info */
1425 ComputeDominators();
1426
1427 /* Allocate data structures in preparation for SSA conversion */
1428 CompilerInitializeSSAConversion();
1429
1430 /* Find out the "Dalvik reg def x block" relation */
1431 ComputeDefBlockMatrix();
1432
1433 /* Insert phi nodes to dominance frontiers for all variables */
1434 InsertPhiNodes();
1435
1436 /* Rename register names by local defs and phi nodes */
1437 ClearAllVisitedFlags();
1438 DoDFSPreOrderSSARename(GetEntryBlock());
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001439
1440 // Update the maximum number of reachable blocks.
1441 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001442}
1443
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001444void MIRGraph::SSATransformationEnd() {
1445 // Verify the dataflow information after the pass.
1446 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1447 VerifyDataflow();
1448 }
1449
1450 temp_bit_vector_size_ = 0u;
1451 temp_bit_vector_ = nullptr;
1452 DCHECK(temp_scoped_alloc_.get() != nullptr);
1453 temp_scoped_alloc_.reset();
1454}
1455
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001456void MIRGraph::ComputeTopologicalSortOrder() {
1457 std::queue<BasicBlock *> q;
1458 std::map<int, int> visited_cnt_values;
1459
1460 // Clear the nodes.
1461 ClearAllVisitedFlags();
1462
1463 // Create the topological order if need be.
1464 if (topological_order_ != nullptr) {
1465 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, 0);
1466 }
1467 topological_order_->Reset();
1468
1469 // Set up visitedCntValues map for all BB. The default value for this counters in the map is zero.
1470 // also fill initial queue.
1471 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1472
1473 while (true) {
1474 BasicBlock* bb = iterator.Next();
1475
1476 if (bb == nullptr) {
1477 break;
1478 }
1479
1480 if (bb->hidden == true) {
1481 continue;
1482 }
1483
1484 visited_cnt_values[bb->id] = bb->predecessors->Size();
1485
1486 GrowableArray<BasicBlockId>::Iterator pred_iterator(bb->predecessors);
1487 // To process loops we should not wait for dominators.
1488 while (true) {
1489 BasicBlock* pred_bb = GetBasicBlock(pred_iterator.Next());
1490
1491 if (pred_bb == nullptr) {
1492 break;
1493 }
1494
1495 if (pred_bb->dominators == nullptr || pred_bb->hidden == true) {
1496 continue;
1497 }
1498
1499 // Skip the backward branch.
1500 if (pred_bb->dominators->IsBitSet(bb->id) != 0) {
1501 visited_cnt_values[bb->id]--;
1502 }
1503 }
1504
1505 // Add entry block to queue.
1506 if (visited_cnt_values[bb->id] == 0) {
1507 q.push(bb);
1508 }
1509 }
1510
1511 while (q.size() > 0) {
1512 // Get top.
1513 BasicBlock *bb = q.front();
1514 q.pop();
1515
1516 DCHECK_EQ(bb->hidden, false);
1517
1518 if (bb->IsExceptionBlock() == true) {
1519 continue;
1520 }
1521
1522 // We've visited all the predecessors. So, we can visit bb.
1523 if (bb->visited == false) {
1524 bb->visited = true;
1525
1526 // Now add the basic block.
1527 topological_order_->Insert(bb->id);
1528
1529 // Reduce visitedCnt for all the successors and add into the queue ones with visitedCnt equals to zero.
1530 ChildBlockIterator succIter(bb, this);
1531 BasicBlock *successor = succIter.Next();
1532 while (successor != nullptr) {
1533 // one more predecessor was visited.
1534 visited_cnt_values[successor->id]--;
1535
1536 if (visited_cnt_values[successor->id] <= 0 && successor->visited == false && successor->hidden == false) {
1537 q.push(successor);
1538 }
1539
1540 // Take next successor.
1541 successor = succIter.Next();
1542 }
1543 }
1544 }
1545}
1546
1547bool BasicBlock::IsExceptionBlock() const {
1548 if (block_type == kExceptionHandling) {
1549 return true;
1550 }
1551 return false;
1552}
1553
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001554ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1555 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1556 visited_taken_(false), have_successors_(false) {
1557 // Check if we actually do have successors.
1558 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1559 have_successors_ = true;
1560 successor_iter_.Reset(basic_block_->successor_blocks);
1561 }
1562}
1563
1564BasicBlock* ChildBlockIterator::Next() {
1565 // We check if we have a basic block. If we don't we cannot get next child.
1566 if (basic_block_ == nullptr) {
1567 return nullptr;
1568 }
1569
1570 // If we haven't visited fallthrough, return that.
1571 if (visited_fallthrough_ == false) {
1572 visited_fallthrough_ = true;
1573
1574 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
1575 if (result != nullptr) {
1576 return result;
1577 }
1578 }
1579
1580 // If we haven't visited taken, return that.
1581 if (visited_taken_ == false) {
1582 visited_taken_ = true;
1583
1584 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
1585 if (result != nullptr) {
1586 return result;
1587 }
1588 }
1589
1590 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
1591 if (have_successors_ == true) {
1592 // Get information about next successor block.
1593 SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
1594
1595 // If we don't have anymore successors, return nullptr.
1596 if (successor_block_info != nullptr) {
1597 return mir_graph_->GetBasicBlock(successor_block_info->block);
1598 }
1599 }
1600
1601 // We do not have anything.
1602 return nullptr;
1603}
1604
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001605BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
1606 MIRGraph* mir_graph = c_unit->mir_graph.get();
1607 return Copy(mir_graph);
1608}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001609
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001610BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
1611 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001612
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001613 // We don't do a memcpy style copy here because it would lead to a lot of things
1614 // to clean up. Let us do it by hand instead.
1615 // Copy in taken and fallthrough.
1616 result_bb->fall_through = fall_through;
1617 result_bb->taken = taken;
1618
1619 // Copy successor links if needed.
1620 ArenaAllocator* arena = mir_graph->GetArena();
1621
1622 result_bb->successor_block_list_type = successor_block_list_type;
1623 if (result_bb->successor_block_list_type != kNotUsed) {
1624 size_t size = successor_blocks->Size();
1625 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
1626 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1627 while (true) {
1628 SuccessorBlockInfo* sbi_old = iterator.Next();
1629 if (sbi_old == nullptr) {
1630 break;
1631 }
1632 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
1633 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
1634 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001635 }
1636 }
1637
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001638 // Copy offset, method.
1639 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001640
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001641 // Now copy instructions.
1642 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
1643 // Get a copy first.
1644 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001645
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001646 // Append it.
1647 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001648 }
1649
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001650 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001651}
1652
1653MIR* MIR::Copy(MIRGraph* mir_graph) {
1654 MIR* res = mir_graph->NewMIR();
1655 *res = *this;
1656
1657 // Remove links
1658 res->next = nullptr;
1659 res->bb = NullBasicBlockId;
1660 res->ssa_rep = nullptr;
1661
1662 return res;
1663}
1664
1665MIR* MIR::Copy(CompilationUnit* c_unit) {
1666 return Copy(c_unit->mir_graph.get());
1667}
1668
1669uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
1670 // Default result.
1671 int res = 0;
1672
1673 // We are basically setting the iputs to their igets counterparts.
1674 switch (opcode) {
1675 case Instruction::IPUT:
1676 case Instruction::IPUT_OBJECT:
1677 case Instruction::IPUT_BOOLEAN:
1678 case Instruction::IPUT_BYTE:
1679 case Instruction::IPUT_CHAR:
1680 case Instruction::IPUT_SHORT:
1681 case Instruction::IPUT_QUICK:
1682 case Instruction::IPUT_OBJECT_QUICK:
1683 case Instruction::APUT:
1684 case Instruction::APUT_OBJECT:
1685 case Instruction::APUT_BOOLEAN:
1686 case Instruction::APUT_BYTE:
1687 case Instruction::APUT_CHAR:
1688 case Instruction::APUT_SHORT:
1689 case Instruction::SPUT:
1690 case Instruction::SPUT_OBJECT:
1691 case Instruction::SPUT_BOOLEAN:
1692 case Instruction::SPUT_BYTE:
1693 case Instruction::SPUT_CHAR:
1694 case Instruction::SPUT_SHORT:
1695 // Skip the VR containing what to store.
1696 res = 1;
1697 break;
1698 case Instruction::IPUT_WIDE:
1699 case Instruction::IPUT_WIDE_QUICK:
1700 case Instruction::APUT_WIDE:
1701 case Instruction::SPUT_WIDE:
1702 // Skip the two VRs containing what to store.
1703 res = 2;
1704 break;
1705 default:
1706 // Do nothing in the general case.
1707 break;
1708 }
1709
1710 return res;
1711}
1712
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07001713/**
1714 * @brief Given a decoded instruction, it checks whether the instruction
1715 * sets a constant and if it does, more information is provided about the
1716 * constant being set.
1717 * @param ptr_value pointer to a 64-bit holder for the constant.
1718 * @param wide Updated by function whether a wide constant is being set by bytecode.
1719 * @return Returns false if the decoded instruction does not represent a constant bytecode.
1720 */
1721bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
1722 bool sets_const = true;
1723 int64_t value = vB;
1724
1725 DCHECK(ptr_value != nullptr);
1726 DCHECK(wide != nullptr);
1727
1728 switch (opcode) {
1729 case Instruction::CONST_4:
1730 case Instruction::CONST_16:
1731 case Instruction::CONST:
1732 *wide = false;
1733 value <<= 32; // In order to get the sign extend.
1734 value >>= 32;
1735 break;
1736 case Instruction::CONST_HIGH16:
1737 *wide = false;
1738 value <<= 48; // In order to get the sign extend.
1739 value >>= 32;
1740 break;
1741 case Instruction::CONST_WIDE_16:
1742 case Instruction::CONST_WIDE_32:
1743 *wide = true;
1744 value <<= 32; // In order to get the sign extend.
1745 value >>= 32;
1746 break;
1747 case Instruction::CONST_WIDE:
1748 *wide = true;
1749 value = vB_wide;
1750 break;
1751 case Instruction::CONST_WIDE_HIGH16:
1752 *wide = true;
1753 value <<= 48; // In order to get the sign extend.
1754 break;
1755 default:
1756 sets_const = false;
1757 break;
1758 }
1759
1760 if (sets_const) {
1761 *ptr_value = value;
1762 }
1763
1764 return sets_const;
1765}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001766
1767void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
1768 // Reset flags for all MIRs in bb.
1769 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
1770 mir->optimization_flags &= (~reset_flags);
1771 }
1772}
1773
1774void BasicBlock::Hide(CompilationUnit* c_unit) {
1775 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
1776 block_type = kDalvikByteCode;
1777
1778 // Mark it as hidden.
1779 hidden = true;
1780
1781 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
1782 // are updated to know that they no longer have a parent.
1783 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1784 mir->bb = NullBasicBlockId;
1785 }
1786 first_mir_insn = nullptr;
1787 last_mir_insn = nullptr;
1788
1789 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1790
1791 MIRGraph* mir_graph = c_unit->mir_graph.get();
1792 while (true) {
1793 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
1794 if (pred_bb == nullptr) {
1795 break;
1796 }
1797
1798 // Sadly we have to go through the children by hand here.
1799 pred_bb->ReplaceChild(id, NullBasicBlockId);
1800 }
1801
1802 // Iterate through children of bb we are hiding.
1803 ChildBlockIterator successorChildIter(this, mir_graph);
1804
1805 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
1806 // Replace child with null child.
1807 childPtr->predecessors->Delete(id);
1808 }
1809}
1810
1811bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
1812 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
1813 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
1814 // then it is not live out of this BB.
1815 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
1816
1817 int last_ssa_reg = -1;
1818
1819 // Walk through the MIRs backwards.
1820 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
1821 // Get ssa rep.
1822 SSARepresentation *ssa_rep = mir->ssa_rep;
1823
1824 // Go through the defines for this MIR.
1825 for (int i = 0; i < ssa_rep->num_defs; i++) {
1826 DCHECK(ssa_rep->defs != nullptr);
1827
1828 // Get the ssa reg.
1829 int def_ssa_reg = ssa_rep->defs[i];
1830
1831 // Get dalvik reg.
1832 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
1833
1834 // Compare dalvik regs.
1835 if (dalvik_reg == def_dalvik_reg) {
1836 // We found a def of the register that we are being asked about.
1837 // Remember it.
1838 last_ssa_reg = def_ssa_reg;
1839 }
1840 }
1841 }
1842
1843 if (last_ssa_reg == -1) {
1844 // If we get to this point we couldn't find a define of register user asked about.
1845 // Let's assume the user knows what he's doing so we can be safe and say that if we
1846 // couldn't find a def, it is live out.
1847 return true;
1848 }
1849
1850 // If it is not -1, we found a match, is it ssa_reg?
1851 return (ssa_reg == last_ssa_reg);
1852}
1853
1854bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
1855 // We need to check taken, fall_through, and successor_blocks to replace.
1856 bool found = false;
1857 if (taken == old_bb) {
1858 taken = new_bb;
1859 found = true;
1860 }
1861
1862 if (fall_through == old_bb) {
1863 fall_through = new_bb;
1864 found = true;
1865 }
1866
1867 if (successor_block_list_type != kNotUsed) {
1868 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
1869 while (true) {
1870 SuccessorBlockInfo* successor_block_info = iterator.Next();
1871 if (successor_block_info == nullptr) {
1872 break;
1873 }
1874 if (successor_block_info->block == old_bb) {
1875 successor_block_info->block = new_bb;
1876 found = true;
1877 }
1878 }
1879 }
1880
1881 return found;
1882}
1883
1884void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
1885 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
1886 bool found = false;
1887
1888 while (true) {
1889 BasicBlockId pred_bb_id = iterator.Next();
1890
1891 if (pred_bb_id == NullBasicBlockId) {
1892 break;
1893 }
1894
1895 if (pred_bb_id == old_parent) {
1896 size_t idx = iterator.GetIndex() - 1;
1897 predecessors->Put(idx, new_parent);
1898 found = true;
1899 break;
1900 }
1901 }
1902
1903 // If not found, add it.
1904 if (found == false) {
1905 predecessors->Insert(new_parent);
1906 }
1907}
1908
1909// Create a new basic block with block_id as num_blocks_ that is
1910// post-incremented.
1911BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
1912 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
1913 block_list_.Insert(res);
1914 return res;
1915}
1916
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001917} // namespace art