blob: 93b774c67b61cfe60e82dd30bdc6687cdd8548a9 [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 Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070023#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080024#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080025#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070026#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010027#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000028#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000030#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070031#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010033#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000034
buzbee311ca162013-02-28 15:56:43 -080035namespace art {
36
37#define MAX_PATTERN_LEN 5
38
buzbee1fd33462013-03-25 13:40:45 -070039const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
40 "Phi",
41 "Copy",
42 "FusedCmplFloat",
43 "FusedCmpgFloat",
44 "FusedCmplDouble",
45 "FusedCmpgDouble",
46 "FusedCmpLong",
47 "Nop",
48 "OpNullCheck",
49 "OpRangeCheck",
50 "OpDivZeroCheck",
51 "Check1",
52 "Check2",
53 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040054 "ConstVector",
55 "MoveVector",
56 "PackedMultiply",
57 "PackedAddition",
58 "PackedSubtract",
59 "PackedShiftLeft",
60 "PackedSignedShiftRight",
61 "PackedUnsignedShiftRight",
62 "PackedAnd",
63 "PackedOr",
64 "PackedXor",
65 "PackedAddReduce",
66 "PackedReduce",
67 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070068 "ReserveVectorRegisters",
69 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070070 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070071 "PackedArrayGet",
72 "PackedArrayPut",
buzbee1fd33462013-03-25 13:40:45 -070073};
74
buzbee862a7602013-04-05 10:58:54 -070075MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070076 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010077 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070078 cu_(cu),
buzbee311ca162013-02-28 15:56:43 -080079 ssa_base_vregs_(NULL),
80 ssa_subscripts_(NULL),
buzbee311ca162013-02-28 15:56:43 -080081 vreg_to_ssa_map_(NULL),
82 ssa_last_defs_(NULL),
83 is_constant_v_(NULL),
84 constant_values_(NULL),
buzbee862a7602013-04-05 10:58:54 -070085 use_counts_(arena, 256, kGrowableArrayMisc),
86 raw_use_counts_(arena, 256, kGrowableArrayMisc),
buzbee311ca162013-02-28 15:56:43 -080087 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070088 max_num_reachable_blocks_(0),
buzbee862a7602013-04-05 10:58:54 -070089 dfs_order_(NULL),
90 dfs_post_order_(NULL),
91 dom_post_order_traversal_(NULL),
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -070092 topological_order_(nullptr),
Vladimir Marko55fff042014-07-10 12:42:52 +010093 topological_order_loop_ends_(nullptr),
94 topological_order_indexes_(nullptr),
95 topological_order_loop_head_stack_(nullptr),
buzbee311ca162013-02-28 15:56:43 -080096 i_dom_list_(NULL),
97 def_block_matrix_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000098 temp_scoped_alloc_(),
99 temp_insn_data_(nullptr),
100 temp_bit_vector_size_(0u),
101 temp_bit_vector_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +0100102 temp_gvn_(),
buzbee862a7602013-04-05 10:58:54 -0700103 block_list_(arena, 100, kGrowableArrayBlockList),
buzbee311ca162013-02-28 15:56:43 -0800104 try_block_addr_(NULL),
105 entry_block_(NULL),
106 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800107 num_blocks_(0),
108 current_code_item_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700109 dex_pc_to_block_map_(arena, 0, kGrowableArrayMisc),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100110 m_units_(arena->Adapter()),
111 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800112 current_method_(kInvalidEntry),
113 current_offset_(kInvalidEntry),
114 def_count_(0),
115 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700116 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100117 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700118 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700119 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
120 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700121 arena_(arena),
122 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800123 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800124 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700125 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
126 requested_backend_temp_(false),
127 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000128 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000129 merged_df_flags_(0u),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000130 ifield_lowering_infos_(arena, 0u),
Vladimir Markof096aad2014-01-23 15:51:58 +0000131 sfield_lowering_infos_(arena, 0u),
Wei Jin04f4d8a2014-05-29 18:04:29 -0700132 method_lowering_infos_(arena, 0u),
133 gen_suspend_test_list_(arena, 0u) {
buzbee862a7602013-04-05 10:58:54 -0700134 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700135
136
137 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
138 // X86 requires a temp to keep track of the method address.
139 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
140 // this needs to be updated to reserve 0 temps for BE.
141 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
142 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
143 } else {
144 // Other architectures do not have a known lower bound for non-special temps.
145 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
146 max_available_non_special_compiler_temps_ = 0;
147 reserved_temps_for_backend_ = 0;
148 }
buzbee311ca162013-02-28 15:56:43 -0800149}
150
Ian Rogers6282dc12013-04-18 15:54:02 -0700151MIRGraph::~MIRGraph() {
152 STLDeleteElements(&m_units_);
153}
154
buzbee311ca162013-02-28 15:56:43 -0800155/*
156 * Parse an instruction, return the length of the instruction
157 */
Ian Rogers29a26482014-05-02 15:27:29 -0700158int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
159 const Instruction* inst = Instruction::At(code_ptr);
160 decoded_instruction->opcode = inst->Opcode();
161 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
162 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
163 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
164 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
165 if (inst->HasVarArgs()) {
166 inst->GetVarArgs(decoded_instruction->arg);
167 }
168 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800169}
170
171
172/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700173BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700174 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700175 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800176 MIR* insn = orig_block->first_mir_insn;
buzbee0d829482013-10-11 15:24:55 -0700177 MIR* prev = NULL;
buzbee311ca162013-02-28 15:56:43 -0800178 while (insn) {
179 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700180 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800181 insn = insn->next;
182 }
183 if (insn == NULL) {
184 LOG(FATAL) << "Break split failed";
185 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700186 BasicBlock* bottom_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700187 block_list_.Insert(bottom_block);
buzbee311ca162013-02-28 15:56:43 -0800188
189 bottom_block->start_offset = code_offset;
190 bottom_block->first_mir_insn = insn;
191 bottom_block->last_mir_insn = orig_block->last_mir_insn;
192
Junmo Park90223cc2014-08-04 18:51:21 +0900193 /* If this block was terminated by a return, conditional branch or throw,
194 * the flag needs to go with the bottom block
195 */
buzbee311ca162013-02-28 15:56:43 -0800196 bottom_block->terminated_by_return = orig_block->terminated_by_return;
197 orig_block->terminated_by_return = false;
198
Junmo Park90223cc2014-08-04 18:51:21 +0900199 bottom_block->conditional_branch = orig_block->conditional_branch;
200 orig_block->conditional_branch = false;
201
202 bottom_block->explicit_throw = orig_block->explicit_throw;
203 orig_block->explicit_throw = false;
204
buzbee311ca162013-02-28 15:56:43 -0800205 /* Handle the taken path */
206 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700207 if (bottom_block->taken != NullBasicBlockId) {
208 orig_block->taken = NullBasicBlockId;
209 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
210 bb_taken->predecessors->Delete(orig_block->id);
211 bb_taken->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800212 }
213
214 /* Handle the fallthrough path */
215 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700216 orig_block->fall_through = bottom_block->id;
217 bottom_block->predecessors->Insert(orig_block->id);
218 if (bottom_block->fall_through != NullBasicBlockId) {
219 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
220 bb_fall_through->predecessors->Delete(orig_block->id);
221 bb_fall_through->predecessors->Insert(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800222 }
223
224 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700225 if (orig_block->successor_block_list_type != kNotUsed) {
226 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
227 bottom_block->successor_blocks = orig_block->successor_blocks;
228 orig_block->successor_block_list_type = kNotUsed;
Niranjan Kumar989367a2014-06-12 12:15:48 -0700229 orig_block->successor_blocks = nullptr;
buzbee0d829482013-10-11 15:24:55 -0700230 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bottom_block->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -0800231 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700232 SuccessorBlockInfo* successor_block_info = iterator.Next();
Niranjan Kumar989367a2014-06-12 12:15:48 -0700233 if (successor_block_info == nullptr) break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700234 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700235 if (bb != nullptr) {
236 bb->predecessors->Delete(orig_block->id);
237 bb->predecessors->Insert(bottom_block->id);
238 }
buzbee311ca162013-02-28 15:56:43 -0800239 }
240 }
241
buzbee0d829482013-10-11 15:24:55 -0700242 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700243 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800244
buzbee311ca162013-02-28 15:56:43 -0800245 /*
246 * Update the immediate predecessor block pointer so that outgoing edges
247 * can be applied to the proper block.
248 */
249 if (immed_pred_block_p) {
250 DCHECK_EQ(*immed_pred_block_p, orig_block);
251 *immed_pred_block_p = bottom_block;
252 }
buzbeeb48819d2013-09-14 16:15:25 -0700253
254 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000255 DCHECK(insn != nullptr);
256 DCHECK(insn != orig_block->first_mir_insn);
257 DCHECK(insn == bottom_block->first_mir_insn);
258 DCHECK_EQ(insn->offset, bottom_block->start_offset);
259 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700260 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Marko4376c872014-01-23 12:39:29 +0000261 DCHECK_EQ(dex_pc_to_block_map_.Get(insn->offset), orig_block->id);
262 MIR* p = insn;
263 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
264 while (p != bottom_block->last_mir_insn) {
265 p = p->next;
266 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700267 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700268 int opcode = p->dalvikInsn.opcode;
269 /*
270 * Some messiness here to ensure that we only enter real opcodes and only the
271 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000272 * CHECK and work portions. Since the 2nd half of a split operation is always
273 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700274 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700275 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Vladimir Marko4376c872014-01-23 12:39:29 +0000276 DCHECK_EQ(dex_pc_to_block_map_.Get(p->offset), orig_block->id);
buzbeeb48819d2013-09-14 16:15:25 -0700277 dex_pc_to_block_map_.Put(p->offset, bottom_block->id);
278 }
buzbeeb48819d2013-09-14 16:15:25 -0700279 }
280
buzbee311ca162013-02-28 15:56:43 -0800281 return bottom_block;
282}
283
284/*
285 * Given a code offset, find out the block that starts with it. If the offset
286 * is in the middle of an existing block, split it into two. If immed_pred_block_p
287 * is not non-null and is the block being split, update *immed_pred_block_p to
288 * point to the bottom block so that outgoing edges can be set up properly
289 * (by the caller)
290 * Utilizes a map for fast lookup of the typical cases.
291 */
buzbee0d829482013-10-11 15:24:55 -0700292BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool split, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700293 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700294 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
buzbee311ca162013-02-28 15:56:43 -0800295 return NULL;
296 }
buzbeeb48819d2013-09-14 16:15:25 -0700297
298 int block_id = dex_pc_to_block_map_.Get(code_offset);
299 BasicBlock* bb = (block_id == 0) ? NULL : block_list_.Get(block_id);
300
301 if ((bb != NULL) && (bb->start_offset == code_offset)) {
302 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700303 return bb;
304 }
buzbee311ca162013-02-28 15:56:43 -0800305
buzbeeb48819d2013-09-14 16:15:25 -0700306 // No direct hit.
307 if (!create) {
308 return NULL;
buzbee311ca162013-02-28 15:56:43 -0800309 }
310
buzbeeb48819d2013-09-14 16:15:25 -0700311 if (bb != NULL) {
312 // The target exists somewhere in an existing block.
313 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : NULL);
314 }
315
316 // Create a new block.
buzbee862a7602013-04-05 10:58:54 -0700317 bb = NewMemBB(kDalvikByteCode, num_blocks_++);
318 block_list_.Insert(bb);
buzbee311ca162013-02-28 15:56:43 -0800319 bb->start_offset = code_offset;
buzbeeb48819d2013-09-14 16:15:25 -0700320 dex_pc_to_block_map_.Put(bb->start_offset, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800321 return bb;
322}
323
buzbeeb48819d2013-09-14 16:15:25 -0700324
buzbee311ca162013-02-28 15:56:43 -0800325/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700326void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800327 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700328 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800329
330 if (tries_size == 0) {
331 return;
332 }
333
334 for (int i = 0; i < tries_size; i++) {
335 const DexFile::TryItem* pTry =
336 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700337 DexOffset start_offset = pTry->start_addr_;
338 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800339 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700340 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800341 }
342 }
343
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700344 // Iterate over each of the handlers to enqueue the empty Catch blocks.
buzbee311ca162013-02-28 15:56:43 -0800345 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
346 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
347 for (uint32_t idx = 0; idx < handlers_size; idx++) {
348 CatchHandlerIterator iterator(handlers_ptr);
349 for (; iterator.HasNext(); iterator.Next()) {
350 uint32_t address = iterator.GetHandlerAddress();
351 FindBlock(address, false /* split */, true /*create*/,
352 /* immed_pred_block_p */ NULL);
353 }
354 handlers_ptr = iterator.EndDataPointer();
355 }
356}
357
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100358bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
359 NarrowDexOffset catch_offset) {
360 // Catches for monitor-exit during stack unwinding have the pattern
361 // move-exception (move)* (goto)? monitor-exit throw
362 // In the currently generated dex bytecode we see these catching a bytecode range including
363 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
364 // it's the case for a given monitor-exit and catch block so that we can ignore it.
365 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
366 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
367 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700368 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100369 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
370 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700371 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100372 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
373 if (check_insn->VRegA_11x() == monitor_reg) {
374 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
375 return false;
376 }
377 check_insn = check_insn->Next();
378 while (true) {
379 int dest = -1;
380 bool wide = false;
381 switch (check_insn->Opcode()) {
382 case Instruction::MOVE_WIDE:
383 wide = true;
384 // Intentional fall-through.
385 case Instruction::MOVE_OBJECT:
386 case Instruction::MOVE:
387 dest = check_insn->VRegA_12x();
388 break;
389
390 case Instruction::MOVE_WIDE_FROM16:
391 wide = true;
392 // Intentional fall-through.
393 case Instruction::MOVE_OBJECT_FROM16:
394 case Instruction::MOVE_FROM16:
395 dest = check_insn->VRegA_22x();
396 break;
397
398 case Instruction::MOVE_WIDE_16:
399 wide = true;
400 // Intentional fall-through.
401 case Instruction::MOVE_OBJECT_16:
402 case Instruction::MOVE_16:
403 dest = check_insn->VRegA_32x();
404 break;
405
406 case Instruction::GOTO:
407 case Instruction::GOTO_16:
408 case Instruction::GOTO_32:
409 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
410 // Intentional fall-through.
411 default:
412 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
413 check_insn->VRegA_11x() == monitor_reg;
414 }
415
416 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
417 return false;
418 }
419
420 check_insn = check_insn->Next();
421 }
422}
423
buzbee311ca162013-02-28 15:56:43 -0800424/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700425BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
426 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700427 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700428 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800429 switch (insn->dalvikInsn.opcode) {
430 case Instruction::GOTO:
431 case Instruction::GOTO_16:
432 case Instruction::GOTO_32:
433 target += insn->dalvikInsn.vA;
434 break;
435 case Instruction::IF_EQ:
436 case Instruction::IF_NE:
437 case Instruction::IF_LT:
438 case Instruction::IF_GE:
439 case Instruction::IF_GT:
440 case Instruction::IF_LE:
441 cur_block->conditional_branch = true;
442 target += insn->dalvikInsn.vC;
443 break;
444 case Instruction::IF_EQZ:
445 case Instruction::IF_NEZ:
446 case Instruction::IF_LTZ:
447 case Instruction::IF_GEZ:
448 case Instruction::IF_GTZ:
449 case Instruction::IF_LEZ:
450 cur_block->conditional_branch = true;
451 target += insn->dalvikInsn.vB;
452 break;
453 default:
454 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
455 }
buzbeeb48819d2013-09-14 16:15:25 -0700456 CountBranch(target);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700457 BasicBlock* taken_block = FindBlock(target, /* split */ true, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800458 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700459 cur_block->taken = taken_block->id;
460 taken_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800461
462 /* Always terminate the current block for conditional branches */
463 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700464 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800465 /*
466 * If the method is processed
467 * in sequential order from the
468 * beginning, we don't need to
469 * specify split for continue
470 * blocks. However, this
471 * routine can be called by
472 * compileLoop, which starts
473 * parsing the method from an
474 * arbitrary address in the
475 * method body.
476 */
477 true,
478 /* create */
479 true,
480 /* immed_pred_block_p */
481 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700482 cur_block->fall_through = fallthrough_block->id;
483 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800484 } else if (code_ptr < code_end) {
buzbee27247762013-07-28 12:03:58 -0700485 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800486 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800487 }
488 return cur_block;
489}
490
491/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800492BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
493 int width, int flags) {
buzbee311ca162013-02-28 15:56:43 -0800494 const uint16_t* switch_data =
495 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
496 int size;
497 const int* keyTable;
498 const int* target_table;
499 int i;
500 int first_key;
501
502 /*
503 * Packed switch data format:
504 * ushort ident = 0x0100 magic value
505 * ushort size number of entries in the table
506 * int first_key first (and lowest) switch case value
507 * int targets[size] branch targets, relative to switch opcode
508 *
509 * Total size is (4+size*2) 16-bit code units.
510 */
511 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
512 DCHECK_EQ(static_cast<int>(switch_data[0]),
513 static_cast<int>(Instruction::kPackedSwitchSignature));
514 size = switch_data[1];
515 first_key = switch_data[2] | (switch_data[3] << 16);
516 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700517 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800518 /*
519 * Sparse switch data format:
520 * ushort ident = 0x0200 magic value
521 * ushort size number of entries in the table; > 0
522 * int keys[size] keys, sorted low-to-high; 32-bit aligned
523 * int targets[size] branch targets, relative to switch opcode
524 *
525 * Total size is (2+size*4) 16-bit code units.
526 */
527 } else {
528 DCHECK_EQ(static_cast<int>(switch_data[0]),
529 static_cast<int>(Instruction::kSparseSwitchSignature));
530 size = switch_data[1];
531 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
532 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700533 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800534 }
535
buzbee0d829482013-10-11 15:24:55 -0700536 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800537 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700538 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800539 }
buzbee0d829482013-10-11 15:24:55 -0700540 cur_block->successor_block_list_type =
541 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
542 cur_block->successor_blocks =
Brian Carlstromdf629502013-07-17 22:39:56 -0700543 new (arena_) GrowableArray<SuccessorBlockInfo*>(arena_, size, kGrowableArraySuccessorBlocks);
buzbee311ca162013-02-28 15:56:43 -0800544
545 for (i = 0; i < size; i++) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700546 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* split */ true,
buzbee311ca162013-02-28 15:56:43 -0800547 /* create */ true, /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700548 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700549 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000550 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700551 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800552 successor_block_info->key =
553 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
554 first_key + i : keyTable[i];
buzbee0d829482013-10-11 15:24:55 -0700555 cur_block->successor_blocks->Insert(successor_block_info);
556 case_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800557 }
558
559 /* Fall-through case */
Brian Carlstromdf629502013-07-17 22:39:56 -0700560 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* split */ false,
561 /* create */ true, /* immed_pred_block_p */ NULL);
buzbee0d829482013-10-11 15:24:55 -0700562 cur_block->fall_through = fallthrough_block->id;
563 fallthrough_block->predecessors->Insert(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800564 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800565}
566
567/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700568BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
569 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700570 const uint16_t* code_ptr, const uint16_t* code_end) {
buzbee862a7602013-04-05 10:58:54 -0700571 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800572 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
573 bool build_all_edges =
574 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
buzbee311ca162013-02-28 15:56:43 -0800575
576 /* In try block */
577 if (in_try_block) {
578 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
579
buzbee0d829482013-10-11 15:24:55 -0700580 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800581 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
582 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700583 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800584 }
585
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700586 for (; iterator.HasNext(); iterator.Next()) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700587 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* split*/,
buzbee311ca162013-02-28 15:56:43 -0800588 false /* creat */, NULL /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100589 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
590 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
591 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
592 continue;
593 }
594 if (cur_block->successor_block_list_type == kNotUsed) {
595 cur_block->successor_block_list_type = kCatch;
596 cur_block->successor_blocks = new (arena_) GrowableArray<SuccessorBlockInfo*>(
597 arena_, 2, kGrowableArraySuccessorBlocks);
598 }
buzbee311ca162013-02-28 15:56:43 -0800599 catch_block->catch_entry = true;
600 if (kIsDebugBuild) {
601 catches_.insert(catch_block->start_offset);
602 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700603 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000604 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700605 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800606 successor_block_info->key = iterator.GetHandlerTypeIndex();
buzbee0d829482013-10-11 15:24:55 -0700607 cur_block->successor_blocks->Insert(successor_block_info);
608 catch_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800609 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100610 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
611 }
612 if (!in_try_block && build_all_edges) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700613 BasicBlock* eh_block = NewMemBB(kExceptionHandling, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700614 cur_block->taken = eh_block->id;
buzbee862a7602013-04-05 10:58:54 -0700615 block_list_.Insert(eh_block);
buzbee311ca162013-02-28 15:56:43 -0800616 eh_block->start_offset = cur_offset;
buzbee0d829482013-10-11 15:24:55 -0700617 eh_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800618 }
619
buzbee17189ac2013-11-08 11:07:02 -0800620 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800621 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700622 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700623 // Force creation of new block following THROW via side-effect.
buzbee311ca162013-02-28 15:56:43 -0800624 FindBlock(cur_offset + width, /* split */ false, /* create */ true,
625 /* immed_pred_block_p */ NULL);
626 }
627 if (!in_try_block) {
628 // Don't split a THROW that can't rethrow - we're done.
629 return cur_block;
630 }
631 }
632
buzbee17189ac2013-11-08 11:07:02 -0800633 if (!build_all_edges) {
634 /*
635 * Even though there is an exception edge here, control cannot return to this
636 * method. Thus, for the purposes of dataflow analysis and optimization, we can
637 * ignore the edge. Doing this reduces compile time, and increases the scope
638 * of the basic-block level optimization pass.
639 */
640 return cur_block;
641 }
642
buzbee311ca162013-02-28 15:56:43 -0800643 /*
644 * Split the potentially-throwing instruction into two parts.
645 * The first half will be a pseudo-op that captures the exception
646 * edges and terminates the basic block. It always falls through.
647 * Then, create a new basic block that begins with the throwing instruction
648 * (minus exceptions). Note: this new basic block must NOT be entered into
649 * the block_map. If the potentially-throwing instruction is the target of a
650 * future branch, we need to find the check psuedo half. The new
651 * basic block containing the work portion of the instruction should
652 * only be entered via fallthrough from the block containing the
653 * pseudo exception edge MIR. Note also that this new block is
654 * not automatically terminated after the work portion, and may
655 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700656 *
657 * Note also that the dex_pc_to_block_map_ entry for the potentially
658 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800659 */
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700660 BasicBlock* new_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700661 block_list_.Insert(new_block);
buzbee311ca162013-02-28 15:56:43 -0800662 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700663 cur_block->fall_through = new_block->id;
664 new_block->predecessors->Insert(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700665 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800666 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700667 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700668 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800669 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700670 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800671 return new_block;
672}
673
674/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
675void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700676 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700677 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800678 current_code_item_ = code_item;
679 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
680 current_method_ = m_units_.size();
681 current_offset_ = 0;
682 // TODO: will need to snapshot stack image and use that as the mir context identification.
683 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000684 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
685 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800686 const uint16_t* code_ptr = current_code_item_->insns_;
687 const uint16_t* code_end =
688 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
689
690 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700691 // TUNING: use better estimate of basic blocks for following resize.
buzbee862a7602013-04-05 10:58:54 -0700692 block_list_.Resize(block_list_.Size() + current_code_item_->insns_size_in_code_units_);
buzbeeb48819d2013-09-14 16:15:25 -0700693 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 -0700694
buzbee311ca162013-02-28 15:56:43 -0800695 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700696 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
697 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800698
699 // If this is the first method, set up default entry and exit blocks.
700 if (current_method_ == 0) {
701 DCHECK(entry_block_ == NULL);
702 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700703 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700704 // Use id 0 to represent a null block.
705 BasicBlock* null_block = NewMemBB(kNullBlock, num_blocks_++);
706 DCHECK_EQ(null_block->id, NullBasicBlockId);
707 null_block->hidden = true;
708 block_list_.Insert(null_block);
buzbee862a7602013-04-05 10:58:54 -0700709 entry_block_ = NewMemBB(kEntryBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700710 block_list_.Insert(entry_block_);
buzbee0d829482013-10-11 15:24:55 -0700711 exit_block_ = NewMemBB(kExitBlock, num_blocks_++);
buzbee862a7602013-04-05 10:58:54 -0700712 block_list_.Insert(exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800713 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
714 cu_->dex_file = &dex_file;
715 cu_->class_def_idx = class_def_idx;
716 cu_->method_idx = method_idx;
717 cu_->access_flags = access_flags;
718 cu_->invoke_type = invoke_type;
719 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800720 cu_->code_item = current_code_item_;
721 } else {
722 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
723 /*
724 * Will need to manage storage for ins & outs, push prevous state and update
725 * insert point.
726 */
727 }
728
729 /* Current block to record parsed instructions */
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700730 BasicBlock* cur_block = NewMemBB(kDalvikByteCode, num_blocks_++);
buzbee0d829482013-10-11 15:24:55 -0700731 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800732 cur_block->start_offset = current_offset_;
buzbee862a7602013-04-05 10:58:54 -0700733 block_list_.Insert(cur_block);
buzbee0d829482013-10-11 15:24:55 -0700734 // TODO: for inlining support, insert at the insert point rather than entry block.
735 entry_block_->fall_through = cur_block->id;
736 cur_block->predecessors->Insert(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800737
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000738 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800739 ProcessTryCatchBlocks();
740
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000741 uint64_t merged_df_flags = 0u;
742
buzbee311ca162013-02-28 15:56:43 -0800743 /* Parse all instructions and put them into containing basic blocks */
744 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700745 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800746 insn->offset = current_offset_;
747 insn->m_unit_index = current_method_;
748 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800749 Instruction::Code opcode = insn->dalvikInsn.opcode;
750 if (opcode_count_ != NULL) {
751 opcode_count_[static_cast<int>(opcode)]++;
752 }
753
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700754 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800755 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800756
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700757 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000758 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800759
760 if (df_flags & DF_HAS_DEFS) {
761 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
762 }
763
buzbee1da1e2f2013-11-15 13:37:01 -0800764 if (df_flags & DF_LVN) {
765 cur_block->use_lvn = true; // Run local value numbering on this basic block.
766 }
767
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700768 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700769 if (opcode == Instruction::NOP) {
770 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
771 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
772 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
773 uint16_t following_raw_instruction = code_ptr[1];
774 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
775 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
776 (following_raw_instruction == Instruction::kArrayDataSignature)) {
777 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
778 }
779 }
780 if (width == 1) {
781 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700782 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700783 } else {
buzbee0d829482013-10-11 15:24:55 -0700784 DCHECK(cur_block->fall_through == NullBasicBlockId);
785 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700786 // Unreachable instruction, mark for no continuation.
787 flags &= ~Instruction::kContinue;
788 }
789 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700790 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700791 }
792
buzbeeb48819d2013-09-14 16:15:25 -0700793 // Associate the starting dex_pc for this opcode with its containing basic block.
794 dex_pc_to_block_map_.Put(insn->offset, cur_block->id);
795
buzbee27247762013-07-28 12:03:58 -0700796 code_ptr += width;
797
buzbee311ca162013-02-28 15:56:43 -0800798 if (flags & Instruction::kBranch) {
799 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
800 width, flags, code_ptr, code_end);
801 } else if (flags & Instruction::kReturn) {
802 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700803 cur_block->fall_through = exit_block_->id;
804 exit_block_->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800805 /*
806 * Terminate the current block if there are instructions
807 * afterwards.
808 */
809 if (code_ptr < code_end) {
810 /*
811 * Create a fallthrough block for real instructions
812 * (incl. NOP).
813 */
buzbee27247762013-07-28 12:03:58 -0700814 FindBlock(current_offset_ + width, /* split */ false, /* create */ true,
815 /* immed_pred_block_p */ NULL);
buzbee311ca162013-02-28 15:56:43 -0800816 }
817 } else if (flags & Instruction::kThrow) {
818 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
819 code_ptr, code_end);
820 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800821 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800822 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700823 if (verify_flags & Instruction::kVerifyVarArgRange ||
824 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800825 /*
826 * The Quick backend's runtime model includes a gap between a method's
827 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
828 * which spans the gap is somewhat complicated, and should not happen
829 * in normal usage of dx. Punt to the interpreter.
830 */
831 int first_reg_in_range = insn->dalvikInsn.vC;
832 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
833 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
834 punt_to_interpreter_ = true;
835 }
836 }
buzbee311ca162013-02-28 15:56:43 -0800837 current_offset_ += width;
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700838 BasicBlock* next_block = FindBlock(current_offset_, /* split */ false, /* create */
buzbee311ca162013-02-28 15:56:43 -0800839 false, /* immed_pred_block_p */ NULL);
840 if (next_block) {
841 /*
842 * The next instruction could be the target of a previously parsed
843 * forward branch so a block is already created. If the current
844 * instruction is not an unconditional branch, connect them through
845 * the fall-through link.
846 */
buzbee0d829482013-10-11 15:24:55 -0700847 DCHECK(cur_block->fall_through == NullBasicBlockId ||
848 GetBasicBlock(cur_block->fall_through) == next_block ||
849 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800850
buzbee0d829482013-10-11 15:24:55 -0700851 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
852 cur_block->fall_through = next_block->id;
853 next_block->predecessors->Insert(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800854 }
855 cur_block = next_block;
856 }
857 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000858 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000859
buzbee311ca162013-02-28 15:56:43 -0800860 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
861 DumpCFG("/sdcard/1_post_parse_cfg/", true);
862 }
863
864 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700865 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800866 }
867}
868
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700869void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800870 DCHECK(opcode_count_ != NULL);
871 LOG(INFO) << "Opcode Count";
872 for (int i = 0; i < kNumPackedOpcodes; i++) {
873 if (opcode_count_[i] != 0) {
874 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
875 << " " << opcode_count_[i];
876 }
877 }
878}
879
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700880uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
881 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
882 return oat_data_flow_attributes_[opcode];
883}
884
885uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
886 DCHECK(mir != nullptr);
887 Instruction::Code opcode = mir->dalvikInsn.opcode;
888 return GetDataFlowAttributes(opcode);
889}
890
buzbee311ca162013-02-28 15:56:43 -0800891// TODO: use a configurable base prefix, and adjust callers to supply pass name.
892/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800893void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800894 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700895 static AtomicInteger cnt(0);
896
897 // Increment counter to get a unique file number.
898 cnt++;
899
buzbee311ca162013-02-28 15:56:43 -0800900 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
901 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700902 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800903 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700904 suffix == nullptr ? "" : suffix,
905 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800906 file = fopen(fname.c_str(), "w");
907 if (file == NULL) {
908 return;
909 }
910 fprintf(file, "digraph G {\n");
911
912 fprintf(file, " rankdir=TB\n");
913
914 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
915 int idx;
916
917 for (idx = 0; idx < num_blocks; idx++) {
buzbee862a7602013-04-05 10:58:54 -0700918 int block_idx = all_blocks ? idx : dfs_order_->Get(idx);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700919 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700920 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800921 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700922 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800923 if (bb->block_type == kEntryBlock) {
924 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
925 } else if (bb->block_type == kExitBlock) {
926 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
927 } else if (bb->block_type == kDalvikByteCode) {
928 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
929 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700930 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800931 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
932 bb->first_mir_insn ? " | " : " ");
933 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
934 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700935 fprintf(file, " {%04x %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400936 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700937 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
938 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400939 extended_mir_op_names_[opcode - kMirOpFirst],
940 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
941 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700942 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700943 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700944 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
945 (mir->optimization_flags & MIR_IGNORE_CLINIT_CHECK) != 0 ? " no_clinit" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400946 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800947 }
948 fprintf(file, " }\"];\n\n");
949 } else if (bb->block_type == kExceptionHandling) {
950 char block_name[BLOCK_NAME_LEN];
951
952 GetBlockName(bb, block_name);
953 fprintf(file, " %s [shape=invhouse];\n", block_name);
954 }
955
956 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
957
buzbee0d829482013-10-11 15:24:55 -0700958 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800959 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700960 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800961 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
962 block_name1, block_name2);
963 }
buzbee0d829482013-10-11 15:24:55 -0700964 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800965 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700966 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800967 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
968 }
969
buzbee0d829482013-10-11 15:24:55 -0700970 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800971 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
972 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700973 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
974 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(bb->successor_blocks);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700975 SuccessorBlockInfo* successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800976
977 int succ_id = 0;
978 while (true) {
979 if (successor_block_info == NULL) break;
980
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700981 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee862a7602013-04-05 10:58:54 -0700982 SuccessorBlockInfo *next_successor_block_info = iterator.Next();
buzbee311ca162013-02-28 15:56:43 -0800983
984 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
985 succ_id++,
986 successor_block_info->key,
987 dest_block->start_offset,
988 (next_successor_block_info != NULL) ? " | " : " ");
989
990 successor_block_info = next_successor_block_info;
991 }
992 fprintf(file, " }\"];\n\n");
993
994 GetBlockName(bb, block_name1);
995 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
996 block_name1, bb->start_offset, bb->id);
997
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700998 // Link the successor pseudo-block with all of its potential targets.
999 GrowableArray<SuccessorBlockInfo*>::Iterator iter(bb->successor_blocks);
buzbee311ca162013-02-28 15:56:43 -08001000
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001001 succ_id = 0;
1002 while (true) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001003 SuccessorBlockInfo* successor_block_info = iter.Next();
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001004 if (successor_block_info == NULL) break;
buzbee311ca162013-02-28 15:56:43 -08001005
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001006 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001007
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001008 GetBlockName(dest_block, block_name2);
1009 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1010 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001011 }
1012 }
1013 fprintf(file, "\n");
1014
1015 if (cu_->verbose) {
1016 /* Display the dominator tree */
1017 GetBlockName(bb, block_name1);
1018 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1019 block_name1, block_name1);
1020 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001021 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001022 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1023 }
1024 }
1025 }
1026 fprintf(file, "}\n");
1027 fclose(file);
1028}
1029
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001030/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001031void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001032 // Insert it after the last MIR.
1033 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001034}
1035
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001036void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1037 // Insert it after the last MIR.
1038 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1039}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001040
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001041void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1042 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1043 MIR* new_mir = *it;
1044
1045 // Add a copy of each MIR.
1046 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1047 }
buzbee1fd33462013-03-25 13:40:45 -07001048}
1049
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001050/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001051void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001052 InsertMIRListAfter(current_mir, new_mir, new_mir);
1053}
buzbee1fd33462013-03-25 13:40:45 -07001054
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001055void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1056 // If no MIR, we are done.
1057 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1058 return;
buzbee1fd33462013-03-25 13:40:45 -07001059 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001060
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001061 // If insert_after is null, assume BB is empty.
1062 if (insert_after == nullptr) {
1063 first_mir_insn = first_list_mir;
1064 last_mir_insn = last_list_mir;
1065 last_list_mir->next = nullptr;
1066 } else {
1067 MIR* after_list = insert_after->next;
1068 insert_after->next = first_list_mir;
1069 last_list_mir->next = after_list;
1070 if (after_list == nullptr) {
1071 last_mir_insn = last_list_mir;
1072 }
1073 }
1074
1075 // Set this BB to be the basic block of the MIRs.
1076 MIR* last = last_list_mir->next;
1077 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1078 mir->bb = id;
1079 }
1080}
1081
1082/* Insert an MIR instruction to the head of a basic block. */
1083void BasicBlock::PrependMIR(MIR* mir) {
1084 InsertMIRListBefore(first_mir_insn, mir, mir);
1085}
1086
1087void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1088 // Insert it before the first MIR.
1089 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1090}
1091
1092void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1093 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1094 MIR* mir = *it;
1095
1096 InsertMIRListBefore(first_mir_insn, mir, mir);
1097 }
1098}
1099
1100/* Insert a MIR instruction before the specified MIR. */
1101void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1102 // Insert as a single element list.
1103 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001104}
1105
1106MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1107 MIR* current = first_mir_insn;
1108
1109 while (current != nullptr) {
1110 MIR* next = current->next;
1111
1112 if (next == mir) {
1113 return current;
1114 }
1115
1116 current = next;
1117 }
1118
1119 return nullptr;
1120}
1121
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001122void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1123 // If no MIR, we are done.
1124 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1125 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001126 }
1127
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001128 // If insert_before is null, assume BB is empty.
1129 if (insert_before == nullptr) {
1130 first_mir_insn = first_list_mir;
1131 last_mir_insn = last_list_mir;
1132 last_list_mir->next = nullptr;
1133 } else {
1134 if (first_mir_insn == insert_before) {
1135 last_list_mir->next = first_mir_insn;
1136 first_mir_insn = first_list_mir;
1137 } else {
1138 // Find the preceding MIR.
1139 MIR* before_list = FindPreviousMIR(insert_before);
1140 DCHECK(before_list != nullptr);
1141 before_list->next = first_list_mir;
1142 last_list_mir->next = insert_before;
1143 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001144 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001145
1146 // Set this BB to be the basic block of the MIRs.
1147 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1148 mir->bb = id;
1149 }
1150}
1151
1152bool BasicBlock::RemoveMIR(MIR* mir) {
1153 // Remove as a single element list.
1154 return RemoveMIRList(mir, mir);
1155}
1156
1157bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1158 if (first_list_mir == nullptr) {
1159 return false;
1160 }
1161
1162 // Try to find the MIR.
1163 MIR* before_list = nullptr;
1164 MIR* after_list = nullptr;
1165
1166 // If we are removing from the beginning of the MIR list.
1167 if (first_mir_insn == first_list_mir) {
1168 before_list = nullptr;
1169 } else {
1170 before_list = FindPreviousMIR(first_list_mir);
1171 if (before_list == nullptr) {
1172 // We did not find the mir.
1173 return false;
1174 }
1175 }
1176
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001177 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001178 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001179 mir->bb = NullBasicBlockId;
1180 }
1181
1182 after_list = last_list_mir->next;
1183
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001184 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001185 if (before_list == nullptr) {
1186 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001187 } else {
1188 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001189 }
1190
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001191 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001192 if (after_list == nullptr) {
1193 last_mir_insn = before_list;
1194 }
1195
1196 return true;
buzbee1fd33462013-03-25 13:40:45 -07001197}
1198
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001199MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001200 MIR* next_mir = nullptr;
1201
1202 if (current != nullptr) {
1203 next_mir = current->next;
1204 }
1205
1206 if (next_mir == nullptr) {
1207 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001208 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1209 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001210 }
1211 }
1212
1213 return next_mir;
1214}
1215
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001216static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1217 DCHECK(decoded_mir != nullptr);
1218 OpSize type = static_cast<OpSize>(type_size >> 16);
1219 uint16_t vect_size = (type_size & 0xFFFF);
1220
1221 // Now print the type and vector size.
1222 std::stringstream ss;
1223 ss << " (type:";
1224 ss << type;
1225 ss << " vectsize:";
1226 ss << vect_size;
1227 ss << ")";
1228
1229 decoded_mir->append(ss.str());
1230}
1231
1232void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1233 DCHECK(decoded_mir != nullptr);
1234 int opcode = mir->dalvikInsn.opcode;
1235 SSARepresentation* ssa_rep = mir->ssa_rep;
1236 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1237 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1238
1239 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1240
1241 switch (opcode) {
1242 case kMirOpPhi: {
1243 if (defs > 0 && uses > 0) {
1244 BasicBlockId* incoming = mir->meta.phi_incoming;
1245 decoded_mir->append(StringPrintf(" %s = (%s",
1246 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1247 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1248 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1249 for (int i = 1; i < uses; i++) {
1250 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1251 }
1252 decoded_mir->append(")");
1253 }
1254 break;
1255 }
1256 case kMirOpCopy:
1257 if (ssa_rep != nullptr) {
1258 decoded_mir->append(" ");
1259 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1260 if (defs > 1) {
1261 decoded_mir->append(", ");
1262 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1263 }
1264 decoded_mir->append(" = ");
1265 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1266 if (uses > 1) {
1267 decoded_mir->append(", ");
1268 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1269 }
1270 } else {
1271 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1272 }
1273 break;
1274 case kMirOpFusedCmplFloat:
1275 case kMirOpFusedCmpgFloat:
1276 case kMirOpFusedCmplDouble:
1277 case kMirOpFusedCmpgDouble:
1278 case kMirOpFusedCmpLong:
1279 if (ssa_rep != nullptr) {
1280 decoded_mir->append(" ");
1281 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1282 for (int i = 1; i < uses; i++) {
1283 decoded_mir->append(", ");
1284 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1285 }
1286 } else {
1287 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1288 }
1289 break;
1290 case kMirOpMoveVector:
1291 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1292 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1293 break;
1294 case kMirOpPackedAddition:
1295 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1296 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1297 break;
1298 case kMirOpPackedMultiply:
1299 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1300 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1301 break;
1302 case kMirOpPackedSubtract:
1303 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1304 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1305 break;
1306 case kMirOpPackedAnd:
1307 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1308 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1309 break;
1310 case kMirOpPackedOr:
1311 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1312 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1313 break;
1314 case kMirOpPackedXor:
1315 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1316 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1317 break;
1318 case kMirOpPackedShiftLeft:
1319 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1320 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1321 break;
1322 case kMirOpPackedUnsignedShiftRight:
1323 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1324 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1325 break;
1326 case kMirOpPackedSignedShiftRight:
1327 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1328 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1329 break;
1330 case kMirOpConstVector:
1331 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1332 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1333 break;
1334 case kMirOpPackedSet:
1335 if (ssa_rep != nullptr) {
1336 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1337 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1338 if (uses > 1) {
1339 decoded_mir->append(", ");
1340 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1341 }
1342 } else {
1343 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1344 }
1345 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1346 break;
1347 case kMirOpPackedAddReduce:
1348 if (ssa_rep != nullptr) {
1349 decoded_mir->append(" ");
1350 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1351 if (defs > 1) {
1352 decoded_mir->append(", ");
1353 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1354 }
1355 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1356 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1357 if (uses > 1) {
1358 decoded_mir->append(", ");
1359 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1360 }
1361 } else {
1362 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1363 }
1364 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1365 break;
1366 case kMirOpPackedReduce:
1367 if (ssa_rep != nullptr) {
1368 decoded_mir->append(" ");
1369 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1370 if (defs > 1) {
1371 decoded_mir->append(", ");
1372 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1373 }
1374 decoded_mir->append(StringPrintf(" = vect%d", mir->dalvikInsn.vB));
1375 } else {
1376 decoded_mir->append(StringPrintf(" v%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1377 }
1378 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1379 break;
1380 case kMirOpReserveVectorRegisters:
1381 case kMirOpReturnVectorRegisters:
1382 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1383 break;
1384 case kMirOpMemBarrier: {
1385 decoded_mir->append(" type:");
1386 std::stringstream ss;
1387 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1388 decoded_mir->append(ss.str());
1389 break;
1390 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001391 case kMirOpPackedArrayGet:
1392 case kMirOpPackedArrayPut:
1393 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1394 if (ssa_rep != nullptr) {
1395 decoded_mir->append(StringPrintf(", %s[%s]",
1396 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1397 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1398 } else {
1399 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1400 }
1401 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1402 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001403 default:
1404 break;
1405 }
1406}
1407
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001408char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001409 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001410 std::string str;
1411 int flags = 0;
1412 int opcode = insn.opcode;
1413 char* ret;
1414 bool nop = false;
1415 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001416 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001417
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001418 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001419 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1420 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1421 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001422 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001423 insn = mir->meta.throw_insn->dalvikInsn;
1424 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001425 opcode = insn.opcode;
1426 } else if (opcode == kMirOpNop) {
1427 str.append("[");
buzbee0d829482013-10-11 15:24:55 -07001428 // Recover original opcode.
1429 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1430 opcode = insn.opcode;
buzbee1fd33462013-03-25 13:40:45 -07001431 nop = true;
1432 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001433 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1434 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001435
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001436 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001437 // Note that this does not check the MIR's opcode in all cases. In cases where it
1438 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1439 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001440 } else {
1441 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001442 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001443 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001444
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001445 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001446 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1447 (dalvik_format == Instruction::k3rc));
1448 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001449 str.append(" ");
1450 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1451 if (defs > 1) {
1452 str.append(", ");
1453 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1454 }
buzbee1fd33462013-03-25 13:40:45 -07001455 if (uses != 0) {
1456 str.append(", ");
1457 }
1458 }
1459 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001460 str.append(" ");
1461 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001462 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1463 // For the listing, skip the high sreg.
1464 i++;
1465 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001466 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001467 str.append(",");
1468 }
1469 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001470
buzbee1fd33462013-03-25 13:40:45 -07001471 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001472 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001473 case Instruction::k21s:
1474 case Instruction::k31i:
1475 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001476 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001477 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001478 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001479 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001480 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001481 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001482 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001483 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001484 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001485 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001486 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001487 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001488 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001489 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001490 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001491 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001492 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001493 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001494 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001495 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001496
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001497 if ((flags & Instruction::kBranch) != 0) {
1498 // For branches, decode the instructions to print out the branch targets.
1499 int offset = 0;
1500 switch (dalvik_format) {
1501 case Instruction::k21t:
1502 offset = insn.vB;
1503 break;
1504 case Instruction::k22t:
1505 offset = insn.vC;
1506 break;
1507 case Instruction::k10t:
1508 case Instruction::k20t:
1509 case Instruction::k30t:
1510 offset = insn.vA;
1511 break;
1512 default:
1513 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001514 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001515 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001516 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001517 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1518 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001519
1520 if (nop) {
1521 str.append("]--optimized away");
1522 }
buzbee1fd33462013-03-25 13:40:45 -07001523 }
1524 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001525 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001526 strncpy(ret, str.c_str(), length);
1527 return ret;
1528}
1529
1530/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001531void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001532 static const struct { const char before; const char after; } match[] = {
1533 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1534 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1535 };
buzbee1fd33462013-03-25 13:40:45 -07001536 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1537 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1538 }
1539}
1540
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001541std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001542 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1543 // the arena. We should be smarter and just place straight into the arena, or compute the
1544 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001545 int vreg = SRegToVReg(ssa_reg);
1546 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1547 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1548 } else {
1549 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1550 }
buzbee1fd33462013-03-25 13:40:45 -07001551}
1552
1553// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001554std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001555 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001556 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001557 return GetSSAName(ssa_reg);
1558 }
1559 if (IsConst(reg_location_[ssa_reg])) {
1560 if (!singles_only && reg_location_[ssa_reg].wide) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001561 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001562 ConstantValueWide(reg_location_[ssa_reg]));
1563 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001564 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001565 ConstantValue(reg_location_[ssa_reg]));
1566 }
1567 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001568 int vreg = SRegToVReg(ssa_reg);
1569 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1570 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1571 } else {
1572 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1573 }
buzbee1fd33462013-03-25 13:40:45 -07001574 }
1575}
1576
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001577void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001578 switch (bb->block_type) {
1579 case kEntryBlock:
1580 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1581 break;
1582 case kExitBlock:
1583 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1584 break;
1585 case kDalvikByteCode:
1586 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1587 break;
1588 case kExceptionHandling:
1589 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1590 bb->id);
1591 break;
1592 default:
1593 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1594 break;
1595 }
1596}
1597
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001598const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001599 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001600 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1601 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1602}
1603
1604/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001605void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001606 BasicBlock* bb;
1607 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001608 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001609 "Entry Block",
1610 "Code Block",
1611 "Exit Block",
1612 "Exception Handling",
1613 "Catch Block"
1614 };
1615
1616 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001617 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001618 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee862a7602013-04-05 10:58:54 -07001619 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
buzbee1fd33462013-03-25 13:40:45 -07001620
1621 while (true) {
buzbee862a7602013-04-05 10:58:54 -07001622 bb = iterator.Next();
buzbee1fd33462013-03-25 13:40:45 -07001623 if (bb == NULL) break;
1624 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1625 bb->id,
1626 block_type_names[bb->block_type],
1627 bb->start_offset,
1628 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1629 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001630 if (bb->taken != NullBasicBlockId) {
1631 LOG(INFO) << " Taken branch: block " << bb->taken
1632 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001633 }
buzbee0d829482013-10-11 15:24:55 -07001634 if (bb->fall_through != NullBasicBlockId) {
1635 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1636 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001637 }
1638 }
1639}
1640
1641/*
1642 * Build an array of location records for the incoming arguments.
1643 * Note: one location record per word of arguments, with dummy
1644 * high-word loc for wide arguments. Also pull up any following
1645 * MOVE_RESULT and incorporate it into the invoke.
1646 */
1647CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001648 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001649 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001650 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001651 MIR* move_result_mir = FindMoveResult(bb, mir);
1652 if (move_result_mir == NULL) {
1653 info->result.location = kLocInvalid;
1654 } else {
1655 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001656 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1657 }
1658 info->num_arg_words = mir->ssa_rep->num_uses;
1659 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001660 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001661 for (int i = 0; i < info->num_arg_words; i++) {
1662 info->args[i] = GetRawSrc(mir, i);
1663 }
1664 info->opt_flags = mir->optimization_flags;
1665 info->type = type;
1666 info->is_range = is_range;
1667 info->index = mir->dalvikInsn.vB;
1668 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001669 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001670 return info;
1671}
1672
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001673// Allocate a new MIR.
1674MIR* MIRGraph::NewMIR() {
1675 MIR* mir = new (arena_) MIR();
1676 return mir;
1677}
1678
buzbee862a7602013-04-05 10:58:54 -07001679// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001680BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001681 BasicBlock* bb = new (arena_) BasicBlock();
1682
buzbee862a7602013-04-05 10:58:54 -07001683 bb->block_type = block_type;
1684 bb->id = block_id;
1685 // TUNING: better estimate of the exit block predecessors?
buzbee0d829482013-10-11 15:24:55 -07001686 bb->predecessors = new (arena_) GrowableArray<BasicBlockId>(arena_,
Brian Carlstromdf629502013-07-17 22:39:56 -07001687 (block_type == kExitBlock) ? 2048 : 2,
1688 kGrowableArrayPredecessors);
buzbee0d829482013-10-11 15:24:55 -07001689 bb->successor_block_list_type = kNotUsed;
buzbee862a7602013-04-05 10:58:54 -07001690 block_id_map_.Put(block_id, block_id);
1691 return bb;
1692}
buzbee1fd33462013-03-25 13:40:45 -07001693
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001694void MIRGraph::InitializeConstantPropagation() {
1695 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001696 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001697}
1698
1699void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001700 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001701 int num_ssa_regs = GetNumSSARegs();
1702 use_counts_.Resize(num_ssa_regs + 32);
1703 raw_use_counts_.Resize(num_ssa_regs + 32);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001704 // Resize does not actually reset the number of used, so reset before initialization.
1705 use_counts_.Reset();
1706 raw_use_counts_.Reset();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001707 // Initialize list.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001708 for (int i = 0; i < num_ssa_regs; i++) {
1709 use_counts_.Insert(0);
1710 raw_use_counts_.Insert(0);
1711 }
1712}
1713
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001714void MIRGraph::SSATransformationStart() {
1715 DCHECK(temp_scoped_alloc_.get() == nullptr);
1716 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001717 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001718 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1719 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
1720
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -07001721 // Update the maximum number of reachable blocks.
1722 max_num_reachable_blocks_ = num_reachable_blocks_;
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001723}
1724
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001725void MIRGraph::SSATransformationEnd() {
1726 // Verify the dataflow information after the pass.
1727 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1728 VerifyDataflow();
1729 }
1730
1731 temp_bit_vector_size_ = 0u;
1732 temp_bit_vector_ = nullptr;
1733 DCHECK(temp_scoped_alloc_.get() != nullptr);
1734 temp_scoped_alloc_.reset();
1735}
1736
Vladimir Marko55fff042014-07-10 12:42:52 +01001737static BasicBlock* SelectTopologicalSortOrderFallBack(
1738 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1739 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1740 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1741 // No true loop head has been found but there may be true loop heads after the mess we need
1742 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1743 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1744 BasicBlock* fall_back = nullptr;
1745 size_t fall_back_num_reachable = 0u;
1746 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1747 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1748 AllNodesIterator iter(mir_graph);
1749 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1750 if (candidate->hidden || // Hidden, or
1751 candidate->visited || // already processed, or
1752 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1753 (current_loop != nullptr && // outside current loop.
1754 !current_loop->IsBitSet(candidate->id))) {
1755 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001756 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001757 DCHECK(tmp_stack->empty());
1758 tmp_stack->push_back(candidate->id);
1759 candidate_reachable.ClearAllBits();
1760 size_t num_reachable = 0u;
1761 while (!tmp_stack->empty()) {
1762 BasicBlockId current_id = tmp_stack->back();
1763 tmp_stack->pop_back();
1764 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1765 DCHECK(current_bb != nullptr);
1766 ChildBlockIterator child_iter(current_bb, mir_graph);
1767 BasicBlock* child_bb = child_iter.Next();
1768 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1769 DCHECK(!child_bb->hidden);
1770 if (child_bb->visited || // Already processed, or
1771 (current_loop != nullptr && // outside current loop.
1772 !current_loop->IsBitSet(child_bb->id))) {
1773 continue;
1774 }
1775 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1776 candidate_reachable.SetBit(child_bb->id);
1777 tmp_stack->push_back(child_bb->id);
1778 num_reachable += 1u;
1779 }
1780 }
1781 }
1782 if (fall_back_num_reachable < num_reachable) {
1783 fall_back_num_reachable = num_reachable;
1784 fall_back = candidate;
1785 }
1786 }
1787 return fall_back;
1788}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001789
Vladimir Marko55fff042014-07-10 12:42:52 +01001790// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1791static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1792 ArenaBitVector* reachable,
1793 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1794 // NOTE: Loop heads indicated by the "visited" flag.
1795 DCHECK(tmp_stack->empty());
1796 reachable->ClearAllBits();
1797 tmp_stack->push_back(bb_id);
1798 while (!tmp_stack->empty()) {
1799 BasicBlockId current_id = tmp_stack->back();
1800 tmp_stack->pop_back();
1801 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1802 DCHECK(current_bb != nullptr);
1803 GrowableArray<BasicBlockId>::Iterator iter(current_bb->predecessors);
1804 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iter.Next());
1805 for ( ; pred_bb != nullptr; pred_bb = mir_graph->GetBasicBlock(iter.Next())) {
1806 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1807 reachable->SetBit(pred_bb->id);
1808 tmp_stack->push_back(pred_bb->id);
1809 }
1810 }
1811 }
1812}
1813
1814void MIRGraph::ComputeTopologicalSortOrder() {
1815 ScopedArenaAllocator allocator(&cu_->arena_stack);
1816 unsigned int num_blocks = GetNumBlocks();
1817
1818 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1819 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1820 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1821 size_t max_nested_loops = 0u;
1822 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1823 loop_exit_blocks.ClearAllBits();
1824
1825 // Count the number of blocks to process and add the entry block(s).
1826 GrowableArray<BasicBlock*>::Iterator iterator(&block_list_);
1827 unsigned int num_blocks_to_process = 0u;
1828 for (BasicBlock* bb = iterator.Next(); bb != nullptr; bb = iterator.Next()) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001829 if (bb->hidden == true) {
1830 continue;
1831 }
1832
Vladimir Marko55fff042014-07-10 12:42:52 +01001833 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001834
Vladimir Marko55fff042014-07-10 12:42:52 +01001835 if (bb->predecessors->Size() == 0u) {
1836 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001837 q.push(bb);
1838 }
1839 }
1840
Vladimir Marko55fff042014-07-10 12:42:52 +01001841 // Create the topological order if need be.
1842 if (topological_order_ == nullptr) {
1843 topological_order_ = new (arena_) GrowableArray<BasicBlockId>(arena_, num_blocks);
1844 topological_order_loop_ends_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1845 topological_order_indexes_ = new (arena_) GrowableArray<uint16_t>(arena_, num_blocks);
1846 }
1847 topological_order_->Reset();
1848 topological_order_loop_ends_->Reset();
1849 topological_order_indexes_->Reset();
1850 topological_order_loop_ends_->Resize(num_blocks);
1851 topological_order_indexes_->Resize(num_blocks);
1852 for (BasicBlockId i = 0; i != num_blocks; ++i) {
1853 topological_order_loop_ends_->Insert(0u);
1854 topological_order_indexes_->Insert(static_cast<uint16_t>(-1));
1855 }
1856
1857 // Mark all blocks as unvisited.
1858 ClearAllVisitedFlags();
1859
1860 // For loop heads, keep track from which blocks they are reachable not going through other
1861 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1862 // in this set go into the loop body, the other children are jumping over the loop.
1863 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1864 loop_head_reachable_from.resize(num_blocks, nullptr);
1865 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1866 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1867
1868 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001869 BasicBlock* bb = nullptr;
1870 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001871 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001872 // Get top.
1873 bb = q.front();
1874 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001875 if (bb->visited) {
1876 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1877 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1878 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1879 topological_order_loop_ends_->Put(topological_order_indexes_->Get(bb->id), idx);
1880 DCHECK_EQ(loop_head_stack.back(), bb->id);
1881 loop_head_stack.pop_back();
1882 ArenaBitVector* reachable =
1883 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1884 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1885 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1886 q.push(GetBasicBlock(candidate_id));
1887 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1888 // so clearing the bit has no effect on the iterator.
1889 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001890 }
1891 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001892 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001893 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001894 } else {
1895 // Find the new loop head.
1896 AllNodesIterator iter(this);
1897 while (true) {
1898 BasicBlock* candidate = iter.Next();
1899 if (candidate == nullptr) {
1900 // We did not find a true loop head, fall back to a reachable block in any loop.
1901 ArenaBitVector* current_loop =
1902 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1903 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1904 &allocator, &tmp_stack);
1905 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1906 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1907 LOG(INFO) << "Topological sort order: Using fall-back in "
1908 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1909 << " @0x" << std::hex << bb->start_offset
1910 << ", num_blocks = " << std::dec << num_blocks;
1911 }
1912 break;
1913 }
1914 if (candidate->hidden || // Hidden, or
1915 candidate->visited || // already processed, or
1916 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1917 (!loop_head_stack.empty() && // outside current loop.
1918 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1919 continue;
1920 }
1921
1922 GrowableArray<BasicBlockId>::Iterator pred_iter(candidate->predecessors);
1923 BasicBlock* pred_bb = GetBasicBlock(pred_iter.Next());
1924 for ( ; pred_bb != nullptr; pred_bb = GetBasicBlock(pred_iter.Next())) {
1925 if (pred_bb != candidate && !pred_bb->visited &&
1926 !pred_bb->dominators->IsBitSet(candidate->id)) {
1927 break; // Keep non-null pred_bb to indicate failure.
1928 }
1929 }
1930 if (pred_bb == nullptr) {
1931 bb = candidate;
1932 break;
1933 }
1934 }
1935 // Compute blocks from which the loop head is reachable and process those blocks first.
1936 ArenaBitVector* reachable =
1937 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1938 loop_head_reachable_from[bb->id] = reachable;
1939 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1940 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1941 loop_head_stack.push_back(bb->id);
1942 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001943 }
1944
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001945 DCHECK_EQ(bb->hidden, false);
1946 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001947 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001948
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001949 // Now add the basic block.
Vladimir Marko55fff042014-07-10 12:42:52 +01001950 uint16_t idx = static_cast<uint16_t>(topological_order_->Size());
1951 topological_order_indexes_->Put(bb->id, idx);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001952 topological_order_->Insert(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001953
Vladimir Marko55fff042014-07-10 12:42:52 +01001954 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001955 ChildBlockIterator succIter(bb, this);
1956 BasicBlock* successor = succIter.Next();
1957 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001958 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001959 continue;
1960 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001961
Vladimir Marko55fff042014-07-10 12:42:52 +01001962 // One more predecessor was visited.
1963 visited_cnt_values[successor->id] += 1u;
1964 if (visited_cnt_values[successor->id] == successor->predecessors->Size()) {
1965 if (loop_head_stack.empty() ||
1966 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1967 q.push(successor);
1968 } else {
1969 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1970 loop_exit_blocks.SetBit(successor->id);
1971 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001972 }
1973 }
1974 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001975
1976 // Prepare the loop head stack for iteration.
1977 topological_order_loop_head_stack_ =
1978 new (arena_) GrowableArray<std::pair<uint16_t, bool>>(arena_, max_nested_loops);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001979}
1980
1981bool BasicBlock::IsExceptionBlock() const {
1982 if (block_type == kExceptionHandling) {
1983 return true;
1984 }
1985 return false;
1986}
1987
Wei Jin04f4d8a2014-05-29 18:04:29 -07001988bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1989 BasicBlock* target = GetBasicBlock(target_id);
1990
1991 if (source == nullptr || target == nullptr)
1992 return false;
1993
1994 int idx;
1995 for (idx = gen_suspend_test_list_.Size() - 1; idx >= 0; idx--) {
1996 BasicBlock* bb = gen_suspend_test_list_.Get(idx);
1997 if (bb == source)
1998 return true; // The block has been inserted by a suspend check before.
1999 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
2000 return true;
2001 }
2002
2003 return false;
2004}
2005
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002006ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2007 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2008 visited_taken_(false), have_successors_(false) {
2009 // Check if we actually do have successors.
2010 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2011 have_successors_ = true;
2012 successor_iter_.Reset(basic_block_->successor_blocks);
2013 }
2014}
2015
2016BasicBlock* ChildBlockIterator::Next() {
2017 // We check if we have a basic block. If we don't we cannot get next child.
2018 if (basic_block_ == nullptr) {
2019 return nullptr;
2020 }
2021
2022 // If we haven't visited fallthrough, return that.
2023 if (visited_fallthrough_ == false) {
2024 visited_fallthrough_ = true;
2025
2026 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2027 if (result != nullptr) {
2028 return result;
2029 }
2030 }
2031
2032 // If we haven't visited taken, return that.
2033 if (visited_taken_ == false) {
2034 visited_taken_ = true;
2035
2036 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2037 if (result != nullptr) {
2038 return result;
2039 }
2040 }
2041
2042 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2043 if (have_successors_ == true) {
2044 // Get information about next successor block.
Niranjan Kumar989367a2014-06-12 12:15:48 -07002045 for (SuccessorBlockInfo* successor_block_info = successor_iter_.Next();
2046 successor_block_info != nullptr;
2047 successor_block_info = successor_iter_.Next()) {
2048 // If block was replaced by zero block, take next one.
2049 if (successor_block_info->block != NullBasicBlockId) {
2050 return mir_graph_->GetBasicBlock(successor_block_info->block);
2051 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002052 }
2053 }
2054
2055 // We do not have anything.
2056 return nullptr;
2057}
2058
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002059BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2060 MIRGraph* mir_graph = c_unit->mir_graph.get();
2061 return Copy(mir_graph);
2062}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002063
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002064BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2065 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002066
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002067 // We don't do a memcpy style copy here because it would lead to a lot of things
2068 // to clean up. Let us do it by hand instead.
2069 // Copy in taken and fallthrough.
2070 result_bb->fall_through = fall_through;
2071 result_bb->taken = taken;
2072
2073 // Copy successor links if needed.
2074 ArenaAllocator* arena = mir_graph->GetArena();
2075
2076 result_bb->successor_block_list_type = successor_block_list_type;
2077 if (result_bb->successor_block_list_type != kNotUsed) {
2078 size_t size = successor_blocks->Size();
2079 result_bb->successor_blocks = new (arena) GrowableArray<SuccessorBlockInfo*>(arena, size, kGrowableArraySuccessorBlocks);
2080 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2081 while (true) {
2082 SuccessorBlockInfo* sbi_old = iterator.Next();
2083 if (sbi_old == nullptr) {
2084 break;
2085 }
2086 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
2087 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
2088 result_bb->successor_blocks->Insert(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002089 }
2090 }
2091
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002092 // Copy offset, method.
2093 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002094
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002095 // Now copy instructions.
2096 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2097 // Get a copy first.
2098 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002099
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002100 // Append it.
2101 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002102 }
2103
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002104 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002105}
2106
2107MIR* MIR::Copy(MIRGraph* mir_graph) {
2108 MIR* res = mir_graph->NewMIR();
2109 *res = *this;
2110
2111 // Remove links
2112 res->next = nullptr;
2113 res->bb = NullBasicBlockId;
2114 res->ssa_rep = nullptr;
2115
2116 return res;
2117}
2118
2119MIR* MIR::Copy(CompilationUnit* c_unit) {
2120 return Copy(c_unit->mir_graph.get());
2121}
2122
2123uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2124 // Default result.
2125 int res = 0;
2126
2127 // We are basically setting the iputs to their igets counterparts.
2128 switch (opcode) {
2129 case Instruction::IPUT:
2130 case Instruction::IPUT_OBJECT:
2131 case Instruction::IPUT_BOOLEAN:
2132 case Instruction::IPUT_BYTE:
2133 case Instruction::IPUT_CHAR:
2134 case Instruction::IPUT_SHORT:
2135 case Instruction::IPUT_QUICK:
2136 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002137 case Instruction::IPUT_BOOLEAN_QUICK:
2138 case Instruction::IPUT_BYTE_QUICK:
2139 case Instruction::IPUT_CHAR_QUICK:
2140 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002141 case Instruction::APUT:
2142 case Instruction::APUT_OBJECT:
2143 case Instruction::APUT_BOOLEAN:
2144 case Instruction::APUT_BYTE:
2145 case Instruction::APUT_CHAR:
2146 case Instruction::APUT_SHORT:
2147 case Instruction::SPUT:
2148 case Instruction::SPUT_OBJECT:
2149 case Instruction::SPUT_BOOLEAN:
2150 case Instruction::SPUT_BYTE:
2151 case Instruction::SPUT_CHAR:
2152 case Instruction::SPUT_SHORT:
2153 // Skip the VR containing what to store.
2154 res = 1;
2155 break;
2156 case Instruction::IPUT_WIDE:
2157 case Instruction::IPUT_WIDE_QUICK:
2158 case Instruction::APUT_WIDE:
2159 case Instruction::SPUT_WIDE:
2160 // Skip the two VRs containing what to store.
2161 res = 2;
2162 break;
2163 default:
2164 // Do nothing in the general case.
2165 break;
2166 }
2167
2168 return res;
2169}
2170
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002171/**
2172 * @brief Given a decoded instruction, it checks whether the instruction
2173 * sets a constant and if it does, more information is provided about the
2174 * constant being set.
2175 * @param ptr_value pointer to a 64-bit holder for the constant.
2176 * @param wide Updated by function whether a wide constant is being set by bytecode.
2177 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2178 */
2179bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2180 bool sets_const = true;
2181 int64_t value = vB;
2182
2183 DCHECK(ptr_value != nullptr);
2184 DCHECK(wide != nullptr);
2185
2186 switch (opcode) {
2187 case Instruction::CONST_4:
2188 case Instruction::CONST_16:
2189 case Instruction::CONST:
2190 *wide = false;
2191 value <<= 32; // In order to get the sign extend.
2192 value >>= 32;
2193 break;
2194 case Instruction::CONST_HIGH16:
2195 *wide = false;
2196 value <<= 48; // In order to get the sign extend.
2197 value >>= 32;
2198 break;
2199 case Instruction::CONST_WIDE_16:
2200 case Instruction::CONST_WIDE_32:
2201 *wide = true;
2202 value <<= 32; // In order to get the sign extend.
2203 value >>= 32;
2204 break;
2205 case Instruction::CONST_WIDE:
2206 *wide = true;
2207 value = vB_wide;
2208 break;
2209 case Instruction::CONST_WIDE_HIGH16:
2210 *wide = true;
2211 value <<= 48; // In order to get the sign extend.
2212 break;
2213 default:
2214 sets_const = false;
2215 break;
2216 }
2217
2218 if (sets_const) {
2219 *ptr_value = value;
2220 }
2221
2222 return sets_const;
2223}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002224
2225void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2226 // Reset flags for all MIRs in bb.
2227 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2228 mir->optimization_flags &= (~reset_flags);
2229 }
2230}
2231
2232void BasicBlock::Hide(CompilationUnit* c_unit) {
2233 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2234 block_type = kDalvikByteCode;
2235
2236 // Mark it as hidden.
2237 hidden = true;
2238
2239 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2240 // are updated to know that they no longer have a parent.
2241 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2242 mir->bb = NullBasicBlockId;
2243 }
2244 first_mir_insn = nullptr;
2245 last_mir_insn = nullptr;
2246
2247 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2248
2249 MIRGraph* mir_graph = c_unit->mir_graph.get();
2250 while (true) {
2251 BasicBlock* pred_bb = mir_graph->GetBasicBlock(iterator.Next());
2252 if (pred_bb == nullptr) {
2253 break;
2254 }
2255
2256 // Sadly we have to go through the children by hand here.
2257 pred_bb->ReplaceChild(id, NullBasicBlockId);
2258 }
2259
2260 // Iterate through children of bb we are hiding.
2261 ChildBlockIterator successorChildIter(this, mir_graph);
2262
2263 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
2264 // Replace child with null child.
2265 childPtr->predecessors->Delete(id);
2266 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002267
2268 // Remove link to children.
2269 taken = NullBasicBlockId;
2270 fall_through = NullBasicBlockId;
2271 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002272}
2273
2274bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2275 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2276 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2277 // then it is not live out of this BB.
2278 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2279
2280 int last_ssa_reg = -1;
2281
2282 // Walk through the MIRs backwards.
2283 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2284 // Get ssa rep.
2285 SSARepresentation *ssa_rep = mir->ssa_rep;
2286
2287 // Go through the defines for this MIR.
2288 for (int i = 0; i < ssa_rep->num_defs; i++) {
2289 DCHECK(ssa_rep->defs != nullptr);
2290
2291 // Get the ssa reg.
2292 int def_ssa_reg = ssa_rep->defs[i];
2293
2294 // Get dalvik reg.
2295 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2296
2297 // Compare dalvik regs.
2298 if (dalvik_reg == def_dalvik_reg) {
2299 // We found a def of the register that we are being asked about.
2300 // Remember it.
2301 last_ssa_reg = def_ssa_reg;
2302 }
2303 }
2304 }
2305
2306 if (last_ssa_reg == -1) {
2307 // If we get to this point we couldn't find a define of register user asked about.
2308 // Let's assume the user knows what he's doing so we can be safe and say that if we
2309 // couldn't find a def, it is live out.
2310 return true;
2311 }
2312
2313 // If it is not -1, we found a match, is it ssa_reg?
2314 return (ssa_reg == last_ssa_reg);
2315}
2316
2317bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2318 // We need to check taken, fall_through, and successor_blocks to replace.
2319 bool found = false;
2320 if (taken == old_bb) {
2321 taken = new_bb;
2322 found = true;
2323 }
2324
2325 if (fall_through == old_bb) {
2326 fall_through = new_bb;
2327 found = true;
2328 }
2329
2330 if (successor_block_list_type != kNotUsed) {
2331 GrowableArray<SuccessorBlockInfo*>::Iterator iterator(successor_blocks);
2332 while (true) {
2333 SuccessorBlockInfo* successor_block_info = iterator.Next();
2334 if (successor_block_info == nullptr) {
2335 break;
2336 }
2337 if (successor_block_info->block == old_bb) {
2338 successor_block_info->block = new_bb;
2339 found = true;
2340 }
2341 }
2342 }
2343
2344 return found;
2345}
2346
2347void BasicBlock::UpdatePredecessor(BasicBlockId old_parent, BasicBlockId new_parent) {
2348 GrowableArray<BasicBlockId>::Iterator iterator(predecessors);
2349 bool found = false;
2350
2351 while (true) {
2352 BasicBlockId pred_bb_id = iterator.Next();
2353
2354 if (pred_bb_id == NullBasicBlockId) {
2355 break;
2356 }
2357
2358 if (pred_bb_id == old_parent) {
2359 size_t idx = iterator.GetIndex() - 1;
2360 predecessors->Put(idx, new_parent);
2361 found = true;
2362 break;
2363 }
2364 }
2365
2366 // If not found, add it.
2367 if (found == false) {
2368 predecessors->Insert(new_parent);
2369 }
2370}
2371
2372// Create a new basic block with block_id as num_blocks_ that is
2373// post-incremented.
2374BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2375 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
2376 block_list_.Insert(res);
2377 return res;
2378}
2379
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002380void MIRGraph::CalculateBasicBlockInformation() {
2381 PassDriverMEPostOpt driver(cu_);
2382 driver.Launch();
2383}
2384
2385void MIRGraph::InitializeBasicBlockData() {
2386 num_blocks_ = block_list_.Size();
2387}
2388
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002389int MIR::DecodedInstruction::FlagsOf() const {
2390 // Calculate new index.
2391 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2392
2393 // Check if it is an extended or not.
2394 if (idx < 0) {
2395 return Instruction::FlagsOf(opcode);
2396 }
2397
2398 // For extended, we use a switch.
2399 switch (static_cast<int>(opcode)) {
2400 case kMirOpPhi:
2401 return Instruction::kContinue;
2402 case kMirOpCopy:
2403 return Instruction::kContinue;
2404 case kMirOpFusedCmplFloat:
2405 return Instruction::kContinue | Instruction::kBranch;
2406 case kMirOpFusedCmpgFloat:
2407 return Instruction::kContinue | Instruction::kBranch;
2408 case kMirOpFusedCmplDouble:
2409 return Instruction::kContinue | Instruction::kBranch;
2410 case kMirOpFusedCmpgDouble:
2411 return Instruction::kContinue | Instruction::kBranch;
2412 case kMirOpFusedCmpLong:
2413 return Instruction::kContinue | Instruction::kBranch;
2414 case kMirOpNop:
2415 return Instruction::kContinue;
2416 case kMirOpNullCheck:
2417 return Instruction::kContinue | Instruction::kThrow;
2418 case kMirOpRangeCheck:
2419 return Instruction::kContinue | Instruction::kThrow;
2420 case kMirOpDivZeroCheck:
2421 return Instruction::kContinue | Instruction::kThrow;
2422 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002423 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002424 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002425 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002426 case kMirOpSelect:
2427 return Instruction::kContinue;
2428 case kMirOpConstVector:
2429 return Instruction::kContinue;
2430 case kMirOpMoveVector:
2431 return Instruction::kContinue;
2432 case kMirOpPackedMultiply:
2433 return Instruction::kContinue;
2434 case kMirOpPackedAddition:
2435 return Instruction::kContinue;
2436 case kMirOpPackedSubtract:
2437 return Instruction::kContinue;
2438 case kMirOpPackedShiftLeft:
2439 return Instruction::kContinue;
2440 case kMirOpPackedSignedShiftRight:
2441 return Instruction::kContinue;
2442 case kMirOpPackedUnsignedShiftRight:
2443 return Instruction::kContinue;
2444 case kMirOpPackedAnd:
2445 return Instruction::kContinue;
2446 case kMirOpPackedOr:
2447 return Instruction::kContinue;
2448 case kMirOpPackedXor:
2449 return Instruction::kContinue;
2450 case kMirOpPackedAddReduce:
2451 return Instruction::kContinue;
2452 case kMirOpPackedReduce:
2453 return Instruction::kContinue;
2454 case kMirOpPackedSet:
2455 return Instruction::kContinue;
2456 case kMirOpReserveVectorRegisters:
2457 return Instruction::kContinue;
2458 case kMirOpReturnVectorRegisters:
2459 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002460 case kMirOpMemBarrier:
2461 return Instruction::kContinue;
2462 case kMirOpPackedArrayGet:
2463 return Instruction::kContinue | Instruction::kThrow;
2464 case kMirOpPackedArrayPut:
2465 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002466 default:
2467 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2468 return 0;
2469 }
2470}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002471} // namespace art