blob: ecd3ed833982d7193d49e78dc41512cdf11f7c7f [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_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100100 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800101 try_block_addr_(NULL),
102 entry_block_(NULL),
103 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800104 num_blocks_(0),
105 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100106 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100107 m_units_(arena->Adapter()),
108 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800109 current_method_(kInvalidEntry),
110 current_offset_(kInvalidEntry),
111 def_count_(0),
112 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700113 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100114 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700115 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700116 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
117 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700118 arena_(arena),
119 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800120 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800121 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700122 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
123 requested_backend_temp_(false),
124 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000125 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000126 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100127 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
128 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
129 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
130 gen_suspend_test_list_(arena->Adapter()) {
Vladimir Markof585e542014-11-21 13:41:32 +0000131 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100132 use_counts_.reserve(256);
133 raw_use_counts_.reserve(256);
134 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700135 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700136
137
138 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
139 // X86 requires a temp to keep track of the method address.
140 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
141 // this needs to be updated to reserve 0 temps for BE.
142 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
143 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
144 } else {
145 // Other architectures do not have a known lower bound for non-special temps.
146 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
147 max_available_non_special_compiler_temps_ = 0;
148 reserved_temps_for_backend_ = 0;
149 }
buzbee311ca162013-02-28 15:56:43 -0800150}
151
Ian Rogers6282dc12013-04-18 15:54:02 -0700152MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100153 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700154 STLDeleteElements(&m_units_);
155}
156
buzbee311ca162013-02-28 15:56:43 -0800157/*
158 * Parse an instruction, return the length of the instruction
159 */
Ian Rogers29a26482014-05-02 15:27:29 -0700160int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
161 const Instruction* inst = Instruction::At(code_ptr);
162 decoded_instruction->opcode = inst->Opcode();
163 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
164 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
165 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
166 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
167 if (inst->HasVarArgs()) {
168 inst->GetVarArgs(decoded_instruction->arg);
169 }
170 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800171}
172
173
174/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700175BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700176 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700177 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800178 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400179 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800180 while (insn) {
181 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700182 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800183 insn = insn->next;
184 }
185 if (insn == NULL) {
186 LOG(FATAL) << "Break split failed";
187 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400188 // Now insn is at the instruction where we want to split, namely
189 // insn will be the first instruction of the "bottom" block.
190 // Similarly, prev will be the last instruction of the "top" block
191
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100192 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800193
194 bottom_block->start_offset = code_offset;
195 bottom_block->first_mir_insn = insn;
196 bottom_block->last_mir_insn = orig_block->last_mir_insn;
197
Junmo Park90223cc2014-08-04 18:51:21 +0900198 /* If this block was terminated by a return, conditional branch or throw,
199 * the flag needs to go with the bottom block
200 */
buzbee311ca162013-02-28 15:56:43 -0800201 bottom_block->terminated_by_return = orig_block->terminated_by_return;
202 orig_block->terminated_by_return = false;
203
Junmo Park90223cc2014-08-04 18:51:21 +0900204 bottom_block->conditional_branch = orig_block->conditional_branch;
205 orig_block->conditional_branch = false;
206
207 bottom_block->explicit_throw = orig_block->explicit_throw;
208 orig_block->explicit_throw = false;
209
buzbee311ca162013-02-28 15:56:43 -0800210 /* Handle the taken path */
211 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700212 if (bottom_block->taken != NullBasicBlockId) {
213 orig_block->taken = NullBasicBlockId;
214 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100215 bb_taken->ErasePredecessor(orig_block->id);
216 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800217 }
218
219 /* Handle the fallthrough path */
220 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700221 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100222 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700223 if (bottom_block->fall_through != NullBasicBlockId) {
224 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100225 bb_fall_through->ErasePredecessor(orig_block->id);
226 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800227 }
228
229 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700230 if (orig_block->successor_block_list_type != kNotUsed) {
231 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100232 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700233 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100234 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
235 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700236 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700237 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100238 bb->ErasePredecessor(orig_block->id);
239 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700240 }
buzbee311ca162013-02-28 15:56:43 -0800241 }
242 }
243
buzbee0d829482013-10-11 15:24:55 -0700244 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700245 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800246
buzbee311ca162013-02-28 15:56:43 -0800247 /*
248 * Update the immediate predecessor block pointer so that outgoing edges
249 * can be applied to the proper block.
250 */
251 if (immed_pred_block_p) {
252 DCHECK_EQ(*immed_pred_block_p, orig_block);
253 *immed_pred_block_p = bottom_block;
254 }
buzbeeb48819d2013-09-14 16:15:25 -0700255
256 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000257 DCHECK(insn != nullptr);
258 DCHECK(insn != orig_block->first_mir_insn);
259 DCHECK(insn == bottom_block->first_mir_insn);
260 DCHECK_EQ(insn->offset, bottom_block->start_offset);
261 DCHECK(static_cast<int>(insn->dalvikInsn.opcode) == kMirOpCheck ||
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700262 !MIR::DecodedInstruction::IsPseudoMirOp(insn->dalvikInsn.opcode));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100263 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400264 // Scan the "bottom" instructions, remapping them to the
265 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000266 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400267 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100268 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000269 while (p != bottom_block->last_mir_insn) {
270 p = p->next;
271 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700272 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700273 int opcode = p->dalvikInsn.opcode;
274 /*
275 * Some messiness here to ensure that we only enter real opcodes and only the
276 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000277 * CHECK and work portions. Since the 2nd half of a split operation is always
278 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700279 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700280 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400281 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
282 // At first glance the instructions should all be mapped to orig_block.
283 // However, multiple instructions may correspond to the same dex, hence an earlier
284 // instruction may have already moved the mapping for dex to bottom_block.
285 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100286 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700287 }
buzbeeb48819d2013-09-14 16:15:25 -0700288 }
289
buzbee311ca162013-02-28 15:56:43 -0800290 return bottom_block;
291}
292
293/*
294 * Given a code offset, find out the block that starts with it. If the offset
295 * is in the middle of an existing block, split it into two. If immed_pred_block_p
296 * is not non-null and is the block being split, update *immed_pred_block_p to
297 * point to the bottom block so that outgoing edges can be set up properly
298 * (by the caller)
299 * Utilizes a map for fast lookup of the typical cases.
300 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700301BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700302 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700303 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700304 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800305 }
buzbeeb48819d2013-09-14 16:15:25 -0700306
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100307 int block_id = dex_pc_to_block_map_[code_offset];
308 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700309
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700310 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700311 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700312 return bb;
313 }
buzbee311ca162013-02-28 15:56:43 -0800314
buzbeeb48819d2013-09-14 16:15:25 -0700315 // No direct hit.
316 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700317 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800318 }
319
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700320 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700321 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700322 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700323 }
324
325 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100326 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800327 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100328 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800329 return bb;
330}
331
buzbeeb48819d2013-09-14 16:15:25 -0700332
buzbee311ca162013-02-28 15:56:43 -0800333/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700334void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800335 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700336 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800337
338 if (tries_size == 0) {
339 return;
340 }
341
342 for (int i = 0; i < tries_size; i++) {
343 const DexFile::TryItem* pTry =
344 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700345 DexOffset start_offset = pTry->start_addr_;
346 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800347 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700348 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800349 }
350 }
351
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700352 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700353 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800354 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
355 for (uint32_t idx = 0; idx < handlers_size; idx++) {
356 CatchHandlerIterator iterator(handlers_ptr);
357 for (; iterator.HasNext(); iterator.Next()) {
358 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700359 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800360 }
361 handlers_ptr = iterator.EndDataPointer();
362 }
363}
364
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100365bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
366 NarrowDexOffset catch_offset) {
367 // Catches for monitor-exit during stack unwinding have the pattern
368 // move-exception (move)* (goto)? monitor-exit throw
369 // In the currently generated dex bytecode we see these catching a bytecode range including
370 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
371 // it's the case for a given monitor-exit and catch block so that we can ignore it.
372 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
373 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
374 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700375 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100376 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
377 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700378 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100379 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
380 if (check_insn->VRegA_11x() == monitor_reg) {
381 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
382 return false;
383 }
384 check_insn = check_insn->Next();
385 while (true) {
386 int dest = -1;
387 bool wide = false;
388 switch (check_insn->Opcode()) {
389 case Instruction::MOVE_WIDE:
390 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700391 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100392 case Instruction::MOVE_OBJECT:
393 case Instruction::MOVE:
394 dest = check_insn->VRegA_12x();
395 break;
396
397 case Instruction::MOVE_WIDE_FROM16:
398 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700399 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100400 case Instruction::MOVE_OBJECT_FROM16:
401 case Instruction::MOVE_FROM16:
402 dest = check_insn->VRegA_22x();
403 break;
404
405 case Instruction::MOVE_WIDE_16:
406 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700407 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100408 case Instruction::MOVE_OBJECT_16:
409 case Instruction::MOVE_16:
410 dest = check_insn->VRegA_32x();
411 break;
412
413 case Instruction::GOTO:
414 case Instruction::GOTO_16:
415 case Instruction::GOTO_32:
416 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700417 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100418 default:
419 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
420 check_insn->VRegA_11x() == monitor_reg;
421 }
422
423 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
424 return false;
425 }
426
427 check_insn = check_insn->Next();
428 }
429}
430
buzbee311ca162013-02-28 15:56:43 -0800431/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700432BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
433 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700434 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700435 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800436 switch (insn->dalvikInsn.opcode) {
437 case Instruction::GOTO:
438 case Instruction::GOTO_16:
439 case Instruction::GOTO_32:
440 target += insn->dalvikInsn.vA;
441 break;
442 case Instruction::IF_EQ:
443 case Instruction::IF_NE:
444 case Instruction::IF_LT:
445 case Instruction::IF_GE:
446 case Instruction::IF_GT:
447 case Instruction::IF_LE:
448 cur_block->conditional_branch = true;
449 target += insn->dalvikInsn.vC;
450 break;
451 case Instruction::IF_EQZ:
452 case Instruction::IF_NEZ:
453 case Instruction::IF_LTZ:
454 case Instruction::IF_GEZ:
455 case Instruction::IF_GTZ:
456 case Instruction::IF_LEZ:
457 cur_block->conditional_branch = true;
458 target += insn->dalvikInsn.vB;
459 break;
460 default:
461 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
462 }
buzbeeb48819d2013-09-14 16:15:25 -0700463 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700464 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800465 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700466 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100467 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800468
469 /* Always terminate the current block for conditional branches */
470 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700471 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800472 /* create */
473 true,
474 /* immed_pred_block_p */
475 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700476 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100477 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800478 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700479 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800480 }
481 return cur_block;
482}
483
484/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800485BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
486 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700487 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800488 const uint16_t* switch_data =
489 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
490 int size;
491 const int* keyTable;
492 const int* target_table;
493 int i;
494 int first_key;
495
496 /*
497 * Packed switch data format:
498 * ushort ident = 0x0100 magic value
499 * ushort size number of entries in the table
500 * int first_key first (and lowest) switch case value
501 * int targets[size] branch targets, relative to switch opcode
502 *
503 * Total size is (4+size*2) 16-bit code units.
504 */
505 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
506 DCHECK_EQ(static_cast<int>(switch_data[0]),
507 static_cast<int>(Instruction::kPackedSwitchSignature));
508 size = switch_data[1];
509 first_key = switch_data[2] | (switch_data[3] << 16);
510 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700511 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800512 /*
513 * Sparse switch data format:
514 * ushort ident = 0x0200 magic value
515 * ushort size number of entries in the table; > 0
516 * int keys[size] keys, sorted low-to-high; 32-bit aligned
517 * int targets[size] branch targets, relative to switch opcode
518 *
519 * Total size is (2+size*4) 16-bit code units.
520 */
521 } else {
522 DCHECK_EQ(static_cast<int>(switch_data[0]),
523 static_cast<int>(Instruction::kSparseSwitchSignature));
524 size = switch_data[1];
525 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
526 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700527 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800528 }
529
buzbee0d829482013-10-11 15:24:55 -0700530 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800531 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700532 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800533 }
buzbee0d829482013-10-11 15:24:55 -0700534 cur_block->successor_block_list_type =
535 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100536 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800537
538 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700539 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
540 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700541 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700542 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000543 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700544 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800545 successor_block_info->key =
546 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
547 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100548 cur_block->successor_blocks.push_back(successor_block_info);
549 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800550 }
551
552 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700553 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
554 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700555 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100556 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800557 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800558}
559
560/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700561BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
562 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700563 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700564 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700565 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800566 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800567
568 /* In try block */
569 if (in_try_block) {
570 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
571
buzbee0d829482013-10-11 15:24:55 -0700572 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800573 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
574 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700575 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800576 }
577
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700578 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700579 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
580 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100581 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
582 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
583 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
584 continue;
585 }
586 if (cur_block->successor_block_list_type == kNotUsed) {
587 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100588 }
buzbee311ca162013-02-28 15:56:43 -0800589 catch_block->catch_entry = true;
590 if (kIsDebugBuild) {
591 catches_.insert(catch_block->start_offset);
592 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700593 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000594 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700595 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800596 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100597 cur_block->successor_blocks.push_back(successor_block_info);
598 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800599 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100600 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
601 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100602 bool build_all_edges =
603 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100604 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100605 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700606 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800607 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100608 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800609 }
610
buzbee17189ac2013-11-08 11:07:02 -0800611 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800612 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700613 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700614 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700615 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800616 }
617 if (!in_try_block) {
618 // Don't split a THROW that can't rethrow - we're done.
619 return cur_block;
620 }
621 }
622
buzbee17189ac2013-11-08 11:07:02 -0800623 if (!build_all_edges) {
624 /*
625 * Even though there is an exception edge here, control cannot return to this
626 * method. Thus, for the purposes of dataflow analysis and optimization, we can
627 * ignore the edge. Doing this reduces compile time, and increases the scope
628 * of the basic-block level optimization pass.
629 */
630 return cur_block;
631 }
632
buzbee311ca162013-02-28 15:56:43 -0800633 /*
634 * Split the potentially-throwing instruction into two parts.
635 * The first half will be a pseudo-op that captures the exception
636 * edges and terminates the basic block. It always falls through.
637 * Then, create a new basic block that begins with the throwing instruction
638 * (minus exceptions). Note: this new basic block must NOT be entered into
639 * the block_map. If the potentially-throwing instruction is the target of a
640 * future branch, we need to find the check psuedo half. The new
641 * basic block containing the work portion of the instruction should
642 * only be entered via fallthrough from the block containing the
643 * pseudo exception edge MIR. Note also that this new block is
644 * not automatically terminated after the work portion, and may
645 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700646 *
647 * Note also that the dex_pc_to_block_map_ entry for the potentially
648 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800649 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100650 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800651 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700652 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100653 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700654 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800655 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700656 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700657 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800658 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700659 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800660 return new_block;
661}
662
663/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
664void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700665 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700666 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800667 current_code_item_ = code_item;
668 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
669 current_method_ = m_units_.size();
670 current_offset_ = 0;
671 // TODO: will need to snapshot stack image and use that as the mir context identification.
672 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000673 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
674 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800675 const uint16_t* code_ptr = current_code_item_->insns_;
676 const uint16_t* code_end =
677 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
678
679 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700680 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100681 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
682 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 -0700683
buzbee311ca162013-02-28 15:56:43 -0800684 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700685 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
686 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800687
688 // If this is the first method, set up default entry and exit blocks.
689 if (current_method_ == 0) {
690 DCHECK(entry_block_ == NULL);
691 DCHECK(exit_block_ == NULL);
Andreas Gampe44395962014-06-13 13:44:40 -0700692 DCHECK_EQ(num_blocks_, 0U);
buzbee0d829482013-10-11 15:24:55 -0700693 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100694 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700695 DCHECK_EQ(null_block->id, NullBasicBlockId);
696 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100697 entry_block_ = CreateNewBB(kEntryBlock);
698 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800699 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
700 cu_->dex_file = &dex_file;
701 cu_->class_def_idx = class_def_idx;
702 cu_->method_idx = method_idx;
703 cu_->access_flags = access_flags;
704 cu_->invoke_type = invoke_type;
705 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800706 } else {
707 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
708 /*
709 * Will need to manage storage for ins & outs, push prevous state and update
710 * insert point.
711 */
712 }
713
714 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100715 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700716 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800717 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700718 // TODO: for inlining support, insert at the insert point rather than entry block.
719 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100720 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800721
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000722 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800723 ProcessTryCatchBlocks();
724
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000725 uint64_t merged_df_flags = 0u;
726
buzbee311ca162013-02-28 15:56:43 -0800727 /* Parse all instructions and put them into containing basic blocks */
728 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700729 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800730 insn->offset = current_offset_;
731 insn->m_unit_index = current_method_;
732 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800733 Instruction::Code opcode = insn->dalvikInsn.opcode;
734 if (opcode_count_ != NULL) {
735 opcode_count_[static_cast<int>(opcode)]++;
736 }
737
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700738 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800739 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800740
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700741 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000742 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800743
744 if (df_flags & DF_HAS_DEFS) {
745 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
746 }
747
buzbee1da1e2f2013-11-15 13:37:01 -0800748 if (df_flags & DF_LVN) {
749 cur_block->use_lvn = true; // Run local value numbering on this basic block.
750 }
751
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700752 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700753 if (opcode == Instruction::NOP) {
754 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
755 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
756 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
757 uint16_t following_raw_instruction = code_ptr[1];
758 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
759 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
760 (following_raw_instruction == Instruction::kArrayDataSignature)) {
761 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
762 }
763 }
764 if (width == 1) {
765 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700766 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700767 } else {
buzbee0d829482013-10-11 15:24:55 -0700768 DCHECK(cur_block->fall_through == NullBasicBlockId);
769 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee27247762013-07-28 12:03:58 -0700770 // Unreachable instruction, mark for no continuation.
771 flags &= ~Instruction::kContinue;
772 }
773 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700774 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700775 }
776
buzbeeb48819d2013-09-14 16:15:25 -0700777 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100778 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700779
buzbee27247762013-07-28 12:03:58 -0700780 code_ptr += width;
781
buzbee311ca162013-02-28 15:56:43 -0800782 if (flags & Instruction::kBranch) {
783 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
784 width, flags, code_ptr, code_end);
785 } else if (flags & Instruction::kReturn) {
786 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700787 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100788 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800789 /*
790 * Terminate the current block if there are instructions
791 * afterwards.
792 */
793 if (code_ptr < code_end) {
794 /*
795 * Create a fallthrough block for real instructions
796 * (incl. NOP).
797 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700798 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800799 }
800 } else if (flags & Instruction::kThrow) {
801 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
802 code_ptr, code_end);
803 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800804 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800805 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700806 if (verify_flags & Instruction::kVerifyVarArgRange ||
807 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800808 /*
809 * The Quick backend's runtime model includes a gap between a method's
810 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
811 * which spans the gap is somewhat complicated, and should not happen
812 * in normal usage of dx. Punt to the interpreter.
813 */
814 int first_reg_in_range = insn->dalvikInsn.vC;
815 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
816 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
817 punt_to_interpreter_ = true;
818 }
819 }
buzbee311ca162013-02-28 15:56:43 -0800820 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700821 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
822 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800823 if (next_block) {
824 /*
825 * The next instruction could be the target of a previously parsed
826 * forward branch so a block is already created. If the current
827 * instruction is not an unconditional branch, connect them through
828 * the fall-through link.
829 */
buzbee0d829482013-10-11 15:24:55 -0700830 DCHECK(cur_block->fall_through == NullBasicBlockId ||
831 GetBasicBlock(cur_block->fall_through) == next_block ||
832 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800833
buzbee0d829482013-10-11 15:24:55 -0700834 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
835 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100836 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800837 }
838 cur_block = next_block;
839 }
840 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000841 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000842
buzbee311ca162013-02-28 15:56:43 -0800843 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
844 DumpCFG("/sdcard/1_post_parse_cfg/", true);
845 }
846
847 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700848 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800849 }
850}
851
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700852void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800853 DCHECK(opcode_count_ != NULL);
854 LOG(INFO) << "Opcode Count";
855 for (int i = 0; i < kNumPackedOpcodes; i++) {
856 if (opcode_count_[i] != 0) {
857 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
858 << " " << opcode_count_[i];
859 }
860 }
861}
862
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700863uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
864 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
865 return oat_data_flow_attributes_[opcode];
866}
867
868uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
869 DCHECK(mir != nullptr);
870 Instruction::Code opcode = mir->dalvikInsn.opcode;
871 return GetDataFlowAttributes(opcode);
872}
873
buzbee311ca162013-02-28 15:56:43 -0800874// TODO: use a configurable base prefix, and adjust callers to supply pass name.
875/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800876void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800877 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700878 static AtomicInteger cnt(0);
879
880 // Increment counter to get a unique file number.
881 cnt++;
882
buzbee311ca162013-02-28 15:56:43 -0800883 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
884 ReplaceSpecialChars(fname);
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700885 fname = StringPrintf("%s%s%x%s_%d.dot", dir_prefix, fname.c_str(),
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800886 GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700887 suffix == nullptr ? "" : suffix,
888 cnt.LoadRelaxed());
buzbee311ca162013-02-28 15:56:43 -0800889 file = fopen(fname.c_str(), "w");
890 if (file == NULL) {
891 return;
892 }
893 fprintf(file, "digraph G {\n");
894
895 fprintf(file, " rankdir=TB\n");
896
897 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
898 int idx;
899
900 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100901 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700902 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700903 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800904 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700905 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800906 if (bb->block_type == kEntryBlock) {
907 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
908 } else if (bb->block_type == kExitBlock) {
909 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
910 } else if (bb->block_type == kDalvikByteCode) {
911 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
912 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700913 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800914 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
915 bb->first_mir_insn ? " | " : " ");
916 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
917 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800918 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400919 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700920 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
921 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400922 extended_mir_op_names_[opcode - kMirOpFirst],
923 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
924 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700925 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700926 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700927 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100928 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
929 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800930 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400931 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800932 }
933 fprintf(file, " }\"];\n\n");
934 } else if (bb->block_type == kExceptionHandling) {
935 char block_name[BLOCK_NAME_LEN];
936
937 GetBlockName(bb, block_name);
938 fprintf(file, " %s [shape=invhouse];\n", block_name);
939 }
940
941 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
942
buzbee0d829482013-10-11 15:24:55 -0700943 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800944 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700945 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800946 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
947 block_name1, block_name2);
948 }
buzbee0d829482013-10-11 15:24:55 -0700949 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800950 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700951 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800952 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
953 }
954
buzbee0d829482013-10-11 15:24:55 -0700955 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800956 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
957 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700958 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800959
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100960 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800961 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100962 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700963 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800964 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100965 succ_id,
buzbee311ca162013-02-28 15:56:43 -0800966 successor_block_info->key,
967 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100968 (succ_id != last_succ_id) ? " | " : " ");
969 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -0800970 }
971 fprintf(file, " }\"];\n\n");
972
973 GetBlockName(bb, block_name1);
974 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
975 block_name1, bb->start_offset, bb->id);
976
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700977 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700978 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100979 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700980 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -0800981
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700982 GetBlockName(dest_block, block_name2);
983 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
984 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -0800985 }
986 }
987 fprintf(file, "\n");
988
989 if (cu_->verbose) {
990 /* Display the dominator tree */
991 GetBlockName(bb, block_name1);
992 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
993 block_name1, block_name1);
994 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -0700995 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800996 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
997 }
998 }
999 }
1000 fprintf(file, "}\n");
1001 fclose(file);
1002}
1003
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001004/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001005void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001006 // Insert it after the last MIR.
1007 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001008}
1009
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001010void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1011 // Insert it after the last MIR.
1012 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1013}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001014
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001015void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1016 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1017 MIR* new_mir = *it;
1018
1019 // Add a copy of each MIR.
1020 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1021 }
buzbee1fd33462013-03-25 13:40:45 -07001022}
1023
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001024/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001025void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001026 InsertMIRListAfter(current_mir, new_mir, new_mir);
1027}
buzbee1fd33462013-03-25 13:40:45 -07001028
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001029void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1030 // If no MIR, we are done.
1031 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1032 return;
buzbee1fd33462013-03-25 13:40:45 -07001033 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001034
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001035 // If insert_after is null, assume BB is empty.
1036 if (insert_after == nullptr) {
1037 first_mir_insn = first_list_mir;
1038 last_mir_insn = last_list_mir;
1039 last_list_mir->next = nullptr;
1040 } else {
1041 MIR* after_list = insert_after->next;
1042 insert_after->next = first_list_mir;
1043 last_list_mir->next = after_list;
1044 if (after_list == nullptr) {
1045 last_mir_insn = last_list_mir;
1046 }
1047 }
1048
1049 // Set this BB to be the basic block of the MIRs.
1050 MIR* last = last_list_mir->next;
1051 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1052 mir->bb = id;
1053 }
1054}
1055
1056/* Insert an MIR instruction to the head of a basic block. */
1057void BasicBlock::PrependMIR(MIR* mir) {
1058 InsertMIRListBefore(first_mir_insn, mir, mir);
1059}
1060
1061void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1062 // Insert it before the first MIR.
1063 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1064}
1065
1066void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1067 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1068 MIR* mir = *it;
1069
1070 InsertMIRListBefore(first_mir_insn, mir, mir);
1071 }
1072}
1073
1074/* Insert a MIR instruction before the specified MIR. */
1075void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1076 // Insert as a single element list.
1077 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001078}
1079
1080MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1081 MIR* current = first_mir_insn;
1082
1083 while (current != nullptr) {
1084 MIR* next = current->next;
1085
1086 if (next == mir) {
1087 return current;
1088 }
1089
1090 current = next;
1091 }
1092
1093 return nullptr;
1094}
1095
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001096void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1097 // If no MIR, we are done.
1098 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1099 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001100 }
1101
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001102 // If insert_before is null, assume BB is empty.
1103 if (insert_before == nullptr) {
1104 first_mir_insn = first_list_mir;
1105 last_mir_insn = last_list_mir;
1106 last_list_mir->next = nullptr;
1107 } else {
1108 if (first_mir_insn == insert_before) {
1109 last_list_mir->next = first_mir_insn;
1110 first_mir_insn = first_list_mir;
1111 } else {
1112 // Find the preceding MIR.
1113 MIR* before_list = FindPreviousMIR(insert_before);
1114 DCHECK(before_list != nullptr);
1115 before_list->next = first_list_mir;
1116 last_list_mir->next = insert_before;
1117 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001118 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001119
1120 // Set this BB to be the basic block of the MIRs.
1121 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1122 mir->bb = id;
1123 }
1124}
1125
1126bool BasicBlock::RemoveMIR(MIR* mir) {
1127 // Remove as a single element list.
1128 return RemoveMIRList(mir, mir);
1129}
1130
1131bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1132 if (first_list_mir == nullptr) {
1133 return false;
1134 }
1135
1136 // Try to find the MIR.
1137 MIR* before_list = nullptr;
1138 MIR* after_list = nullptr;
1139
1140 // If we are removing from the beginning of the MIR list.
1141 if (first_mir_insn == first_list_mir) {
1142 before_list = nullptr;
1143 } else {
1144 before_list = FindPreviousMIR(first_list_mir);
1145 if (before_list == nullptr) {
1146 // We did not find the mir.
1147 return false;
1148 }
1149 }
1150
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001151 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001152 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001153 mir->bb = NullBasicBlockId;
1154 }
1155
1156 after_list = last_list_mir->next;
1157
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001158 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001159 if (before_list == nullptr) {
1160 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001161 } else {
1162 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001163 }
1164
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001165 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001166 if (after_list == nullptr) {
1167 last_mir_insn = before_list;
1168 }
1169
1170 return true;
buzbee1fd33462013-03-25 13:40:45 -07001171}
1172
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001173MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001174 MIR* next_mir = nullptr;
1175
1176 if (current != nullptr) {
1177 next_mir = current->next;
1178 }
1179
1180 if (next_mir == nullptr) {
1181 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001182 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1183 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001184 }
1185 }
1186
1187 return next_mir;
1188}
1189
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001190static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1191 DCHECK(decoded_mir != nullptr);
1192 OpSize type = static_cast<OpSize>(type_size >> 16);
1193 uint16_t vect_size = (type_size & 0xFFFF);
1194
1195 // Now print the type and vector size.
1196 std::stringstream ss;
1197 ss << " (type:";
1198 ss << type;
1199 ss << " vectsize:";
1200 ss << vect_size;
1201 ss << ")";
1202
1203 decoded_mir->append(ss.str());
1204}
1205
1206void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1207 DCHECK(decoded_mir != nullptr);
1208 int opcode = mir->dalvikInsn.opcode;
1209 SSARepresentation* ssa_rep = mir->ssa_rep;
1210 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1211 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1212
Vladimirf41b92c2014-10-13 13:41:38 +07001213 if (opcode < kMirOpFirst) {
1214 return; // It is not an extended instruction.
1215 }
1216
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001217 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1218
1219 switch (opcode) {
1220 case kMirOpPhi: {
1221 if (defs > 0 && uses > 0) {
1222 BasicBlockId* incoming = mir->meta.phi_incoming;
1223 decoded_mir->append(StringPrintf(" %s = (%s",
1224 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1225 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1226 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1227 for (int i = 1; i < uses; i++) {
1228 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1229 }
1230 decoded_mir->append(")");
1231 }
1232 break;
1233 }
1234 case kMirOpCopy:
1235 if (ssa_rep != nullptr) {
1236 decoded_mir->append(" ");
1237 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1238 if (defs > 1) {
1239 decoded_mir->append(", ");
1240 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1241 }
1242 decoded_mir->append(" = ");
1243 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1244 if (uses > 1) {
1245 decoded_mir->append(", ");
1246 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1247 }
1248 } else {
1249 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1250 }
1251 break;
1252 case kMirOpFusedCmplFloat:
1253 case kMirOpFusedCmpgFloat:
1254 case kMirOpFusedCmplDouble:
1255 case kMirOpFusedCmpgDouble:
1256 case kMirOpFusedCmpLong:
1257 if (ssa_rep != nullptr) {
1258 decoded_mir->append(" ");
1259 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1260 for (int i = 1; i < uses; i++) {
1261 decoded_mir->append(", ");
1262 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1263 }
1264 } else {
1265 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1266 }
1267 break;
1268 case kMirOpMoveVector:
1269 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1270 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1271 break;
1272 case kMirOpPackedAddition:
1273 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1274 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1275 break;
1276 case kMirOpPackedMultiply:
1277 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1278 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1279 break;
1280 case kMirOpPackedSubtract:
1281 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1282 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1283 break;
1284 case kMirOpPackedAnd:
1285 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1286 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1287 break;
1288 case kMirOpPackedOr:
1289 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1290 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1291 break;
1292 case kMirOpPackedXor:
1293 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1294 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1295 break;
1296 case kMirOpPackedShiftLeft:
1297 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1298 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1299 break;
1300 case kMirOpPackedUnsignedShiftRight:
1301 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1302 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1303 break;
1304 case kMirOpPackedSignedShiftRight:
1305 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1306 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1307 break;
1308 case kMirOpConstVector:
1309 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1310 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1311 break;
1312 case kMirOpPackedSet:
1313 if (ssa_rep != nullptr) {
1314 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1315 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1316 if (uses > 1) {
1317 decoded_mir->append(", ");
1318 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1319 }
1320 } else {
1321 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1322 }
1323 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1324 break;
1325 case kMirOpPackedAddReduce:
1326 if (ssa_rep != nullptr) {
1327 decoded_mir->append(" ");
1328 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1329 if (defs > 1) {
1330 decoded_mir->append(", ");
1331 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1332 }
1333 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1334 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1335 if (uses > 1) {
1336 decoded_mir->append(", ");
1337 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1338 }
1339 } else {
1340 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1341 }
1342 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1343 break;
1344 case kMirOpPackedReduce:
1345 if (ssa_rep != nullptr) {
1346 decoded_mir->append(" ");
1347 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1348 if (defs > 1) {
1349 decoded_mir->append(", ");
1350 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1351 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001352 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001353 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001354 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1355 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001356 }
1357 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1358 break;
1359 case kMirOpReserveVectorRegisters:
1360 case kMirOpReturnVectorRegisters:
1361 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1362 break;
1363 case kMirOpMemBarrier: {
1364 decoded_mir->append(" type:");
1365 std::stringstream ss;
1366 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1367 decoded_mir->append(ss.str());
1368 break;
1369 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001370 case kMirOpPackedArrayGet:
1371 case kMirOpPackedArrayPut:
1372 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1373 if (ssa_rep != nullptr) {
1374 decoded_mir->append(StringPrintf(", %s[%s]",
1375 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1376 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1377 } else {
1378 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1379 }
1380 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1381 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001382 default:
1383 break;
1384 }
1385}
1386
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001387char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001388 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001389 std::string str;
1390 int flags = 0;
1391 int opcode = insn.opcode;
1392 char* ret;
1393 bool nop = false;
1394 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001395 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001396
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001397 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001398 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1399 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1400 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001401 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001402 insn = mir->meta.throw_insn->dalvikInsn;
1403 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001404 opcode = insn.opcode;
1405 } else if (opcode == kMirOpNop) {
1406 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001407 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1408 // Recover original opcode.
1409 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1410 opcode = insn.opcode;
1411 }
buzbee1fd33462013-03-25 13:40:45 -07001412 nop = true;
1413 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001414 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1415 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001416
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001417 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001418 // Note that this does not check the MIR's opcode in all cases. In cases where it
1419 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1420 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001421 } else {
1422 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001423 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001424 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001425
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001426 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001427 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1428 (dalvik_format == Instruction::k3rc));
1429 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001430 str.append(" ");
1431 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1432 if (defs > 1) {
1433 str.append(", ");
1434 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1435 }
buzbee1fd33462013-03-25 13:40:45 -07001436 if (uses != 0) {
1437 str.append(", ");
1438 }
1439 }
1440 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001441 str.append(" ");
1442 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001443 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1444 // For the listing, skip the high sreg.
1445 i++;
1446 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001447 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001448 str.append(",");
1449 }
1450 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001451
buzbee1fd33462013-03-25 13:40:45 -07001452 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001453 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001454 case Instruction::k21s:
1455 case Instruction::k31i:
1456 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001457 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001458 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001459 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001460 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001461 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001462 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001463 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001464 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001465 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001466 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001467 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001468 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001469 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001470 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001471 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001472 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001473 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001474 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001475 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001476 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001477
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001478 if ((flags & Instruction::kBranch) != 0) {
1479 // For branches, decode the instructions to print out the branch targets.
1480 int offset = 0;
1481 switch (dalvik_format) {
1482 case Instruction::k21t:
1483 offset = insn.vB;
1484 break;
1485 case Instruction::k22t:
1486 offset = insn.vC;
1487 break;
1488 case Instruction::k10t:
1489 case Instruction::k20t:
1490 case Instruction::k30t:
1491 offset = insn.vA;
1492 break;
1493 default:
1494 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001495 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001496 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001497 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001498 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1499 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001500
1501 if (nop) {
1502 str.append("]--optimized away");
1503 }
buzbee1fd33462013-03-25 13:40:45 -07001504 }
1505 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001506 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001507 strncpy(ret, str.c_str(), length);
1508 return ret;
1509}
1510
1511/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001512void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001513 static const struct { const char before; const char after; } match[] = {
1514 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1515 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1516 };
buzbee1fd33462013-03-25 13:40:45 -07001517 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1518 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1519 }
1520}
1521
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001522std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001523 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1524 // the arena. We should be smarter and just place straight into the arena, or compute the
1525 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001526 int vreg = SRegToVReg(ssa_reg);
1527 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1528 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1529 } else {
1530 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1531 }
buzbee1fd33462013-03-25 13:40:45 -07001532}
1533
1534// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001535std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001536 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001537 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001538 return GetSSAName(ssa_reg);
1539 }
1540 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001541 if (!singles_only && reg_location_[ssa_reg].wide &&
1542 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001543 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001544 ConstantValueWide(reg_location_[ssa_reg]));
1545 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001546 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001547 ConstantValue(reg_location_[ssa_reg]));
1548 }
1549 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001550 int vreg = SRegToVReg(ssa_reg);
1551 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1552 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1553 } else {
1554 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1555 }
buzbee1fd33462013-03-25 13:40:45 -07001556 }
1557}
1558
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001559void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001560 switch (bb->block_type) {
1561 case kEntryBlock:
1562 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1563 break;
1564 case kExitBlock:
1565 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1566 break;
1567 case kDalvikByteCode:
1568 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1569 break;
1570 case kExceptionHandling:
1571 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1572 bb->id);
1573 break;
1574 default:
1575 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1576 break;
1577 }
1578}
1579
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001580const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001581 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001582 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1583 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1584}
1585
1586/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001587void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001588 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001589 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001590 "Entry Block",
1591 "Code Block",
1592 "Exit Block",
1593 "Exception Handling",
1594 "Catch Block"
1595 };
1596
1597 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001598 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001599 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001600
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001601 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001602 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1603 bb->id,
1604 block_type_names[bb->block_type],
1605 bb->start_offset,
1606 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1607 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001608 if (bb->taken != NullBasicBlockId) {
1609 LOG(INFO) << " Taken branch: block " << bb->taken
1610 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001611 }
buzbee0d829482013-10-11 15:24:55 -07001612 if (bb->fall_through != NullBasicBlockId) {
1613 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1614 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001615 }
1616 }
1617}
1618
1619/*
1620 * Build an array of location records for the incoming arguments.
1621 * Note: one location record per word of arguments, with dummy
1622 * high-word loc for wide arguments. Also pull up any following
1623 * MOVE_RESULT and incorporate it into the invoke.
1624 */
1625CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001626 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001627 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001628 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001629 MIR* move_result_mir = FindMoveResult(bb, mir);
1630 if (move_result_mir == NULL) {
1631 info->result.location = kLocInvalid;
1632 } else {
1633 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001634 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1635 }
1636 info->num_arg_words = mir->ssa_rep->num_uses;
1637 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001638 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001639 for (int i = 0; i < info->num_arg_words; i++) {
1640 info->args[i] = GetRawSrc(mir, i);
1641 }
1642 info->opt_flags = mir->optimization_flags;
1643 info->type = type;
1644 info->is_range = is_range;
1645 info->index = mir->dalvikInsn.vB;
1646 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001647 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001648 return info;
1649}
1650
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001651// Allocate a new MIR.
1652MIR* MIRGraph::NewMIR() {
1653 MIR* mir = new (arena_) MIR();
1654 return mir;
1655}
1656
buzbee862a7602013-04-05 10:58:54 -07001657// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001658BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001659 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001660
buzbee862a7602013-04-05 10:58:54 -07001661 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001662 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001663 block_id_map_.Put(block_id, block_id);
1664 return bb;
1665}
buzbee1fd33462013-03-25 13:40:45 -07001666
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001667void MIRGraph::InitializeConstantPropagation() {
1668 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001669 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001670}
1671
1672void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001673 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001674 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001675 use_counts_.clear();
1676 use_counts_.reserve(num_ssa_regs + 32);
1677 use_counts_.resize(num_ssa_regs, 0u);
1678 raw_use_counts_.clear();
1679 raw_use_counts_.reserve(num_ssa_regs + 32);
1680 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001681}
1682
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001683void MIRGraph::SSATransformationStart() {
1684 DCHECK(temp_scoped_alloc_.get() == nullptr);
1685 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001686 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1687 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1688 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001689}
1690
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001691void MIRGraph::SSATransformationEnd() {
1692 // Verify the dataflow information after the pass.
1693 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1694 VerifyDataflow();
1695 }
1696
Vladimir Markof585e542014-11-21 13:41:32 +00001697 temp_.ssa.num_vregs = 0u;
1698 temp_.ssa.work_live_vregs = nullptr;
1699 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001700 DCHECK(temp_scoped_alloc_.get() != nullptr);
1701 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001702
1703 // Update the maximum number of reachable blocks.
1704 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001705}
1706
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001707size_t MIRGraph::GetNumDalvikInsns() const {
1708 size_t cumulative_size = 0u;
1709 bool counted_current_item = false;
1710 const uint8_t size_for_null_code_item = 2u;
1711
1712 for (auto it : m_units_) {
1713 const DexFile::CodeItem* code_item = it->GetCodeItem();
1714 // Even if the code item is null, we still count non-zero value so that
1715 // each m_unit is counted as having impact.
1716 cumulative_size += (code_item == nullptr ?
1717 size_for_null_code_item : code_item->insns_size_in_code_units_);
1718 if (code_item == current_code_item_) {
1719 counted_current_item = true;
1720 }
1721 }
1722
1723 // If the current code item was not counted yet, count it now.
1724 // This can happen for example in unit tests where some fields like m_units_
1725 // are not initialized.
1726 if (counted_current_item == false) {
1727 cumulative_size += (current_code_item_ == nullptr ?
1728 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1729 }
1730
1731 return cumulative_size;
1732}
1733
Vladimir Marko55fff042014-07-10 12:42:52 +01001734static BasicBlock* SelectTopologicalSortOrderFallBack(
1735 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1736 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1737 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1738 // No true loop head has been found but there may be true loop heads after the mess we need
1739 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1740 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1741 BasicBlock* fall_back = nullptr;
1742 size_t fall_back_num_reachable = 0u;
1743 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1744 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1745 AllNodesIterator iter(mir_graph);
1746 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1747 if (candidate->hidden || // Hidden, or
1748 candidate->visited || // already processed, or
1749 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1750 (current_loop != nullptr && // outside current loop.
1751 !current_loop->IsBitSet(candidate->id))) {
1752 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001753 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001754 DCHECK(tmp_stack->empty());
1755 tmp_stack->push_back(candidate->id);
1756 candidate_reachable.ClearAllBits();
1757 size_t num_reachable = 0u;
1758 while (!tmp_stack->empty()) {
1759 BasicBlockId current_id = tmp_stack->back();
1760 tmp_stack->pop_back();
1761 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1762 DCHECK(current_bb != nullptr);
1763 ChildBlockIterator child_iter(current_bb, mir_graph);
1764 BasicBlock* child_bb = child_iter.Next();
1765 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1766 DCHECK(!child_bb->hidden);
1767 if (child_bb->visited || // Already processed, or
1768 (current_loop != nullptr && // outside current loop.
1769 !current_loop->IsBitSet(child_bb->id))) {
1770 continue;
1771 }
1772 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1773 candidate_reachable.SetBit(child_bb->id);
1774 tmp_stack->push_back(child_bb->id);
1775 num_reachable += 1u;
1776 }
1777 }
1778 }
1779 if (fall_back_num_reachable < num_reachable) {
1780 fall_back_num_reachable = num_reachable;
1781 fall_back = candidate;
1782 }
1783 }
1784 return fall_back;
1785}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001786
Vladimir Marko55fff042014-07-10 12:42:52 +01001787// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1788static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1789 ArenaBitVector* reachable,
1790 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1791 // NOTE: Loop heads indicated by the "visited" flag.
1792 DCHECK(tmp_stack->empty());
1793 reachable->ClearAllBits();
1794 tmp_stack->push_back(bb_id);
1795 while (!tmp_stack->empty()) {
1796 BasicBlockId current_id = tmp_stack->back();
1797 tmp_stack->pop_back();
1798 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1799 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001800 for (BasicBlockId pred_id : current_bb->predecessors) {
1801 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1802 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001803 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1804 reachable->SetBit(pred_bb->id);
1805 tmp_stack->push_back(pred_bb->id);
1806 }
1807 }
1808 }
1809}
1810
1811void MIRGraph::ComputeTopologicalSortOrder() {
1812 ScopedArenaAllocator allocator(&cu_->arena_stack);
1813 unsigned int num_blocks = GetNumBlocks();
1814
1815 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1816 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1817 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1818 size_t max_nested_loops = 0u;
1819 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1820 loop_exit_blocks.ClearAllBits();
1821
1822 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001823 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001824 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001825 if (bb->hidden == true) {
1826 continue;
1827 }
1828
Vladimir Marko55fff042014-07-10 12:42:52 +01001829 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001830
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001831 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001832 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001833 q.push(bb);
1834 }
1835 }
1836
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001837 // Clear the topological order arrays.
1838 topological_order_.clear();
1839 topological_order_.reserve(num_blocks);
1840 topological_order_loop_ends_.clear();
1841 topological_order_loop_ends_.resize(num_blocks, 0u);
1842 topological_order_indexes_.clear();
1843 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001844
1845 // Mark all blocks as unvisited.
1846 ClearAllVisitedFlags();
1847
1848 // For loop heads, keep track from which blocks they are reachable not going through other
1849 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1850 // in this set go into the loop body, the other children are jumping over the loop.
1851 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1852 loop_head_reachable_from.resize(num_blocks, nullptr);
1853 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1854 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1855
1856 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001857 BasicBlock* bb = nullptr;
1858 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001859 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001860 // Get top.
1861 bb = q.front();
1862 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001863 if (bb->visited) {
1864 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1865 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001866 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1867 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001868 DCHECK_EQ(loop_head_stack.back(), bb->id);
1869 loop_head_stack.pop_back();
1870 ArenaBitVector* reachable =
1871 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1872 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1873 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1874 q.push(GetBasicBlock(candidate_id));
1875 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1876 // so clearing the bit has no effect on the iterator.
1877 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001878 }
1879 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001880 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001881 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001882 } else {
1883 // Find the new loop head.
1884 AllNodesIterator iter(this);
1885 while (true) {
1886 BasicBlock* candidate = iter.Next();
1887 if (candidate == nullptr) {
1888 // We did not find a true loop head, fall back to a reachable block in any loop.
1889 ArenaBitVector* current_loop =
1890 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1891 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1892 &allocator, &tmp_stack);
1893 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1894 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1895 LOG(INFO) << "Topological sort order: Using fall-back in "
1896 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1897 << " @0x" << std::hex << bb->start_offset
1898 << ", num_blocks = " << std::dec << num_blocks;
1899 }
1900 break;
1901 }
1902 if (candidate->hidden || // Hidden, or
1903 candidate->visited || // already processed, or
1904 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1905 (!loop_head_stack.empty() && // outside current loop.
1906 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1907 continue;
1908 }
1909
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001910 for (BasicBlockId pred_id : candidate->predecessors) {
1911 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1912 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001913 if (pred_bb != candidate && !pred_bb->visited &&
1914 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001915 candidate = nullptr; // Set candidate to null to indicate failure.
1916 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001917 }
1918 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001919 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001920 bb = candidate;
1921 break;
1922 }
1923 }
1924 // Compute blocks from which the loop head is reachable and process those blocks first.
1925 ArenaBitVector* reachable =
1926 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
1927 loop_head_reachable_from[bb->id] = reachable;
1928 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
1929 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
1930 loop_head_stack.push_back(bb->id);
1931 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001932 }
1933
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001934 DCHECK_EQ(bb->hidden, false);
1935 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001936 bb->visited = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001937
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001938 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001939 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1940 topological_order_indexes_[bb->id] = idx;
1941 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001942
Vladimir Marko55fff042014-07-10 12:42:52 +01001943 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001944 ChildBlockIterator succIter(bb, this);
1945 BasicBlock* successor = succIter.Next();
1946 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001947 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001948 continue;
1949 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001950
Vladimir Marko55fff042014-07-10 12:42:52 +01001951 // One more predecessor was visited.
1952 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001953 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001954 if (loop_head_stack.empty() ||
1955 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
1956 q.push(successor);
1957 } else {
1958 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
1959 loop_exit_blocks.SetBit(successor->id);
1960 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001961 }
1962 }
1963 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001964
1965 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001966 topological_order_loop_head_stack_.clear();
1967 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01001968 max_nested_loops_ = max_nested_loops;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001969}
1970
1971bool BasicBlock::IsExceptionBlock() const {
1972 if (block_type == kExceptionHandling) {
1973 return true;
1974 }
1975 return false;
1976}
1977
Wei Jin04f4d8a2014-05-29 18:04:29 -07001978bool MIRGraph::HasSuspendTestBetween(BasicBlock* source, BasicBlockId target_id) {
1979 BasicBlock* target = GetBasicBlock(target_id);
1980
1981 if (source == nullptr || target == nullptr)
1982 return false;
1983
1984 int idx;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001985 for (idx = gen_suspend_test_list_.size() - 1; idx >= 0; idx--) {
1986 BasicBlock* bb = gen_suspend_test_list_[idx];
Wei Jin04f4d8a2014-05-29 18:04:29 -07001987 if (bb == source)
1988 return true; // The block has been inserted by a suspend check before.
1989 if (source->dominators->IsBitSet(bb->id) && bb->dominators->IsBitSet(target_id))
1990 return true;
1991 }
1992
1993 return false;
1994}
1995
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07001996ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
1997 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
1998 visited_taken_(false), have_successors_(false) {
1999 // Check if we actually do have successors.
2000 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2001 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002002 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002003 }
2004}
2005
2006BasicBlock* ChildBlockIterator::Next() {
2007 // We check if we have a basic block. If we don't we cannot get next child.
2008 if (basic_block_ == nullptr) {
2009 return nullptr;
2010 }
2011
2012 // If we haven't visited fallthrough, return that.
2013 if (visited_fallthrough_ == false) {
2014 visited_fallthrough_ = true;
2015
2016 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2017 if (result != nullptr) {
2018 return result;
2019 }
2020 }
2021
2022 // If we haven't visited taken, return that.
2023 if (visited_taken_ == false) {
2024 visited_taken_ = true;
2025
2026 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2027 if (result != nullptr) {
2028 return result;
2029 }
2030 }
2031
2032 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2033 if (have_successors_ == true) {
2034 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002035 auto end = basic_block_->successor_blocks.cend();
2036 while (successor_iter_ != end) {
2037 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2038 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002039 // If block was replaced by zero block, take next one.
2040 if (successor_block_info->block != NullBasicBlockId) {
2041 return mir_graph_->GetBasicBlock(successor_block_info->block);
2042 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002043 }
2044 }
2045
2046 // We do not have anything.
2047 return nullptr;
2048}
2049
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002050BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2051 MIRGraph* mir_graph = c_unit->mir_graph.get();
2052 return Copy(mir_graph);
2053}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002054
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002055BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2056 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002057
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002058 // We don't do a memcpy style copy here because it would lead to a lot of things
2059 // to clean up. Let us do it by hand instead.
2060 // Copy in taken and fallthrough.
2061 result_bb->fall_through = fall_through;
2062 result_bb->taken = taken;
2063
2064 // Copy successor links if needed.
2065 ArenaAllocator* arena = mir_graph->GetArena();
2066
2067 result_bb->successor_block_list_type = successor_block_list_type;
2068 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002069 result_bb->successor_blocks.reserve(successor_blocks.size());
2070 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2071 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2072 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002073 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002074 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002075 }
2076 }
2077
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002078 // Copy offset, method.
2079 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002080
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002081 // Now copy instructions.
2082 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2083 // Get a copy first.
2084 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002085
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002086 // Append it.
2087 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002088 }
2089
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002090 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002091}
2092
2093MIR* MIR::Copy(MIRGraph* mir_graph) {
2094 MIR* res = mir_graph->NewMIR();
2095 *res = *this;
2096
2097 // Remove links
2098 res->next = nullptr;
2099 res->bb = NullBasicBlockId;
2100 res->ssa_rep = nullptr;
2101
2102 return res;
2103}
2104
2105MIR* MIR::Copy(CompilationUnit* c_unit) {
2106 return Copy(c_unit->mir_graph.get());
2107}
2108
2109uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2110 // Default result.
2111 int res = 0;
2112
2113 // We are basically setting the iputs to their igets counterparts.
2114 switch (opcode) {
2115 case Instruction::IPUT:
2116 case Instruction::IPUT_OBJECT:
2117 case Instruction::IPUT_BOOLEAN:
2118 case Instruction::IPUT_BYTE:
2119 case Instruction::IPUT_CHAR:
2120 case Instruction::IPUT_SHORT:
2121 case Instruction::IPUT_QUICK:
2122 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002123 case Instruction::IPUT_BOOLEAN_QUICK:
2124 case Instruction::IPUT_BYTE_QUICK:
2125 case Instruction::IPUT_CHAR_QUICK:
2126 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002127 case Instruction::APUT:
2128 case Instruction::APUT_OBJECT:
2129 case Instruction::APUT_BOOLEAN:
2130 case Instruction::APUT_BYTE:
2131 case Instruction::APUT_CHAR:
2132 case Instruction::APUT_SHORT:
2133 case Instruction::SPUT:
2134 case Instruction::SPUT_OBJECT:
2135 case Instruction::SPUT_BOOLEAN:
2136 case Instruction::SPUT_BYTE:
2137 case Instruction::SPUT_CHAR:
2138 case Instruction::SPUT_SHORT:
2139 // Skip the VR containing what to store.
2140 res = 1;
2141 break;
2142 case Instruction::IPUT_WIDE:
2143 case Instruction::IPUT_WIDE_QUICK:
2144 case Instruction::APUT_WIDE:
2145 case Instruction::SPUT_WIDE:
2146 // Skip the two VRs containing what to store.
2147 res = 2;
2148 break;
2149 default:
2150 // Do nothing in the general case.
2151 break;
2152 }
2153
2154 return res;
2155}
2156
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002157/**
2158 * @brief Given a decoded instruction, it checks whether the instruction
2159 * sets a constant and if it does, more information is provided about the
2160 * constant being set.
2161 * @param ptr_value pointer to a 64-bit holder for the constant.
2162 * @param wide Updated by function whether a wide constant is being set by bytecode.
2163 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2164 */
2165bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2166 bool sets_const = true;
2167 int64_t value = vB;
2168
2169 DCHECK(ptr_value != nullptr);
2170 DCHECK(wide != nullptr);
2171
2172 switch (opcode) {
2173 case Instruction::CONST_4:
2174 case Instruction::CONST_16:
2175 case Instruction::CONST:
2176 *wide = false;
2177 value <<= 32; // In order to get the sign extend.
2178 value >>= 32;
2179 break;
2180 case Instruction::CONST_HIGH16:
2181 *wide = false;
2182 value <<= 48; // In order to get the sign extend.
2183 value >>= 32;
2184 break;
2185 case Instruction::CONST_WIDE_16:
2186 case Instruction::CONST_WIDE_32:
2187 *wide = true;
2188 value <<= 32; // In order to get the sign extend.
2189 value >>= 32;
2190 break;
2191 case Instruction::CONST_WIDE:
2192 *wide = true;
2193 value = vB_wide;
2194 break;
2195 case Instruction::CONST_WIDE_HIGH16:
2196 *wide = true;
2197 value <<= 48; // In order to get the sign extend.
2198 break;
2199 default:
2200 sets_const = false;
2201 break;
2202 }
2203
2204 if (sets_const) {
2205 *ptr_value = value;
2206 }
2207
2208 return sets_const;
2209}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002210
2211void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2212 // Reset flags for all MIRs in bb.
2213 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2214 mir->optimization_flags &= (~reset_flags);
2215 }
2216}
2217
Vladimir Marko312eb252014-10-07 15:01:57 +01002218void BasicBlock::Hide(MIRGraph* mir_graph) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002219 // First lets make it a dalvik bytecode block so it doesn't have any special meaning.
2220 block_type = kDalvikByteCode;
2221
2222 // Mark it as hidden.
2223 hidden = true;
2224
2225 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2226 // are updated to know that they no longer have a parent.
2227 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2228 mir->bb = NullBasicBlockId;
2229 }
2230 first_mir_insn = nullptr;
2231 last_mir_insn = nullptr;
2232
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002233 for (BasicBlockId pred_id : predecessors) {
2234 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2235 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002236
2237 // Sadly we have to go through the children by hand here.
2238 pred_bb->ReplaceChild(id, NullBasicBlockId);
2239 }
2240
2241 // Iterate through children of bb we are hiding.
2242 ChildBlockIterator successorChildIter(this, mir_graph);
2243
2244 for (BasicBlock* childPtr = successorChildIter.Next(); childPtr != 0; childPtr = successorChildIter.Next()) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002245 // Erase this predecessor from child.
2246 childPtr->ErasePredecessor(id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002247 }
Jean Christophe Beylerf588b502014-06-18 14:14:15 -07002248
2249 // Remove link to children.
2250 taken = NullBasicBlockId;
2251 fall_through = NullBasicBlockId;
2252 successor_block_list_type = kNotUsed;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002253}
2254
Vladimir Marko312eb252014-10-07 15:01:57 +01002255/*
2256 * Kill an unreachable block and all blocks that become unreachable by killing this one.
2257 */
2258void BasicBlock::KillUnreachable(MIRGraph* mir_graph) {
2259 DCHECK(predecessors.empty()); // Unreachable.
2260
2261 // Mark as dead and hidden.
2262 block_type = kDead;
2263 hidden = true;
2264
2265 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2266 // are updated to know that they no longer have a parent.
2267 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2268 mir->bb = NullBasicBlockId;
2269 }
2270 first_mir_insn = nullptr;
2271 last_mir_insn = nullptr;
2272
2273 data_flow_info = nullptr;
2274
2275 // Erase this bb from all children's predecessors and kill unreachable children.
2276 ChildBlockIterator iter(this, mir_graph);
2277 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2278 succ_bb->ErasePredecessor(id);
2279 if (succ_bb->predecessors.empty()) {
2280 succ_bb->KillUnreachable(mir_graph);
2281 }
2282 }
2283
2284 // Remove links to children.
2285 fall_through = NullBasicBlockId;
2286 taken = NullBasicBlockId;
2287 successor_block_list_type = kNotUsed;
2288
2289 if (kIsDebugBuild) {
2290 if (catch_entry) {
2291 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2292 mir_graph->catches_.erase(start_offset);
2293 }
2294 }
2295}
2296
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002297bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2298 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2299 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2300 // then it is not live out of this BB.
2301 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2302
2303 int last_ssa_reg = -1;
2304
2305 // Walk through the MIRs backwards.
2306 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2307 // Get ssa rep.
2308 SSARepresentation *ssa_rep = mir->ssa_rep;
2309
2310 // Go through the defines for this MIR.
2311 for (int i = 0; i < ssa_rep->num_defs; i++) {
2312 DCHECK(ssa_rep->defs != nullptr);
2313
2314 // Get the ssa reg.
2315 int def_ssa_reg = ssa_rep->defs[i];
2316
2317 // Get dalvik reg.
2318 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2319
2320 // Compare dalvik regs.
2321 if (dalvik_reg == def_dalvik_reg) {
2322 // We found a def of the register that we are being asked about.
2323 // Remember it.
2324 last_ssa_reg = def_ssa_reg;
2325 }
2326 }
2327 }
2328
2329 if (last_ssa_reg == -1) {
2330 // If we get to this point we couldn't find a define of register user asked about.
2331 // Let's assume the user knows what he's doing so we can be safe and say that if we
2332 // couldn't find a def, it is live out.
2333 return true;
2334 }
2335
2336 // If it is not -1, we found a match, is it ssa_reg?
2337 return (ssa_reg == last_ssa_reg);
2338}
2339
2340bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2341 // We need to check taken, fall_through, and successor_blocks to replace.
2342 bool found = false;
2343 if (taken == old_bb) {
2344 taken = new_bb;
2345 found = true;
2346 }
2347
2348 if (fall_through == old_bb) {
2349 fall_through = new_bb;
2350 found = true;
2351 }
2352
2353 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002354 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002355 if (successor_block_info->block == old_bb) {
2356 successor_block_info->block = new_bb;
2357 found = true;
2358 }
2359 }
2360 }
2361
2362 return found;
2363}
2364
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002365void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2366 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2367 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002368 // It's faster to move the back() to *pos than erase(pos).
2369 *pos = predecessors.back();
2370 predecessors.pop_back();
2371 size_t idx = std::distance(predecessors.begin(), pos);
2372 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2373 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2374 break;
2375 }
2376 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2377 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2378 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2379 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2380 mir->ssa_rep->num_uses = predecessors.size();
2381 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002382}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002383
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002384void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2385 DCHECK_NE(new_pred, NullBasicBlockId);
2386 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002387 DCHECK(pos != predecessors.end());
2388 *pos = new_pred;
2389 size_t idx = std::distance(predecessors.begin(), pos);
2390 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2391 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2392 break;
2393 }
2394 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2395 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002396 }
2397}
2398
2399// Create a new basic block with block_id as num_blocks_ that is
2400// post-incremented.
2401BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
2402 BasicBlock* res = NewMemBB(block_type, num_blocks_++);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002403 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002404 return res;
2405}
2406
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002407void MIRGraph::CalculateBasicBlockInformation() {
2408 PassDriverMEPostOpt driver(cu_);
2409 driver.Launch();
2410}
2411
2412void MIRGraph::InitializeBasicBlockData() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002413 num_blocks_ = block_list_.size();
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002414}
2415
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002416int MIR::DecodedInstruction::FlagsOf() const {
2417 // Calculate new index.
2418 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2419
2420 // Check if it is an extended or not.
2421 if (idx < 0) {
2422 return Instruction::FlagsOf(opcode);
2423 }
2424
2425 // For extended, we use a switch.
2426 switch (static_cast<int>(opcode)) {
2427 case kMirOpPhi:
2428 return Instruction::kContinue;
2429 case kMirOpCopy:
2430 return Instruction::kContinue;
2431 case kMirOpFusedCmplFloat:
2432 return Instruction::kContinue | Instruction::kBranch;
2433 case kMirOpFusedCmpgFloat:
2434 return Instruction::kContinue | Instruction::kBranch;
2435 case kMirOpFusedCmplDouble:
2436 return Instruction::kContinue | Instruction::kBranch;
2437 case kMirOpFusedCmpgDouble:
2438 return Instruction::kContinue | Instruction::kBranch;
2439 case kMirOpFusedCmpLong:
2440 return Instruction::kContinue | Instruction::kBranch;
2441 case kMirOpNop:
2442 return Instruction::kContinue;
2443 case kMirOpNullCheck:
2444 return Instruction::kContinue | Instruction::kThrow;
2445 case kMirOpRangeCheck:
2446 return Instruction::kContinue | Instruction::kThrow;
2447 case kMirOpDivZeroCheck:
2448 return Instruction::kContinue | Instruction::kThrow;
2449 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002450 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002451 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002452 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002453 case kMirOpSelect:
2454 return Instruction::kContinue;
2455 case kMirOpConstVector:
2456 return Instruction::kContinue;
2457 case kMirOpMoveVector:
2458 return Instruction::kContinue;
2459 case kMirOpPackedMultiply:
2460 return Instruction::kContinue;
2461 case kMirOpPackedAddition:
2462 return Instruction::kContinue;
2463 case kMirOpPackedSubtract:
2464 return Instruction::kContinue;
2465 case kMirOpPackedShiftLeft:
2466 return Instruction::kContinue;
2467 case kMirOpPackedSignedShiftRight:
2468 return Instruction::kContinue;
2469 case kMirOpPackedUnsignedShiftRight:
2470 return Instruction::kContinue;
2471 case kMirOpPackedAnd:
2472 return Instruction::kContinue;
2473 case kMirOpPackedOr:
2474 return Instruction::kContinue;
2475 case kMirOpPackedXor:
2476 return Instruction::kContinue;
2477 case kMirOpPackedAddReduce:
2478 return Instruction::kContinue;
2479 case kMirOpPackedReduce:
2480 return Instruction::kContinue;
2481 case kMirOpPackedSet:
2482 return Instruction::kContinue;
2483 case kMirOpReserveVectorRegisters:
2484 return Instruction::kContinue;
2485 case kMirOpReturnVectorRegisters:
2486 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002487 case kMirOpMemBarrier:
2488 return Instruction::kContinue;
2489 case kMirOpPackedArrayGet:
2490 return Instruction::kContinue | Instruction::kThrow;
2491 case kMirOpPackedArrayPut:
2492 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002493 default:
2494 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2495 return 0;
2496 }
2497}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002498} // namespace art