blob: b87ab6634705df7f5cc52c60f45f2e9fa5b4ce15 [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),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010079 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
80 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
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),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010085 use_counts_(arena->Adapter()),
86 raw_use_counts_(arena->Adapter()),
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),
Vladimir Marko312eb252014-10-07 15:01:57 +010089 dfs_orders_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010090 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
91 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
92 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
93 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
94 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
95 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
96 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +010097 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -080098 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +000099 temp_scoped_alloc_(),
100 temp_insn_data_(nullptr),
101 temp_bit_vector_size_(0u),
102 temp_bit_vector_(nullptr),
Vladimir Marko5229cf12014-10-09 14:57:59 +0100103 temp_bit_matrix_(nullptr),
Vladimir Marko95a05972014-05-30 10:01:32 +0100104 temp_gvn_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100105 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800106 try_block_addr_(NULL),
107 entry_block_(NULL),
108 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800109 num_blocks_(0),
110 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100111 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100112 m_units_(arena->Adapter()),
113 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800114 current_method_(kInvalidEntry),
115 current_offset_(kInvalidEntry),
116 def_count_(0),
117 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700118 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100119 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700120 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700121 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
122 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700123 arena_(arena),
124 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800125 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800126 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700127 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
128 requested_backend_temp_(false),
129 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000130 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000131 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100132 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
133 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
134 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
135 gen_suspend_test_list_(arena->Adapter()) {
136 use_counts_.reserve(256);
137 raw_use_counts_.reserve(256);
138 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700139 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700140
141
142 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
143 // X86 requires a temp to keep track of the method address.
144 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
145 // this needs to be updated to reserve 0 temps for BE.
146 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
147 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
148 } else {
149 // Other architectures do not have a known lower bound for non-special temps.
150 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
151 max_available_non_special_compiler_temps_ = 0;
152 reserved_temps_for_backend_ = 0;
153 }
buzbee311ca162013-02-28 15:56:43 -0800154}
155
Ian Rogers6282dc12013-04-18 15:54:02 -0700156MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100157 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700158 STLDeleteElements(&m_units_);
159}
160
buzbee311ca162013-02-28 15:56:43 -0800161/*
162 * Parse an instruction, return the length of the instruction
163 */
Ian Rogers29a26482014-05-02 15:27:29 -0700164int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
165 const Instruction* inst = Instruction::At(code_ptr);
166 decoded_instruction->opcode = inst->Opcode();
167 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
168 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
169 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
170 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
171 if (inst->HasVarArgs()) {
172 inst->GetVarArgs(decoded_instruction->arg);
173 }
174 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800175}
176
177
178/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700179BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700180 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700181 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800182 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400183 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800184 while (insn) {
185 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700186 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800187 insn = insn->next;
188 }
189 if (insn == NULL) {
190 LOG(FATAL) << "Break split failed";
191 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400192 // Now insn is at the instruction where we want to split, namely
193 // insn will be the first instruction of the "bottom" block.
194 // Similarly, prev will be the last instruction of the "top" block
195
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100196 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800197
198 bottom_block->start_offset = code_offset;
199 bottom_block->first_mir_insn = insn;
200 bottom_block->last_mir_insn = orig_block->last_mir_insn;
201
Junmo Park90223cc2014-08-04 18:51:21 +0900202 /* If this block was terminated by a return, conditional branch or throw,
203 * the flag needs to go with the bottom block
204 */
buzbee311ca162013-02-28 15:56:43 -0800205 bottom_block->terminated_by_return = orig_block->terminated_by_return;
206 orig_block->terminated_by_return = false;
207
Junmo Park90223cc2014-08-04 18:51:21 +0900208 bottom_block->conditional_branch = orig_block->conditional_branch;
209 orig_block->conditional_branch = false;
210
211 bottom_block->explicit_throw = orig_block->explicit_throw;
212 orig_block->explicit_throw = false;
213
buzbee311ca162013-02-28 15:56:43 -0800214 /* Handle the taken path */
215 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700216 if (bottom_block->taken != NullBasicBlockId) {
217 orig_block->taken = NullBasicBlockId;
218 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100219 bb_taken->ErasePredecessor(orig_block->id);
220 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800221 }
222
223 /* Handle the fallthrough path */
224 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700225 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100226 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700227 if (bottom_block->fall_through != NullBasicBlockId) {
228 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100229 bb_fall_through->ErasePredecessor(orig_block->id);
230 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800231 }
232
233 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700234 if (orig_block->successor_block_list_type != kNotUsed) {
235 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100236 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700237 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100238 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
239 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700240 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700241 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100242 bb->ErasePredecessor(orig_block->id);
243 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700244 }
buzbee311ca162013-02-28 15:56:43 -0800245 }
246 }
247
buzbee0d829482013-10-11 15:24:55 -0700248 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700249 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800250
buzbee311ca162013-02-28 15:56:43 -0800251 /*
252 * Update the immediate predecessor block pointer so that outgoing edges
253 * can be applied to the proper block.
254 */
255 if (immed_pred_block_p) {
256 DCHECK_EQ(*immed_pred_block_p, orig_block);
257 *immed_pred_block_p = bottom_block;
258 }
buzbeeb48819d2013-09-14 16:15:25 -0700259
260 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000261 DCHECK(insn != nullptr);
262 DCHECK(insn != orig_block->first_mir_insn);
263 DCHECK(insn == bottom_block->first_mir_insn);
264 DCHECK_EQ(insn->offset, bottom_block->start_offset);
265 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700266 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100267 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400268 // Scan the "bottom" instructions, remapping them to the
269 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000270 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400271 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100272 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000273 while (p != bottom_block->last_mir_insn) {
274 p = p->next;
275 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700276 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700277 int opcode = p->dalvikInsn.opcode;
278 /*
279 * Some messiness here to ensure that we only enter real opcodes and only the
280 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000281 * CHECK and work portions. Since the 2nd half of a split operation is always
282 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700283 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700284 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400285 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
286 // At first glance the instructions should all be mapped to orig_block.
287 // However, multiple instructions may correspond to the same dex, hence an earlier
288 // instruction may have already moved the mapping for dex to bottom_block.
289 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100290 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700291 }
buzbeeb48819d2013-09-14 16:15:25 -0700292 }
293
buzbee311ca162013-02-28 15:56:43 -0800294 return bottom_block;
295}
296
297/*
298 * Given a code offset, find out the block that starts with it. If the offset
299 * is in the middle of an existing block, split it into two. If immed_pred_block_p
300 * is not non-null and is the block being split, update *immed_pred_block_p to
301 * point to the bottom block so that outgoing edges can be set up properly
302 * (by the caller)
303 * Utilizes a map for fast lookup of the typical cases.
304 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700305BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700306 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700307 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700308 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800309 }
buzbeeb48819d2013-09-14 16:15:25 -0700310
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100311 int block_id = dex_pc_to_block_map_[code_offset];
312 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700313
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700314 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700315 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700316 return bb;
317 }
buzbee311ca162013-02-28 15:56:43 -0800318
buzbeeb48819d2013-09-14 16:15:25 -0700319 // No direct hit.
320 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700321 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800322 }
323
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700324 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700325 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700326 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700327 }
328
329 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100330 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800331 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100332 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800333 return bb;
334}
335
buzbeeb48819d2013-09-14 16:15:25 -0700336
buzbee311ca162013-02-28 15:56:43 -0800337/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700338void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800339 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700340 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800341
342 if (tries_size == 0) {
343 return;
344 }
345
346 for (int i = 0; i < tries_size; i++) {
347 const DexFile::TryItem* pTry =
348 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700349 DexOffset start_offset = pTry->start_addr_;
350 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800351 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700352 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800353 }
354 }
355
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700356 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700357 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800358 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
359 for (uint32_t idx = 0; idx < handlers_size; idx++) {
360 CatchHandlerIterator iterator(handlers_ptr);
361 for (; iterator.HasNext(); iterator.Next()) {
362 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700363 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800364 }
365 handlers_ptr = iterator.EndDataPointer();
366 }
367}
368
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100369bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
370 NarrowDexOffset catch_offset) {
371 // Catches for monitor-exit during stack unwinding have the pattern
372 // move-exception (move)* (goto)? monitor-exit throw
373 // In the currently generated dex bytecode we see these catching a bytecode range including
374 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
375 // it's the case for a given monitor-exit and catch block so that we can ignore it.
376 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
377 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
378 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700379 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100380 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
381 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700382 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100383 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
384 if (check_insn->VRegA_11x() == monitor_reg) {
385 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
386 return false;
387 }
388 check_insn = check_insn->Next();
389 while (true) {
390 int dest = -1;
391 bool wide = false;
392 switch (check_insn->Opcode()) {
393 case Instruction::MOVE_WIDE:
394 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700395 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100396 case Instruction::MOVE_OBJECT:
397 case Instruction::MOVE:
398 dest = check_insn->VRegA_12x();
399 break;
400
401 case Instruction::MOVE_WIDE_FROM16:
402 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700403 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100404 case Instruction::MOVE_OBJECT_FROM16:
405 case Instruction::MOVE_FROM16:
406 dest = check_insn->VRegA_22x();
407 break;
408
409 case Instruction::MOVE_WIDE_16:
410 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700411 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100412 case Instruction::MOVE_OBJECT_16:
413 case Instruction::MOVE_16:
414 dest = check_insn->VRegA_32x();
415 break;
416
417 case Instruction::GOTO:
418 case Instruction::GOTO_16:
419 case Instruction::GOTO_32:
420 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700421 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100422 default:
423 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
424 check_insn->VRegA_11x() == monitor_reg;
425 }
426
427 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
428 return false;
429 }
430
431 check_insn = check_insn->Next();
432 }
433}
434
buzbee311ca162013-02-28 15:56:43 -0800435/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700436BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
437 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700438 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700439 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800440 switch (insn->dalvikInsn.opcode) {
441 case Instruction::GOTO:
442 case Instruction::GOTO_16:
443 case Instruction::GOTO_32:
444 target += insn->dalvikInsn.vA;
445 break;
446 case Instruction::IF_EQ:
447 case Instruction::IF_NE:
448 case Instruction::IF_LT:
449 case Instruction::IF_GE:
450 case Instruction::IF_GT:
451 case Instruction::IF_LE:
452 cur_block->conditional_branch = true;
453 target += insn->dalvikInsn.vC;
454 break;
455 case Instruction::IF_EQZ:
456 case Instruction::IF_NEZ:
457 case Instruction::IF_LTZ:
458 case Instruction::IF_GEZ:
459 case Instruction::IF_GTZ:
460 case Instruction::IF_LEZ:
461 cur_block->conditional_branch = true;
462 target += insn->dalvikInsn.vB;
463 break;
464 default:
465 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
466 }
buzbeeb48819d2013-09-14 16:15:25 -0700467 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700468 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800469 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700470 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100471 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800472
473 /* Always terminate the current block for conditional branches */
474 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700475 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800476 /* create */
477 true,
478 /* immed_pred_block_p */
479 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700480 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100481 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800482 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700483 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800484 }
485 return cur_block;
486}
487
488/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800489BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
490 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700491 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800492 const uint16_t* switch_data =
493 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
494 int size;
495 const int* keyTable;
496 const int* target_table;
497 int i;
498 int first_key;
499
500 /*
501 * Packed switch data format:
502 * ushort ident = 0x0100 magic value
503 * ushort size number of entries in the table
504 * int first_key first (and lowest) switch case value
505 * int targets[size] branch targets, relative to switch opcode
506 *
507 * Total size is (4+size*2) 16-bit code units.
508 */
509 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
510 DCHECK_EQ(static_cast<int>(switch_data[0]),
511 static_cast<int>(Instruction::kPackedSwitchSignature));
512 size = switch_data[1];
513 first_key = switch_data[2] | (switch_data[3] << 16);
514 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700515 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800516 /*
517 * Sparse switch data format:
518 * ushort ident = 0x0200 magic value
519 * ushort size number of entries in the table; > 0
520 * int keys[size] keys, sorted low-to-high; 32-bit aligned
521 * int targets[size] branch targets, relative to switch opcode
522 *
523 * Total size is (2+size*4) 16-bit code units.
524 */
525 } else {
526 DCHECK_EQ(static_cast<int>(switch_data[0]),
527 static_cast<int>(Instruction::kSparseSwitchSignature));
528 size = switch_data[1];
529 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
530 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700531 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800532 }
533
buzbee0d829482013-10-11 15:24:55 -0700534 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800535 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700536 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800537 }
buzbee0d829482013-10-11 15:24:55 -0700538 cur_block->successor_block_list_type =
539 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100540 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800541
542 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700543 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
544 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700545 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700546 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000547 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700548 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800549 successor_block_info->key =
550 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
551 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100552 cur_block->successor_blocks.push_back(successor_block_info);
553 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800554 }
555
556 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700557 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
558 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700559 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100560 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800561 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800562}
563
564/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700565BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
566 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700567 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700568 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700569 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800570 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800571
572 /* In try block */
573 if (in_try_block) {
574 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
575
buzbee0d829482013-10-11 15:24:55 -0700576 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800577 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
578 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700579 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800580 }
581
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700582 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700583 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
584 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100585 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
586 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
587 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
588 continue;
589 }
590 if (cur_block->successor_block_list_type == kNotUsed) {
591 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100592 }
buzbee311ca162013-02-28 15:56:43 -0800593 catch_block->catch_entry = true;
594 if (kIsDebugBuild) {
595 catches_.insert(catch_block->start_offset);
596 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700597 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000598 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700599 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800600 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100601 cur_block->successor_blocks.push_back(successor_block_info);
602 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800603 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100604 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
605 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100606 bool build_all_edges =
607 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100608 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100609 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700610 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800611 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100612 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800613 }
614
buzbee17189ac2013-11-08 11:07:02 -0800615 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800616 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700617 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700618 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700619 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800620 }
621 if (!in_try_block) {
622 // Don't split a THROW that can't rethrow - we're done.
623 return cur_block;
624 }
625 }
626
buzbee17189ac2013-11-08 11:07:02 -0800627 if (!build_all_edges) {
628 /*
629 * Even though there is an exception edge here, control cannot return to this
630 * method. Thus, for the purposes of dataflow analysis and optimization, we can
631 * ignore the edge. Doing this reduces compile time, and increases the scope
632 * of the basic-block level optimization pass.
633 */
634 return cur_block;
635 }
636
buzbee311ca162013-02-28 15:56:43 -0800637 /*
638 * Split the potentially-throwing instruction into two parts.
639 * The first half will be a pseudo-op that captures the exception
640 * edges and terminates the basic block. It always falls through.
641 * Then, create a new basic block that begins with the throwing instruction
642 * (minus exceptions). Note: this new basic block must NOT be entered into
643 * the block_map. If the potentially-throwing instruction is the target of a
644 * future branch, we need to find the check psuedo half. The new
645 * basic block containing the work portion of the instruction should
646 * only be entered via fallthrough from the block containing the
647 * pseudo exception edge MIR. Note also that this new block is
648 * not automatically terminated after the work portion, and may
649 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700650 *
651 * Note also that the dex_pc_to_block_map_ entry for the potentially
652 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800653 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100654 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800655 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700656 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100657 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700658 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800659 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700660 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700661 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800662 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700663 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800664 return new_block;
665}
666
667/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
668void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700669 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700670 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800671 current_code_item_ = code_item;
672 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
673 current_method_ = m_units_.size();
674 current_offset_ = 0;
675 // TODO: will need to snapshot stack image and use that as the mir context identification.
676 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000677 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
678 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800679 const uint16_t* code_ptr = current_code_item_->insns_;
680 const uint16_t* code_end =
681 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
682
683 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700684 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100685 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
686 dex_pc_to_block_map_.resize(dex_pc_to_block_map_.size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700687
buzbee311ca162013-02-28 15:56:43 -0800688 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700689 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
690 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800691
692 // If this is the first method, set up default entry and exit blocks.
693 if (current_method_ == 0) {
694 DCHECK(entry_block_ == NULL);
695 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700696 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700697 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100698 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700699 DCHECK_EQ(null_block->id, NullBasicBlockId);
700 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100701 entry_block_ = CreateNewBB(kEntryBlock);
702 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800703 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
704 cu_->dex_file = &dex_file;
705 cu_->class_def_idx = class_def_idx;
706 cu_->method_idx = method_idx;
707 cu_->access_flags = access_flags;
708 cu_->invoke_type = invoke_type;
709 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800710 } else {
711 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
712 /*
713 * Will need to manage storage for ins & outs, push prevous state and update
714 * insert point.
715 */
716 }
717
718 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100719 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700720 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800721 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700722 // TODO: for inlining support, insert at the insert point rather than entry block.
723 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100724 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800725
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000726 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800727 ProcessTryCatchBlocks();
728
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000729 uint64_t merged_df_flags = 0u;
730
buzbee311ca162013-02-28 15:56:43 -0800731 /* Parse all instructions and put them into containing basic blocks */
732 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700733 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800734 insn->offset = current_offset_;
735 insn->m_unit_index = current_method_;
736 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800737 Instruction::Code opcode = insn->dalvikInsn.opcode;
738 if (opcode_count_ != NULL) {
739 opcode_count_[static_cast<int>(opcode)]++;
740 }
741
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700742 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800743 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800744
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700745 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000746 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800747
748 if (df_flags & DF_HAS_DEFS) {
749 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
750 }
751
buzbee1da1e2f2013-11-15 13:37:01 -0800752 if (df_flags & DF_LVN) {
753 cur_block->use_lvn = true; // Run local value numbering on this basic block.
754 }
755
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700756 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700757 if (opcode == Instruction::NOP) {
758 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
759 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
760 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
761 uint16_t following_raw_instruction = code_ptr[1];
762 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
763 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
764 (following_raw_instruction == Instruction::kArrayDataSignature)) {
765 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
766 }
767 }
768 if (width == 1) {
769 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700770 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700771 } else {
buzbee0d829482013-10-11 15:24:55 -0700772 DCHECK(cur_block->fall_through == NullBasicBlockId);
773 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700774 // Unreachable instruction, mark for no continuation.
775 flags &= ~Instruction::kContinue;
776 }
777 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700778 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700779 }
780
buzbeeb48819d2013-09-14 16:15:25 -0700781 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100782 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700783
buzbee27247762013-07-28 12:03:58 -0700784 code_ptr += width;
785
buzbee311ca162013-02-28 15:56:43 -0800786 if (flags & Instruction::kBranch) {
787 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
788 width, flags, code_ptr, code_end);
789 } else if (flags & Instruction::kReturn) {
790 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700791 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100792 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800793 /*
794 * Terminate the current block if there are instructions
795 * afterwards.
796 */
797 if (code_ptr < code_end) {
798 /*
799 * Create a fallthrough block for real instructions
800 * (incl. NOP).
801 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700802 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800803 }
804 } else if (flags & Instruction::kThrow) {
805 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
806 code_ptr, code_end);
807 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800808 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800809 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700810 if (verify_flags & Instruction::kVerifyVarArgRange ||
811 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800812 /*
813 * The Quick backend's runtime model includes a gap between a method's
814 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
815 * which spans the gap is somewhat complicated, and should not happen
816 * in normal usage of dx. Punt to the interpreter.
817 */
818 int first_reg_in_range = insn->dalvikInsn.vC;
819 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
820 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
821 punt_to_interpreter_ = true;
822 }
823 }
buzbee311ca162013-02-28 15:56:43 -0800824 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700825 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
826 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800827 if (next_block) {
828 /*
829 * The next instruction could be the target of a previously parsed
830 * forward branch so a block is already created. If the current
831 * instruction is not an unconditional branch, connect them through
832 * the fall-through link.
833 */
buzbee0d829482013-10-11 15:24:55 -0700834 DCHECK(cur_block->fall_through == NullBasicBlockId ||
835 GetBasicBlock(cur_block->fall_through) == next_block ||
836 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800837
buzbee0d829482013-10-11 15:24:55 -0700838 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
839 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100840 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800841 }
842 cur_block = next_block;
843 }
844 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000845 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000846
buzbee311ca162013-02-28 15:56:43 -0800847 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
848 DumpCFG("/sdcard/1_post_parse_cfg/", true);
849 }
850
851 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700852 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800853 }
854}
855
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700856void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800857 DCHECK(opcode_count_ != NULL);
858 LOG(INFO) << "Opcode Count";
859 for (int i = 0; i < kNumPackedOpcodes; i++) {
860 if (opcode_count_[i] != 0) {
861 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
862 << " " << opcode_count_[i];
863 }
864 }
865}
866
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700867uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
868 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
869 return oat_data_flow_attributes_[opcode];
870}
871
872uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
873 DCHECK(mir != nullptr);
874 Instruction::Code opcode = mir->dalvikInsn.opcode;
875 return GetDataFlowAttributes(opcode);
876}
877
buzbee311ca162013-02-28 15:56:43 -0800878// TODO: use a configurable base prefix, and adjust callers to supply pass name.
879/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800880void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800881 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700882 static AtomicInteger cnt(0);
883
884 // Increment counter to get a unique file number.
885 cnt++;
886
buzbee311ca162013-02-28 15:56:43 -0800887 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
888 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700889 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800890 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700891 suffix == nullptr ? "" : suffix,
892 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800893 file = fopen(fname.c_str(), "w");
894 if (file == NULL) {
895 return;
896 }
897 fprintf(file, "digraph G {\n");
898
899 fprintf(file, " rankdir=TB\n");
900
901 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
902 int idx;
903
904 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100905 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700906 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700907 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800908 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700909 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800910 if (bb->block_type == kEntryBlock) {
911 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
912 } else if (bb->block_type == kExitBlock) {
913 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
914 } else if (bb->block_type == kDalvikByteCode) {
915 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
916 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700917 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800918 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
919 bb->first_mir_insn ? " | " : " ");
920 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
921 int opcode = mir->dalvikInsn.opcode;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100922 fprintf(file, " {%04x %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400923 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700924 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
925 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400926 extended_mir_op_names_[opcode - kMirOpFirst],
927 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
928 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700929 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700930 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700931 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100932 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
933 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400934 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800935 }
936 fprintf(file, " }\"];\n\n");
937 } else if (bb->block_type == kExceptionHandling) {
938 char block_name[BLOCK_NAME_LEN];
939
940 GetBlockName(bb, block_name);
941 fprintf(file, " %s [shape=invhouse];\n", block_name);
942 }
943
944 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
945
buzbee0d829482013-10-11 15:24:55 -0700946 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800947 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700948 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800949 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
950 block_name1, block_name2);
951 }
buzbee0d829482013-10-11 15:24:55 -0700952 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800953 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700954 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800955 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
956 }
957
buzbee0d829482013-10-11 15:24:55 -0700958 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800959 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
960 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700961 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800962
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100963 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800964 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100965 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700966 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800967 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100968 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800969 successor_block_info->key,
970 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100971 (succ_id != last_succ_id) ? " | " : " ");
972 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800973 }
974 fprintf(file, " }\"];\n\n");
975
976 GetBlockName(bb, block_name1);
977 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
978 block_name1, bb->start_offset, bb->id);
979
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700980 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700981 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100982 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700983 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800984
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700985 GetBlockName(dest_block, block_name2);
986 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
987 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800988 }
989 }
990 fprintf(file, "\n");
991
992 if (cu_->verbose) {
993 /* Display the dominator tree */
994 GetBlockName(bb, block_name1);
995 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
996 block_name1, block_name1);
997 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700998 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800999 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1000 }
1001 }
1002 }
1003 fprintf(file, "}\n");
1004 fclose(file);
1005}
1006
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001007/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001008void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001009 // Insert it after the last MIR.
1010 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001011}
1012
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001013void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1014 // Insert it after the last MIR.
1015 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1016}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001017
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001018void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1019 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1020 MIR* new_mir = *it;
1021
1022 // Add a copy of each MIR.
1023 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1024 }
buzbee1fd33462013-03-25 13:40:45 -07001025}
1026
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001027/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001028void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001029 InsertMIRListAfter(current_mir, new_mir, new_mir);
1030}
buzbee1fd33462013-03-25 13:40:45 -07001031
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001032void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1033 // If no MIR, we are done.
1034 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1035 return;
buzbee1fd33462013-03-25 13:40:45 -07001036 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001037
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001038 // If insert_after is null, assume BB is empty.
1039 if (insert_after == nullptr) {
1040 first_mir_insn = first_list_mir;
1041 last_mir_insn = last_list_mir;
1042 last_list_mir->next = nullptr;
1043 } else {
1044 MIR* after_list = insert_after->next;
1045 insert_after->next = first_list_mir;
1046 last_list_mir->next = after_list;
1047 if (after_list == nullptr) {
1048 last_mir_insn = last_list_mir;
1049 }
1050 }
1051
1052 // Set this BB to be the basic block of the MIRs.
1053 MIR* last = last_list_mir->next;
1054 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1055 mir->bb = id;
1056 }
1057}
1058
1059/* Insert an MIR instruction to the head of a basic block. */
1060void BasicBlock::PrependMIR(MIR* mir) {
1061 InsertMIRListBefore(first_mir_insn, mir, mir);
1062}
1063
1064void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1065 // Insert it before the first MIR.
1066 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1067}
1068
1069void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1070 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1071 MIR* mir = *it;
1072
1073 InsertMIRListBefore(first_mir_insn, mir, mir);
1074 }
1075}
1076
1077/* Insert a MIR instruction before the specified MIR. */
1078void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1079 // Insert as a single element list.
1080 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001081}
1082
1083MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1084 MIR* current = first_mir_insn;
1085
1086 while (current != nullptr) {
1087 MIR* next = current->next;
1088
1089 if (next == mir) {
1090 return current;
1091 }
1092
1093 current = next;
1094 }
1095
1096 return nullptr;
1097}
1098
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001099void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1100 // If no MIR, we are done.
1101 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1102 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001103 }
1104
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001105 // If insert_before is null, assume BB is empty.
1106 if (insert_before == nullptr) {
1107 first_mir_insn = first_list_mir;
1108 last_mir_insn = last_list_mir;
1109 last_list_mir->next = nullptr;
1110 } else {
1111 if (first_mir_insn == insert_before) {
1112 last_list_mir->next = first_mir_insn;
1113 first_mir_insn = first_list_mir;
1114 } else {
1115 // Find the preceding MIR.
1116 MIR* before_list = FindPreviousMIR(insert_before);
1117 DCHECK(before_list != nullptr);
1118 before_list->next = first_list_mir;
1119 last_list_mir->next = insert_before;
1120 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001121 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001122
1123 // Set this BB to be the basic block of the MIRs.
1124 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1125 mir->bb = id;
1126 }
1127}
1128
1129bool BasicBlock::RemoveMIR(MIR* mir) {
1130 // Remove as a single element list.
1131 return RemoveMIRList(mir, mir);
1132}
1133
1134bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1135 if (first_list_mir == nullptr) {
1136 return false;
1137 }
1138
1139 // Try to find the MIR.
1140 MIR* before_list = nullptr;
1141 MIR* after_list = nullptr;
1142
1143 // If we are removing from the beginning of the MIR list.
1144 if (first_mir_insn == first_list_mir) {
1145 before_list = nullptr;
1146 } else {
1147 before_list = FindPreviousMIR(first_list_mir);
1148 if (before_list == nullptr) {
1149 // We did not find the mir.
1150 return false;
1151 }
1152 }
1153
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001154 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001155 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001156 mir->bb = NullBasicBlockId;
1157 }
1158
1159 after_list = last_list_mir->next;
1160
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001161 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001162 if (before_list == nullptr) {
1163 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001164 } else {
1165 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001166 }
1167
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001168 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001169 if (after_list == nullptr) {
1170 last_mir_insn = before_list;
1171 }
1172
1173 return true;
buzbee1fd33462013-03-25 13:40:45 -07001174}
1175
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001176MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001177 MIR* next_mir = nullptr;
1178
1179 if (current != nullptr) {
1180 next_mir = current->next;
1181 }
1182
1183 if (next_mir == nullptr) {
1184 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001185 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1186 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001187 }
1188 }
1189
1190 return next_mir;
1191}
1192
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001193static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1194 DCHECK(decoded_mir != nullptr);
1195 OpSize type = static_cast<OpSize>(type_size >> 16);
1196 uint16_t vect_size = (type_size & 0xFFFF);
1197
1198 // Now print the type and vector size.
1199 std::stringstream ss;
1200 ss << " (type:";
1201 ss << type;
1202 ss << " vectsize:";
1203 ss << vect_size;
1204 ss << ")";
1205
1206 decoded_mir->append(ss.str());
1207}
1208
1209void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1210 DCHECK(decoded_mir != nullptr);
1211 int opcode = mir->dalvikInsn.opcode;
1212 SSARepresentation* ssa_rep = mir->ssa_rep;
1213 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1214 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1215
1216 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1217
1218 switch (opcode) {
1219 case kMirOpPhi: {
1220 if (defs > 0 && uses > 0) {
1221 BasicBlockId* incoming = mir->meta.phi_incoming;
1222 decoded_mir->append(StringPrintf(" %s = (%s",
1223 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1224 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1225 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1226 for (int i = 1; i < uses; i++) {
1227 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1228 }
1229 decoded_mir->append(")");
1230 }
1231 break;
1232 }
1233 case kMirOpCopy:
1234 if (ssa_rep != nullptr) {
1235 decoded_mir->append(" ");
1236 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1237 if (defs > 1) {
1238 decoded_mir->append(", ");
1239 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1240 }
1241 decoded_mir->append(" = ");
1242 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1243 if (uses > 1) {
1244 decoded_mir->append(", ");
1245 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1246 }
1247 } else {
1248 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1249 }
1250 break;
1251 case kMirOpFusedCmplFloat:
1252 case kMirOpFusedCmpgFloat:
1253 case kMirOpFusedCmplDouble:
1254 case kMirOpFusedCmpgDouble:
1255 case kMirOpFusedCmpLong:
1256 if (ssa_rep != nullptr) {
1257 decoded_mir->append(" ");
1258 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1259 for (int i = 1; i < uses; i++) {
1260 decoded_mir->append(", ");
1261 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1262 }
1263 } else {
1264 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1265 }
1266 break;
1267 case kMirOpMoveVector:
1268 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1269 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1270 break;
1271 case kMirOpPackedAddition:
1272 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1273 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1274 break;
1275 case kMirOpPackedMultiply:
1276 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1277 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1278 break;
1279 case kMirOpPackedSubtract:
1280 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1281 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1282 break;
1283 case kMirOpPackedAnd:
1284 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1285 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1286 break;
1287 case kMirOpPackedOr:
1288 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1289 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1290 break;
1291 case kMirOpPackedXor:
1292 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1293 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1294 break;
1295 case kMirOpPackedShiftLeft:
1296 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1297 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1298 break;
1299 case kMirOpPackedUnsignedShiftRight:
1300 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1301 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1302 break;
1303 case kMirOpPackedSignedShiftRight:
1304 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1305 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1306 break;
1307 case kMirOpConstVector:
1308 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1309 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1310 break;
1311 case kMirOpPackedSet:
1312 if (ssa_rep != nullptr) {
1313 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1314 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1315 if (uses > 1) {
1316 decoded_mir->append(", ");
1317 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1318 }
1319 } else {
1320 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1321 }
1322 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1323 break;
1324 case kMirOpPackedAddReduce:
1325 if (ssa_rep != nullptr) {
1326 decoded_mir->append(" ");
1327 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1328 if (defs > 1) {
1329 decoded_mir->append(", ");
1330 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1331 }
1332 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1333 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1334 if (uses > 1) {
1335 decoded_mir->append(", ");
1336 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1337 }
1338 } else {
1339 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1340 }
1341 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1342 break;
1343 case kMirOpPackedReduce:
1344 if (ssa_rep != nullptr) {
1345 decoded_mir->append(" ");
1346 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1347 if (defs > 1) {
1348 decoded_mir->append(", ");
1349 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1350 }
1351 decoded_mir->append(StringPrintf(" = vect%d", mir->dalvikInsn.vB));
1352 } else {
1353 decoded_mir->append(StringPrintf(" v%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1354 }
1355 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1356 break;
1357 case kMirOpReserveVectorRegisters:
1358 case kMirOpReturnVectorRegisters:
1359 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1360 break;
1361 case kMirOpMemBarrier: {
1362 decoded_mir->append(" type:");
1363 std::stringstream ss;
1364 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1365 decoded_mir->append(ss.str());
1366 break;
1367 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001368 case kMirOpPackedArrayGet:
1369 case kMirOpPackedArrayPut:
1370 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1371 if (ssa_rep != nullptr) {
1372 decoded_mir->append(StringPrintf(", %s[%s]",
1373 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1374 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1375 } else {
1376 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1377 }
1378 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1379 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001380 default:
1381 break;
1382 }
1383}
1384
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001385char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001386 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001387 std::string str;
1388 int flags = 0;
1389 int opcode = insn.opcode;
1390 char* ret;
1391 bool nop = false;
1392 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001393 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001394
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001395 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001396 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1397 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1398 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001399 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001400 insn = mir->meta.throw_insn->dalvikInsn;
1401 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001402 opcode = insn.opcode;
1403 } else if (opcode == kMirOpNop) {
1404 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001405 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1406 // Recover original opcode.
1407 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1408 opcode = insn.opcode;
1409 }
buzbee1fd33462013-03-25 13:40:45 -07001410 nop = true;
1411 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001412 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1413 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001414
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001415 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001416 // Note that this does not check the MIR's opcode in all cases. In cases where it
1417 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1418 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001419 } else {
1420 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001421 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001422 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001423
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001424 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001425 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1426 (dalvik_format == Instruction::k3rc));
1427 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001428 str.append(" ");
1429 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1430 if (defs > 1) {
1431 str.append(", ");
1432 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1433 }
buzbee1fd33462013-03-25 13:40:45 -07001434 if (uses != 0) {
1435 str.append(", ");
1436 }
1437 }
1438 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001439 str.append(" ");
1440 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001441 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1442 // For the listing, skip the high sreg.
1443 i++;
1444 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001445 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001446 str.append(",");
1447 }
1448 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001449
buzbee1fd33462013-03-25 13:40:45 -07001450 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001451 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001452 case Instruction::k21s:
1453 case Instruction::k31i:
1454 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001455 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001456 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001457 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001458 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001459 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001460 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001461 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001462 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001463 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001464 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001465 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001466 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001467 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001468 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001469 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001470 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001471 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001472 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001473 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001474 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001475
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001476 if ((flags & Instruction::kBranch) != 0) {
1477 // For branches, decode the instructions to print out the branch targets.
1478 int offset = 0;
1479 switch (dalvik_format) {
1480 case Instruction::k21t:
1481 offset = insn.vB;
1482 break;
1483 case Instruction::k22t:
1484 offset = insn.vC;
1485 break;
1486 case Instruction::k10t:
1487 case Instruction::k20t:
1488 case Instruction::k30t:
1489 offset = insn.vA;
1490 break;
1491 default:
1492 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001493 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001494 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001495 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001496 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1497 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001498
1499 if (nop) {
1500 str.append("]--optimized away");
1501 }
buzbee1fd33462013-03-25 13:40:45 -07001502 }
1503 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001504 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001505 strncpy(ret, str.c_str(), length);
1506 return ret;
1507}
1508
1509/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001510void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001511 static const struct { const char before; const char after; } match[] = {
1512 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1513 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1514 };
buzbee1fd33462013-03-25 13:40:45 -07001515 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1516 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1517 }
1518}
1519
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001520std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001521 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1522 // the arena. We should be smarter and just place straight into the arena, or compute the
1523 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001524 int vreg = SRegToVReg(ssa_reg);
1525 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1526 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1527 } else {
1528 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1529 }
buzbee1fd33462013-03-25 13:40:45 -07001530}
1531
1532// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001533std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001534 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001535 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001536 return GetSSAName(ssa_reg);
1537 }
1538 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001539 if (!singles_only && reg_location_[ssa_reg].wide &&
1540 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001541 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001542 ConstantValueWide(reg_location_[ssa_reg]));
1543 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001544 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001545 ConstantValue(reg_location_[ssa_reg]));
1546 }
1547 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001548 int vreg = SRegToVReg(ssa_reg);
1549 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1550 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1551 } else {
1552 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1553 }
buzbee1fd33462013-03-25 13:40:45 -07001554 }
1555}
1556
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001557void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001558 switch (bb->block_type) {
1559 case kEntryBlock:
1560 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1561 break;
1562 case kExitBlock:
1563 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1564 break;
1565 case kDalvikByteCode:
1566 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1567 break;
1568 case kExceptionHandling:
1569 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1570 bb->id);
1571 break;
1572 default:
1573 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1574 break;
1575 }
1576}
1577
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001578const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001579 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001580 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1581 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1582}
1583
1584/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001585void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001586 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001587 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001588 "Entry Block",
1589 "Code Block",
1590 "Exit Block",
1591 "Exception Handling",
1592 "Catch Block"
1593 };
1594
1595 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001596 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001597 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001598
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001599 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001600 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1601 bb->id,
1602 block_type_names[bb->block_type],
1603 bb->start_offset,
1604 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1605 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001606 if (bb->taken != NullBasicBlockId) {
1607 LOG(INFO) << " Taken branch: block " << bb->taken
1608 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001609 }
buzbee0d829482013-10-11 15:24:55 -07001610 if (bb->fall_through != NullBasicBlockId) {
1611 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1612 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001613 }
1614 }
1615}
1616
1617/*
1618 * Build an array of location records for the incoming arguments.
1619 * Note: one location record per word of arguments, with dummy
1620 * high-word loc for wide arguments. Also pull up any following
1621 * MOVE_RESULT and incorporate it into the invoke.
1622 */
1623CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001624 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001625 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001626 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001627 MIR* move_result_mir = FindMoveResult(bb, mir);
1628 if (move_result_mir == NULL) {
1629 info->result.location = kLocInvalid;
1630 } else {
1631 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001632 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1633 }
1634 info->num_arg_words = mir->ssa_rep->num_uses;
1635 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001636 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001637 for (int i = 0; i < info->num_arg_words; i++) {
1638 info->args[i] = GetRawSrc(mir, i);
1639 }
1640 info->opt_flags = mir->optimization_flags;
1641 info->type = type;
1642 info->is_range = is_range;
1643 info->index = mir->dalvikInsn.vB;
1644 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001645 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001646 return info;
1647}
1648
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001649// Allocate a new MIR.
1650MIR* MIRGraph::NewMIR() {
1651 MIR* mir = new (arena_) MIR();
1652 return mir;
1653}
1654
buzbee862a7602013-04-05 10:58:54 -07001655// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001656BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001657 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001658
buzbee862a7602013-04-05 10:58:54 -07001659 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001660 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001661 block_id_map_.Put(block_id, block_id);
1662 return bb;
1663}
buzbee1fd33462013-03-25 13:40:45 -07001664
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001665void MIRGraph::InitializeConstantPropagation() {
1666 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001667 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001668}
1669
1670void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001671 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001672 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001673 use_counts_.clear();
1674 use_counts_.reserve(num_ssa_regs + 32);
1675 use_counts_.resize(num_ssa_regs, 0u);
1676 raw_use_counts_.clear();
1677 raw_use_counts_.reserve(num_ssa_regs + 32);
1678 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001679}
1680
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001681void MIRGraph::SSATransformationStart() {
1682 DCHECK(temp_scoped_alloc_.get() == nullptr);
1683 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001684 temp_bit_vector_size_ = GetNumOfCodeAndTempVRs();
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001685 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1686 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001687}
1688
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001689void MIRGraph::SSATransformationEnd() {
1690 // Verify the dataflow information after the pass.
1691 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1692 VerifyDataflow();
1693 }
1694
1695 temp_bit_vector_size_ = 0u;
1696 temp_bit_vector_ = nullptr;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001697 temp_bit_matrix_ = nullptr; // Def block matrix.
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001698 DCHECK(temp_scoped_alloc_.get() != nullptr);
1699 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001700
1701 // Update the maximum number of reachable blocks.
1702 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001703}
1704
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001705size_t MIRGraph::GetNumDalvikInsns() const {
1706 size_t cumulative_size = 0u;
1707 bool counted_current_item = false;
1708 const uint8_t size_for_null_code_item = 2u;
1709
1710 for (auto it : m_units_) {
1711 const DexFile::CodeItem* code_item = it->GetCodeItem();
1712 // Even if the code item is null, we still count non-zero value so that
1713 // each m_unit is counted as having impact.
1714 cumulative_size += (code_item == nullptr ?
1715 size_for_null_code_item : code_item->insns_size_in_code_units_);
1716 if (code_item == current_code_item_) {
1717 counted_current_item = true;
1718 }
1719 }
1720
1721 // If the current code item was not counted yet, count it now.
1722 // This can happen for example in unit tests where some fields like m_units_
1723 // are not initialized.
1724 if (counted_current_item == false) {
1725 cumulative_size += (current_code_item_ == nullptr ?
1726 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1727 }
1728
1729 return cumulative_size;
1730}
1731
Vladimir Marko55fff042014-07-10 12:42:52 +01001732static BasicBlock* SelectTopologicalSortOrderFallBack(
1733 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1734 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1735 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1736 // No true loop head has been found but there may be true loop heads after the mess we need
1737 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1738 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1739 BasicBlock* fall_back = nullptr;
1740 size_t fall_back_num_reachable = 0u;
1741 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1742 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1743 AllNodesIterator iter(mir_graph);
1744 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1745 if (candidate->hidden || // Hidden, or
1746 candidate->visited || // already processed, or
1747 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1748 (current_loop != nullptr && // outside current loop.
1749 !current_loop->IsBitSet(candidate->id))) {
1750 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001751 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001752 DCHECK(tmp_stack->empty());
1753 tmp_stack->push_back(candidate->id);
1754 candidate_reachable.ClearAllBits();
1755 size_t num_reachable = 0u;
1756 while (!tmp_stack->empty()) {
1757 BasicBlockId current_id = tmp_stack->back();
1758 tmp_stack->pop_back();
1759 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1760 DCHECK(current_bb != nullptr);
1761 ChildBlockIterator child_iter(current_bb, mir_graph);
1762 BasicBlock* child_bb = child_iter.Next();
1763 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1764 DCHECK(!child_bb->hidden);
1765 if (child_bb->visited || // Already processed, or
1766 (current_loop != nullptr && // outside current loop.
1767 !current_loop->IsBitSet(child_bb->id))) {
1768 continue;
1769 }
1770 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1771 candidate_reachable.SetBit(child_bb->id);
1772 tmp_stack->push_back(child_bb->id);
1773 num_reachable += 1u;
1774 }
1775 }
1776 }
1777 if (fall_back_num_reachable < num_reachable) {
1778 fall_back_num_reachable = num_reachable;
1779 fall_back = candidate;
1780 }
1781 }
1782 return fall_back;
1783}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001784
Vladimir Marko55fff042014-07-10 12:42:52 +01001785// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1786static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1787 ArenaBitVector* reachable,
1788 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1789 // NOTE: Loop heads indicated by the "visited" flag.
1790 DCHECK(tmp_stack->empty());
1791 reachable->ClearAllBits();
1792 tmp_stack->push_back(bb_id);
1793 while (!tmp_stack->empty()) {
1794 BasicBlockId current_id = tmp_stack->back();
1795 tmp_stack->pop_back();
1796 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1797 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001798 for (BasicBlockId pred_id : current_bb->predecessors) {
1799 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1800 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001801 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1802 reachable->SetBit(pred_bb->id);
1803 tmp_stack->push_back(pred_bb->id);
1804 }
1805 }
1806 }
1807}
1808
1809void MIRGraph::ComputeTopologicalSortOrder() {
1810 ScopedArenaAllocator allocator(&cu_->arena_stack);
1811 unsigned int num_blocks = GetNumBlocks();
1812
1813 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1814 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1815 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1816 size_t max_nested_loops = 0u;
1817 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1818 loop_exit_blocks.ClearAllBits();
1819
1820 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001821 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001822 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001823 if (bb->hidden == true) {
1824 continue;
1825 }
1826
Vladimir Marko55fff042014-07-10 12:42:52 +01001827 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001828
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001829 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001830 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001831 q.push(bb);
1832 }
1833 }
1834
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001835 // Clear the topological order arrays.
1836 topological_order_.clear();
1837 topological_order_.reserve(num_blocks);
1838 topological_order_loop_ends_.clear();
1839 topological_order_loop_ends_.resize(num_blocks, 0u);
1840 topological_order_indexes_.clear();
1841 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001842
1843 // Mark all blocks as unvisited.
1844 ClearAllVisitedFlags();
1845
1846 // For loop heads, keep track from which blocks they are reachable not going through other
1847 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1848 // in this set go into the loop body, the other children are jumping over the loop.
1849 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1850 loop_head_reachable_from.resize(num_blocks, nullptr);
1851 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1852 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1853
1854 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001855 BasicBlock* bb = nullptr;
1856 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001857 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001858 // Get top.
1859 bb = q.front();
1860 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001861 if (bb->visited) {
1862 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1863 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001864 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1865 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001866 DCHECK_EQ(loop_head_stack.back(), bb->id);
1867 loop_head_stack.pop_back();
1868 ArenaBitVector* reachable =
1869 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1870 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1871 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1872 q.push(GetBasicBlock(candidate_id));
1873 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1874 // so clearing the bit has no effect on the iterator.
1875 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001876 }
1877 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001878 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001879 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001880 } else {
1881 // Find the new loop head.
1882 AllNodesIterator iter(this);
1883 while (true) {
1884 BasicBlock* candidate = iter.Next();
1885 if (candidate == nullptr) {
1886 // We did not find a true loop head, fall back to a reachable block in any loop.
1887 ArenaBitVector* current_loop =
1888 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1889 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1890 &allocator, &tmp_stack);
1891 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1892 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1893 LOG(INFO) << "Topological sort order: Using fall-back in "
1894 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1895 << " @0x" << std::hex << bb->start_offset
1896 << ", num_blocks = " << std::dec << num_blocks;
1897 }
1898 break;
1899 }
1900 if (candidate->hidden || // Hidden, or
1901 candidate->visited || // already processed, or
1902 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1903 (!loop_head_stack.empty() && // outside current loop.
1904 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1905 continue;
1906 }
1907
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001908 for (BasicBlockId pred_id : candidate->predecessors) {
1909 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1910 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001911 if (pred_bb != candidate && !pred_bb->visited &&
1912 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001913 candidate = nullptr; // Set candidate to null to indicate failure.
1914 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001915 }
1916 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001917 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001918 bb = candidate;
1919 break;
1920 }
1921 }
1922 // Compute blocks from which the loop head is reachable and process those blocks first.
1923 ArenaBitVector* reachable =
1924 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1925 loop_head_reachable_from[bb->id] = reachable;
1926 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1927 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1928 loop_head_stack.push_back(bb->id);
1929 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001930 }
1931
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001932 DCHECK_EQ(bb->hidden, false);
1933 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001934 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001935
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001936 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001937 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1938 topological_order_indexes_[bb->id] = idx;
1939 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001940
Vladimir Marko55fff042014-07-10 12:42:52 +01001941 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001942 ChildBlockIterator succIter(bb, this);
1943 BasicBlock* successor = succIter.Next();
1944 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001945 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001946 continue;
1947 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001948
Vladimir Marko55fff042014-07-10 12:42:52 +01001949 // One more predecessor was visited.
1950 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001951 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001952 if (loop_head_stack.empty() ||
1953 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1954 q.push(successor);
1955 } else {
1956 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1957 loop_exit_blocks.SetBit(successor->id);
1958 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001959 }
1960 }
1961 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001962
1963 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001964 topological_order_loop_head_stack_.clear();
1965 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01001966 max_nested_loops_ = max_nested_loops;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001967}
1968
1969bool BasicBlock::IsExceptionBlock() const {
1970 if (block_type == kExceptionHandling) {
1971 return true;
1972 }
1973 return false;
1974}
1975
Wei Jin04f4d8a2014-05-29 18:04:29 -07001976bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1977 BasicBlock* target = GetBasicBlock(target_id);
1978
1979 if (source == nullptr || target == nullptr)
1980 return false;
1981
1982 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001983 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1984 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07001985 if (bb == source)
1986 return true; // The block has been inserted by a suspend check before.
1987 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1988 return true;
1989 }
1990
1991 return false;
1992}
1993
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001994ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1995 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1996 visited_taken_(false), have_successors_(false) {
1997 // Check if we actually do have successors.
1998 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
1999 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002000 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002001 }
2002}
2003
2004BasicBlock* ChildBlockIterator::Next() {
2005 // We check if we have a basic block. If we don't we cannot get next child.
2006 if (basic_block_ == nullptr) {
2007 return nullptr;
2008 }
2009
2010 // If we haven't visited fallthrough, return that.
2011 if (visited_fallthrough_ == false) {
2012 visited_fallthrough_ = true;
2013
2014 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2015 if (result != nullptr) {
2016 return result;
2017 }
2018 }
2019
2020 // If we haven't visited taken, return that.
2021 if (visited_taken_ == false) {
2022 visited_taken_ = true;
2023
2024 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2025 if (result != nullptr) {
2026 return result;
2027 }
2028 }
2029
2030 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2031 if (have_successors_ == true) {
2032 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002033 auto end = basic_block_->successor_blocks.cend();
2034 while (successor_iter_ != end) {
2035 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2036 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002037 // If block was replaced by zero block, take next one.
2038 if (successor_block_info->block != NullBasicBlockId) {
2039 return mir_graph_->GetBasicBlock(successor_block_info->block);
2040 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002041 }
2042 }
2043
2044 // We do not have anything.
2045 return nullptr;
2046}
2047
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002048BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2049 MIRGraph* mir_graph = c_unit->mir_graph.get();
2050 return Copy(mir_graph);
2051}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002052
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002053BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2054 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002055
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002056 // We don't do a memcpy style copy here because it would lead to a lot of things
2057 // to clean up. Let us do it by hand instead.
2058 // Copy in taken and fallthrough.
2059 result_bb->fall_through = fall_through;
2060 result_bb->taken = taken;
2061
2062 // Copy successor links if needed.
2063 ArenaAllocator* arena = mir_graph->GetArena();
2064
2065 result_bb->successor_block_list_type = successor_block_list_type;
2066 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002067 result_bb->successor_blocks.reserve(successor_blocks.size());
2068 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2069 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2070 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002071 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002072 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002073 }
2074 }
2075
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002076 // Copy offset, method.
2077 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002078
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002079 // Now copy instructions.
2080 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2081 // Get a copy first.
2082 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002083
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002084 // Append it.
2085 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002086 }
2087
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002088 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002089}
2090
2091MIR* MIR::Copy(MIRGraph* mir_graph) {
2092 MIR* res = mir_graph->NewMIR();
2093 *res = *this;
2094
2095 // Remove links
2096 res->next = nullptr;
2097 res->bb = NullBasicBlockId;
2098 res->ssa_rep = nullptr;
2099
2100 return res;
2101}
2102
2103MIR* MIR::Copy(CompilationUnit* c_unit) {
2104 return Copy(c_unit->mir_graph.get());
2105}
2106
2107uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2108 // Default result.
2109 int res = 0;
2110
2111 // We are basically setting the iputs to their igets counterparts.
2112 switch (opcode) {
2113 case Instruction::IPUT:
2114 case Instruction::IPUT_OBJECT:
2115 case Instruction::IPUT_BOOLEAN:
2116 case Instruction::IPUT_BYTE:
2117 case Instruction::IPUT_CHAR:
2118 case Instruction::IPUT_SHORT:
2119 case Instruction::IPUT_QUICK:
2120 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002121 case Instruction::IPUT_BOOLEAN_QUICK:
2122 case Instruction::IPUT_BYTE_QUICK:
2123 case Instruction::IPUT_CHAR_QUICK:
2124 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002125 case Instruction::APUT:
2126 case Instruction::APUT_OBJECT:
2127 case Instruction::APUT_BOOLEAN:
2128 case Instruction::APUT_BYTE:
2129 case Instruction::APUT_CHAR:
2130 case Instruction::APUT_SHORT:
2131 case Instruction::SPUT:
2132 case Instruction::SPUT_OBJECT:
2133 case Instruction::SPUT_BOOLEAN:
2134 case Instruction::SPUT_BYTE:
2135 case Instruction::SPUT_CHAR:
2136 case Instruction::SPUT_SHORT:
2137 // Skip the VR containing what to store.
2138 res = 1;
2139 break;
2140 case Instruction::IPUT_WIDE:
2141 case Instruction::IPUT_WIDE_QUICK:
2142 case Instruction::APUT_WIDE:
2143 case Instruction::SPUT_WIDE:
2144 // Skip the two VRs containing what to store.
2145 res = 2;
2146 break;
2147 default:
2148 // Do nothing in the general case.
2149 break;
2150 }
2151
2152 return res;
2153}
2154
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002155/**
2156 * @brief Given a decoded instruction, it checks whether the instruction
2157 * sets a constant and if it does, more information is provided about the
2158 * constant being set.
2159 * @param ptr_value pointer to a 64-bit holder for the constant.
2160 * @param wide Updated by function whether a wide constant is being set by bytecode.
2161 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2162 */
2163bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2164 bool sets_const = true;
2165 int64_t value = vB;
2166
2167 DCHECK(ptr_value != nullptr);
2168 DCHECK(wide != nullptr);
2169
2170 switch (opcode) {
2171 case Instruction::CONST_4:
2172 case Instruction::CONST_16:
2173 case Instruction::CONST:
2174 *wide = false;
2175 value <<= 32; // In order to get the sign extend.
2176 value >>= 32;
2177 break;
2178 case Instruction::CONST_HIGH16:
2179 *wide = false;
2180 value <<= 48; // In order to get the sign extend.
2181 value >>= 32;
2182 break;
2183 case Instruction::CONST_WIDE_16:
2184 case Instruction::CONST_WIDE_32:
2185 *wide = true;
2186 value <<= 32; // In order to get the sign extend.
2187 value >>= 32;
2188 break;
2189 case Instruction::CONST_WIDE:
2190 *wide = true;
2191 value = vB_wide;
2192 break;
2193 case Instruction::CONST_WIDE_HIGH16:
2194 *wide = true;
2195 value <<= 48; // In order to get the sign extend.
2196 break;
2197 default:
2198 sets_const = false;
2199 break;
2200 }
2201
2202 if (sets_const) {
2203 *ptr_value = value;
2204 }
2205
2206 return sets_const;
2207}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002208
2209void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2210 // Reset flags for all MIRs in bb.
2211 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2212 mir->optimization_flags &= (~reset_flags);
2213 }
2214}
2215
Vladimir Marko312eb252014-10-07 15:01:57 +01002216void BasicBlock::Hide(MIRGraph* mir_graph) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002217 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2218 block_type = kDalvikByteCode;
2219
2220 // Mark it as hidden.
2221 hidden = true;
2222
2223 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2224 // are updated to know that they no longer have a parent.
2225 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2226 mir->bb = NullBasicBlockId;
2227 }
2228 first_mir_insn = nullptr;
2229 last_mir_insn = nullptr;
2230
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002231 for (BasicBlockId pred_id : predecessors) {
2232 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2233 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002234
2235 // Sadly we have to go through the children by hand here.
2236 pred_bb->ReplaceChild(id, NullBasicBlockId);
2237 }
2238
2239 // Iterate through children of bb we are hiding.
2240 ChildBlockIterator successorChildIter(this, mir_graph);
2241
2242 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002243 // Erase this predecessor from child.
2244 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002245 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002246
2247 // Remove link to children.
2248 taken = NullBasicBlockId;
2249 fall_through = NullBasicBlockId;
2250 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002251}
2252
Vladimir Marko312eb252014-10-07 15:01:57 +01002253/*
2254 * Kill an unreachable block and all blocks that become unreachable by killing this one.
2255 */
2256void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2257 DCHECK(predecessors.empty()); // Unreachable.
2258
2259 // Mark as dead and hidden.
2260 block_type = kDead;
2261 hidden = true;
2262
2263 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2264 // are updated to know that they no longer have a parent.
2265 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2266 mir->bb = NullBasicBlockId;
2267 }
2268 first_mir_insn = nullptr;
2269 last_mir_insn = nullptr;
2270
2271 data_flow_info = nullptr;
2272
2273 // Erase this bb from all children's predecessors and kill unreachable children.
2274 ChildBlockIterator iter(this, mir_graph);
2275 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2276 succ_bb->ErasePredecessor(id);
2277 if (succ_bb->predecessors.empty()) {
2278 succ_bb->KillUnreachable(mir_graph);
2279 }
2280 }
2281
2282 // Remove links to children.
2283 fall_through = NullBasicBlockId;
2284 taken = NullBasicBlockId;
2285 successor_block_list_type = kNotUsed;
2286
2287 if (kIsDebugBuild) {
2288 if (catch_entry) {
2289 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2290 mir_graph->catches_.erase(start_offset);
2291 }
2292 }
2293}
2294
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002295bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2296 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2297 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2298 // then it is not live out of this BB.
2299 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2300
2301 int last_ssa_reg = -1;
2302
2303 // Walk through the MIRs backwards.
2304 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2305 // Get ssa rep.
2306 SSARepresentation *ssa_rep = mir->ssa_rep;
2307
2308 // Go through the defines for this MIR.
2309 for (int i = 0; i < ssa_rep->num_defs; i++) {
2310 DCHECK(ssa_rep->defs != nullptr);
2311
2312 // Get the ssa reg.
2313 int def_ssa_reg = ssa_rep->defs[i];
2314
2315 // Get dalvik reg.
2316 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2317
2318 // Compare dalvik regs.
2319 if (dalvik_reg == def_dalvik_reg) {
2320 // We found a def of the register that we are being asked about.
2321 // Remember it.
2322 last_ssa_reg = def_ssa_reg;
2323 }
2324 }
2325 }
2326
2327 if (last_ssa_reg == -1) {
2328 // If we get to this point we couldn't find a define of register user asked about.
2329 // Let's assume the user knows what he's doing so we can be safe and say that if we
2330 // couldn't find a def, it is live out.
2331 return true;
2332 }
2333
2334 // If it is not -1, we found a match, is it ssa_reg?
2335 return (ssa_reg == last_ssa_reg);
2336}
2337
2338bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2339 // We need to check taken, fall_through, and successor_blocks to replace.
2340 bool found = false;
2341 if (taken == old_bb) {
2342 taken = new_bb;
2343 found = true;
2344 }
2345
2346 if (fall_through == old_bb) {
2347 fall_through = new_bb;
2348 found = true;
2349 }
2350
2351 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002352 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002353 if (successor_block_info->block == old_bb) {
2354 successor_block_info->block = new_bb;
2355 found = true;
2356 }
2357 }
2358 }
2359
2360 return found;
2361}
2362
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002363void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2364 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2365 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002366 // It's faster to move the back() to *pos than erase(pos).
2367 *pos = predecessors.back();
2368 predecessors.pop_back();
2369 size_t idx = std::distance(predecessors.begin(), pos);
2370 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2371 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2372 break;
2373 }
2374 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2375 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2376 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2377 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2378 mir->ssa_rep->num_uses = predecessors.size();
2379 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002380}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002381
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002382void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2383 DCHECK_NE(new_pred, NullBasicBlockId);
2384 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002385 DCHECK(pos != predecessors.end());
2386 *pos = new_pred;
2387 size_t idx = std::distance(predecessors.begin(), pos);
2388 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2389 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2390 break;
2391 }
2392 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2393 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002394 }
2395}
2396
2397// Create a new basic block with block_id as num_blocks_ that is
2398// post-incremented.
2399BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2400 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002401 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002402 return res;
2403}
2404
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002405void MIRGraph::CalculateBasicBlockInformation() {
2406 PassDriverMEPostOpt driver(cu_);
2407 driver.Launch();
2408}
2409
2410void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002411 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002412}
2413
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002414int MIR::DecodedInstruction::FlagsOf() const {
2415 // Calculate new index.
2416 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2417
2418 // Check if it is an extended or not.
2419 if (idx < 0) {
2420 return Instruction::FlagsOf(opcode);
2421 }
2422
2423 // For extended, we use a switch.
2424 switch (static_cast<int>(opcode)) {
2425 case kMirOpPhi:
2426 return Instruction::kContinue;
2427 case kMirOpCopy:
2428 return Instruction::kContinue;
2429 case kMirOpFusedCmplFloat:
2430 return Instruction::kContinue | Instruction::kBranch;
2431 case kMirOpFusedCmpgFloat:
2432 return Instruction::kContinue | Instruction::kBranch;
2433 case kMirOpFusedCmplDouble:
2434 return Instruction::kContinue | Instruction::kBranch;
2435 case kMirOpFusedCmpgDouble:
2436 return Instruction::kContinue | Instruction::kBranch;
2437 case kMirOpFusedCmpLong:
2438 return Instruction::kContinue | Instruction::kBranch;
2439 case kMirOpNop:
2440 return Instruction::kContinue;
2441 case kMirOpNullCheck:
2442 return Instruction::kContinue | Instruction::kThrow;
2443 case kMirOpRangeCheck:
2444 return Instruction::kContinue | Instruction::kThrow;
2445 case kMirOpDivZeroCheck:
2446 return Instruction::kContinue | Instruction::kThrow;
2447 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002448 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002449 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002450 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002451 case kMirOpSelect:
2452 return Instruction::kContinue;
2453 case kMirOpConstVector:
2454 return Instruction::kContinue;
2455 case kMirOpMoveVector:
2456 return Instruction::kContinue;
2457 case kMirOpPackedMultiply:
2458 return Instruction::kContinue;
2459 case kMirOpPackedAddition:
2460 return Instruction::kContinue;
2461 case kMirOpPackedSubtract:
2462 return Instruction::kContinue;
2463 case kMirOpPackedShiftLeft:
2464 return Instruction::kContinue;
2465 case kMirOpPackedSignedShiftRight:
2466 return Instruction::kContinue;
2467 case kMirOpPackedUnsignedShiftRight:
2468 return Instruction::kContinue;
2469 case kMirOpPackedAnd:
2470 return Instruction::kContinue;
2471 case kMirOpPackedOr:
2472 return Instruction::kContinue;
2473 case kMirOpPackedXor:
2474 return Instruction::kContinue;
2475 case kMirOpPackedAddReduce:
2476 return Instruction::kContinue;
2477 case kMirOpPackedReduce:
2478 return Instruction::kContinue;
2479 case kMirOpPackedSet:
2480 return Instruction::kContinue;
2481 case kMirOpReserveVectorRegisters:
2482 return Instruction::kContinue;
2483 case kMirOpReturnVectorRegisters:
2484 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002485 case kMirOpMemBarrier:
2486 return Instruction::kContinue;
2487 case kMirOpPackedArrayGet:
2488 return Instruction::kContinue | Instruction::kThrow;
2489 case kMirOpPackedArrayPut:
2490 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002491 default:
2492 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2493 return 0;
2494 }
2495}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002496} // namespace art