blob: abd34820abd0683263b85872e523cc78cb2c3f63 [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>
Andreas Gampecee97e52014-12-19 15:30:11 -080021#include <unistd.h>
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000022
Ian Rogerse77493c2014-08-20 15:08:45 -070023#include "base/bit_vector-inl.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070024#include "base/stl_util.h"
buzbee311ca162013-02-28 15:56:43 -080025#include "compiler_internals.h"
buzbee311ca162013-02-28 15:56:43 -080026#include "dex_file-inl.h"
Ian Rogers29a26482014-05-02 15:27:29 -070027#include "dex_instruction-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010028#include "dex/global_value_numbering.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000029#include "dex/quick/dex_file_to_method_inliner_map.h"
30#include "dex/quick/dex_file_method_inliner.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000031#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070032#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070033#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010034#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000035
buzbee311ca162013-02-28 15:56:43 -080036namespace art {
37
38#define MAX_PATTERN_LEN 5
39
buzbee1fd33462013-03-25 13:40:45 -070040const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
41 "Phi",
42 "Copy",
43 "FusedCmplFloat",
44 "FusedCmpgFloat",
45 "FusedCmplDouble",
46 "FusedCmpgDouble",
47 "FusedCmpLong",
48 "Nop",
49 "OpNullCheck",
50 "OpRangeCheck",
51 "OpDivZeroCheck",
52 "Check1",
53 "Check2",
54 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040055 "ConstVector",
56 "MoveVector",
57 "PackedMultiply",
58 "PackedAddition",
59 "PackedSubtract",
60 "PackedShiftLeft",
61 "PackedSignedShiftRight",
62 "PackedUnsignedShiftRight",
63 "PackedAnd",
64 "PackedOr",
65 "PackedXor",
66 "PackedAddReduce",
67 "PackedReduce",
68 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070069 "ReserveVectorRegisters",
70 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070071 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070072 "PackedArrayGet",
73 "PackedArrayPut",
Ningsheng Jiana262f772014-11-25 16:48:07 +080074 "MaddInt",
75 "MsubInt",
76 "MaddLong",
77 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070078};
79
buzbee862a7602013-04-05 10:58:54 -070080MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070081 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010082 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070083 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010084 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
85 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
Vladimir Marko1c6ea442014-12-19 18:11:35 +000086 vreg_to_ssa_map_(NULL),
87 ssa_last_defs_(NULL),
buzbee311ca162013-02-28 15:56:43 -080088 is_constant_v_(NULL),
89 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010090 use_counts_(arena->Adapter()),
91 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080092 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070093 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010094 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000095 domination_up_to_date_(false),
96 mir_ssa_rep_up_to_date_(false),
97 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010098 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
99 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
100 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
101 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
102 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
103 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
104 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100105 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -0800106 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000107 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100108 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800109 try_block_addr_(NULL),
110 entry_block_(NULL),
111 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800112 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100113 dex_pc_to_block_map_(arena->Adapter()),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100114 m_units_(arena->Adapter()),
115 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800116 current_method_(kInvalidEntry),
117 current_offset_(kInvalidEntry),
118 def_count_(0),
119 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700120 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100121 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700122 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700123 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
124 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700125 arena_(arena),
126 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800127 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800128 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700129 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
130 requested_backend_temp_(false),
131 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000132 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000133 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100134 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
135 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
136 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
Vladimir Marko8b858e12014-11-27 14:52:37 +0000137 suspend_checks_in_loops_(nullptr) {
Vladimir Markof585e542014-11-21 13:41:32 +0000138 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100139 use_counts_.reserve(256);
140 raw_use_counts_.reserve(256);
141 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700142 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700143
144
145 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
146 // X86 requires a temp to keep track of the method address.
147 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
148 // this needs to be updated to reserve 0 temps for BE.
149 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
150 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
151 } else {
152 // Other architectures do not have a known lower bound for non-special temps.
153 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
154 max_available_non_special_compiler_temps_ = 0;
155 reserved_temps_for_backend_ = 0;
156 }
buzbee311ca162013-02-28 15:56:43 -0800157}
158
Ian Rogers6282dc12013-04-18 15:54:02 -0700159MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100160 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700161 STLDeleteElements(&m_units_);
162}
163
buzbee311ca162013-02-28 15:56:43 -0800164/*
165 * Parse an instruction, return the length of the instruction
166 */
Ian Rogers29a26482014-05-02 15:27:29 -0700167int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
168 const Instruction* inst = Instruction::At(code_ptr);
169 decoded_instruction->opcode = inst->Opcode();
170 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
171 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
172 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
173 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
174 if (inst->HasVarArgs()) {
175 inst->GetVarArgs(decoded_instruction->arg);
176 }
177 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800178}
179
180
181/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700182BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700183 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700184 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800185 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400186 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800187 while (insn) {
188 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700189 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800190 insn = insn->next;
191 }
192 if (insn == NULL) {
193 LOG(FATAL) << "Break split failed";
194 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400195 // Now insn is at the instruction where we want to split, namely
196 // insn will be the first instruction of the "bottom" block.
197 // Similarly, prev will be the last instruction of the "top" block
198
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100199 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800200
201 bottom_block->start_offset = code_offset;
202 bottom_block->first_mir_insn = insn;
203 bottom_block->last_mir_insn = orig_block->last_mir_insn;
204
Junmo Park90223cc2014-08-04 18:51:21 +0900205 /* If this block was terminated by a return, conditional branch or throw,
206 * the flag needs to go with the bottom block
207 */
buzbee311ca162013-02-28 15:56:43 -0800208 bottom_block->terminated_by_return = orig_block->terminated_by_return;
209 orig_block->terminated_by_return = false;
210
Junmo Park90223cc2014-08-04 18:51:21 +0900211 bottom_block->conditional_branch = orig_block->conditional_branch;
212 orig_block->conditional_branch = false;
213
214 bottom_block->explicit_throw = orig_block->explicit_throw;
215 orig_block->explicit_throw = false;
216
buzbee311ca162013-02-28 15:56:43 -0800217 /* Handle the taken path */
218 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700219 if (bottom_block->taken != NullBasicBlockId) {
220 orig_block->taken = NullBasicBlockId;
221 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100222 bb_taken->ErasePredecessor(orig_block->id);
223 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800224 }
225
226 /* Handle the fallthrough path */
227 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700228 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100229 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700230 if (bottom_block->fall_through != NullBasicBlockId) {
231 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100232 bb_fall_through->ErasePredecessor(orig_block->id);
233 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800234 }
235
236 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700237 if (orig_block->successor_block_list_type != kNotUsed) {
238 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100239 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700240 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100241 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
242 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700243 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700244 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100245 bb->ErasePredecessor(orig_block->id);
246 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700247 }
buzbee311ca162013-02-28 15:56:43 -0800248 }
249 }
250
buzbee0d829482013-10-11 15:24:55 -0700251 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700252 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800253
buzbee311ca162013-02-28 15:56:43 -0800254 /*
255 * Update the immediate predecessor block pointer so that outgoing edges
256 * can be applied to the proper block.
257 */
258 if (immed_pred_block_p) {
259 DCHECK_EQ(*immed_pred_block_p, orig_block);
260 *immed_pred_block_p = bottom_block;
261 }
buzbeeb48819d2013-09-14 16:15:25 -0700262
263 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000264 DCHECK(insn != nullptr);
265 DCHECK(insn != orig_block->first_mir_insn);
266 DCHECK(insn == bottom_block->first_mir_insn);
267 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100268 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400269 // Scan the "bottom" instructions, remapping them to the
270 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000271 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400272 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100273 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000274 while (p != bottom_block->last_mir_insn) {
275 p = p->next;
276 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700277 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700278 int opcode = p->dalvikInsn.opcode;
279 /*
280 * Some messiness here to ensure that we only enter real opcodes and only the
281 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000282 * CHECK and work portions. Since the 2nd half of a split operation is always
283 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700284 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700285 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400286 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
287 // At first glance the instructions should all be mapped to orig_block.
288 // However, multiple instructions may correspond to the same dex, hence an earlier
289 // instruction may have already moved the mapping for dex to bottom_block.
290 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100291 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700292 }
buzbeeb48819d2013-09-14 16:15:25 -0700293 }
294
buzbee311ca162013-02-28 15:56:43 -0800295 return bottom_block;
296}
297
298/*
299 * Given a code offset, find out the block that starts with it. If the offset
300 * is in the middle of an existing block, split it into two. If immed_pred_block_p
301 * is not non-null and is the block being split, update *immed_pred_block_p to
302 * point to the bottom block so that outgoing edges can be set up properly
303 * (by the caller)
304 * Utilizes a map for fast lookup of the typical cases.
305 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700306BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700307 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700308 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700309 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800310 }
buzbeeb48819d2013-09-14 16:15:25 -0700311
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100312 int block_id = dex_pc_to_block_map_[code_offset];
313 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700314
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700315 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700316 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700317 return bb;
318 }
buzbee311ca162013-02-28 15:56:43 -0800319
buzbeeb48819d2013-09-14 16:15:25 -0700320 // No direct hit.
321 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700322 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800323 }
324
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700325 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700326 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700327 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700328 }
329
330 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100331 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800332 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100333 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800334 return bb;
335}
336
buzbeeb48819d2013-09-14 16:15:25 -0700337
buzbee311ca162013-02-28 15:56:43 -0800338/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700339void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800340 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700341 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800342
343 if (tries_size == 0) {
344 return;
345 }
346
347 for (int i = 0; i < tries_size; i++) {
348 const DexFile::TryItem* pTry =
349 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700350 DexOffset start_offset = pTry->start_addr_;
351 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800352 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700353 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800354 }
355 }
356
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700357 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700358 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800359 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
360 for (uint32_t idx = 0; idx < handlers_size; idx++) {
361 CatchHandlerIterator iterator(handlers_ptr);
362 for (; iterator.HasNext(); iterator.Next()) {
363 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700364 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800365 }
366 handlers_ptr = iterator.EndDataPointer();
367 }
368}
369
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100370bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
371 NarrowDexOffset catch_offset) {
372 // Catches for monitor-exit during stack unwinding have the pattern
373 // move-exception (move)* (goto)? monitor-exit throw
374 // In the currently generated dex bytecode we see these catching a bytecode range including
375 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
376 // it's the case for a given monitor-exit and catch block so that we can ignore it.
377 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
378 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
379 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700380 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100381 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
382 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700383 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100384 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
385 if (check_insn->VRegA_11x() == monitor_reg) {
386 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
387 return false;
388 }
389 check_insn = check_insn->Next();
390 while (true) {
391 int dest = -1;
392 bool wide = false;
393 switch (check_insn->Opcode()) {
394 case Instruction::MOVE_WIDE:
395 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700396 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100397 case Instruction::MOVE_OBJECT:
398 case Instruction::MOVE:
399 dest = check_insn->VRegA_12x();
400 break;
401
402 case Instruction::MOVE_WIDE_FROM16:
403 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700404 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100405 case Instruction::MOVE_OBJECT_FROM16:
406 case Instruction::MOVE_FROM16:
407 dest = check_insn->VRegA_22x();
408 break;
409
410 case Instruction::MOVE_WIDE_16:
411 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700412 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100413 case Instruction::MOVE_OBJECT_16:
414 case Instruction::MOVE_16:
415 dest = check_insn->VRegA_32x();
416 break;
417
418 case Instruction::GOTO:
419 case Instruction::GOTO_16:
420 case Instruction::GOTO_32:
421 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700422 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100423 default:
424 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
425 check_insn->VRegA_11x() == monitor_reg;
426 }
427
428 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
429 return false;
430 }
431
432 check_insn = check_insn->Next();
433 }
434}
435
buzbee311ca162013-02-28 15:56:43 -0800436/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700437BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
438 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700439 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700440 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800441 switch (insn->dalvikInsn.opcode) {
442 case Instruction::GOTO:
443 case Instruction::GOTO_16:
444 case Instruction::GOTO_32:
445 target += insn->dalvikInsn.vA;
446 break;
447 case Instruction::IF_EQ:
448 case Instruction::IF_NE:
449 case Instruction::IF_LT:
450 case Instruction::IF_GE:
451 case Instruction::IF_GT:
452 case Instruction::IF_LE:
453 cur_block->conditional_branch = true;
454 target += insn->dalvikInsn.vC;
455 break;
456 case Instruction::IF_EQZ:
457 case Instruction::IF_NEZ:
458 case Instruction::IF_LTZ:
459 case Instruction::IF_GEZ:
460 case Instruction::IF_GTZ:
461 case Instruction::IF_LEZ:
462 cur_block->conditional_branch = true;
463 target += insn->dalvikInsn.vB;
464 break;
465 default:
466 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
467 }
buzbeeb48819d2013-09-14 16:15:25 -0700468 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700469 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800470 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700471 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100472 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800473
474 /* Always terminate the current block for conditional branches */
475 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700476 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800477 /* create */
478 true,
479 /* immed_pred_block_p */
480 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700481 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100482 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800483 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700484 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800485 }
486 return cur_block;
487}
488
489/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800490BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
491 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700492 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800493 const uint16_t* switch_data =
494 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
495 int size;
496 const int* keyTable;
497 const int* target_table;
498 int i;
499 int first_key;
500
501 /*
502 * Packed switch data format:
503 * ushort ident = 0x0100 magic value
504 * ushort size number of entries in the table
505 * int first_key first (and lowest) switch case value
506 * int targets[size] branch targets, relative to switch opcode
507 *
508 * Total size is (4+size*2) 16-bit code units.
509 */
510 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
511 DCHECK_EQ(static_cast<int>(switch_data[0]),
512 static_cast<int>(Instruction::kPackedSwitchSignature));
513 size = switch_data[1];
514 first_key = switch_data[2] | (switch_data[3] << 16);
515 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700516 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800517 /*
518 * Sparse switch data format:
519 * ushort ident = 0x0200 magic value
520 * ushort size number of entries in the table; > 0
521 * int keys[size] keys, sorted low-to-high; 32-bit aligned
522 * int targets[size] branch targets, relative to switch opcode
523 *
524 * Total size is (2+size*4) 16-bit code units.
525 */
526 } else {
527 DCHECK_EQ(static_cast<int>(switch_data[0]),
528 static_cast<int>(Instruction::kSparseSwitchSignature));
529 size = switch_data[1];
530 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
531 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700532 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800533 }
534
buzbee0d829482013-10-11 15:24:55 -0700535 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800536 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700537 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800538 }
buzbee0d829482013-10-11 15:24:55 -0700539 cur_block->successor_block_list_type =
540 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100541 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800542
543 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700544 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
545 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700546 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700547 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000548 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700549 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800550 successor_block_info->key =
551 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
552 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100553 cur_block->successor_blocks.push_back(successor_block_info);
554 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800555 }
556
557 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700558 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
559 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700560 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100561 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800562 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800563}
564
565/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700566BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
567 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700568 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700569 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700570 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800571 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800572
573 /* In try block */
574 if (in_try_block) {
575 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
576
buzbee0d829482013-10-11 15:24:55 -0700577 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800578 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
579 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700580 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800581 }
582
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700583 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700584 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
585 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100586 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
587 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
588 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
589 continue;
590 }
591 if (cur_block->successor_block_list_type == kNotUsed) {
592 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100593 }
buzbee311ca162013-02-28 15:56:43 -0800594 catch_block->catch_entry = true;
595 if (kIsDebugBuild) {
596 catches_.insert(catch_block->start_offset);
597 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700598 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000599 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700600 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800601 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100602 cur_block->successor_blocks.push_back(successor_block_info);
603 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800604 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100605 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
606 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100607 bool build_all_edges =
608 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100609 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100610 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700611 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800612 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100613 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800614 }
615
buzbee17189ac2013-11-08 11:07:02 -0800616 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800617 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700618 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700619 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700620 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800621 }
622 if (!in_try_block) {
623 // Don't split a THROW that can't rethrow - we're done.
624 return cur_block;
625 }
626 }
627
buzbee17189ac2013-11-08 11:07:02 -0800628 if (!build_all_edges) {
629 /*
630 * Even though there is an exception edge here, control cannot return to this
631 * method. Thus, for the purposes of dataflow analysis and optimization, we can
632 * ignore the edge. Doing this reduces compile time, and increases the scope
633 * of the basic-block level optimization pass.
634 */
635 return cur_block;
636 }
637
buzbee311ca162013-02-28 15:56:43 -0800638 /*
639 * Split the potentially-throwing instruction into two parts.
640 * The first half will be a pseudo-op that captures the exception
641 * edges and terminates the basic block. It always falls through.
642 * Then, create a new basic block that begins with the throwing instruction
643 * (minus exceptions). Note: this new basic block must NOT be entered into
644 * the block_map. If the potentially-throwing instruction is the target of a
645 * future branch, we need to find the check psuedo half. The new
646 * basic block containing the work portion of the instruction should
647 * only be entered via fallthrough from the block containing the
648 * pseudo exception edge MIR. Note also that this new block is
649 * not automatically terminated after the work portion, and may
650 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700651 *
652 * Note also that the dex_pc_to_block_map_ entry for the potentially
653 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800654 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100655 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800656 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700657 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100658 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700659 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800660 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700661 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700662 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800663 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700664 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800665 return new_block;
666}
667
668/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
669void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700670 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700671 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800672 current_code_item_ = code_item;
673 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
674 current_method_ = m_units_.size();
675 current_offset_ = 0;
676 // TODO: will need to snapshot stack image and use that as the mir context identification.
677 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000678 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
679 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800680 const uint16_t* code_ptr = current_code_item_->insns_;
681 const uint16_t* code_end =
682 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
683
684 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700685 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100686 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
687 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 -0700688
buzbee311ca162013-02-28 15:56:43 -0800689 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700690 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
691 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800692
693 // If this is the first method, set up default entry and exit blocks.
694 if (current_method_ == 0) {
695 DCHECK(entry_block_ == NULL);
696 DCHECK(exit_block_ == NULL);
Vladimir Markoffda4992014-12-18 17:05:58 +0000697 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700698 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100699 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700700 DCHECK_EQ(null_block->id, NullBasicBlockId);
701 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100702 entry_block_ = CreateNewBB(kEntryBlock);
703 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800704 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
705 cu_->dex_file = &dex_file;
706 cu_->class_def_idx = class_def_idx;
707 cu_->method_idx = method_idx;
708 cu_->access_flags = access_flags;
709 cu_->invoke_type = invoke_type;
710 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800711 } else {
712 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
713 /*
714 * Will need to manage storage for ins & outs, push prevous state and update
715 * insert point.
716 */
717 }
718
719 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100720 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700721 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800722 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700723 // TODO: for inlining support, insert at the insert point rather than entry block.
724 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100725 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800726
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000727 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800728 ProcessTryCatchBlocks();
729
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000730 uint64_t merged_df_flags = 0u;
731
buzbee311ca162013-02-28 15:56:43 -0800732 /* Parse all instructions and put them into containing basic blocks */
733 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700734 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800735 insn->offset = current_offset_;
736 insn->m_unit_index = current_method_;
737 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800738 Instruction::Code opcode = insn->dalvikInsn.opcode;
739 if (opcode_count_ != NULL) {
740 opcode_count_[static_cast<int>(opcode)]++;
741 }
742
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700743 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800744 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800745
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700746 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000747 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800748
749 if (df_flags & DF_HAS_DEFS) {
750 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
751 }
752
buzbee1da1e2f2013-11-15 13:37:01 -0800753 if (df_flags & DF_LVN) {
754 cur_block->use_lvn = true; // Run local value numbering on this basic block.
755 }
756
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700757 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700758 if (opcode == Instruction::NOP) {
759 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
760 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
761 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
762 uint16_t following_raw_instruction = code_ptr[1];
763 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
764 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
765 (following_raw_instruction == Instruction::kArrayDataSignature)) {
766 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
767 }
768 }
769 if (width == 1) {
770 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700771 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700772 } else {
buzbee0d829482013-10-11 15:24:55 -0700773 DCHECK(cur_block->fall_through == NullBasicBlockId);
774 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800775 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700776 flags &= ~Instruction::kContinue;
buzbee6489d222014-11-25 10:52:19 -0800777 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee27247762013-07-28 12:03:58 -0700778 }
779 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700780 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700781 }
782
buzbeeb48819d2013-09-14 16:15:25 -0700783 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100784 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700785
buzbee27247762013-07-28 12:03:58 -0700786 code_ptr += width;
787
buzbee311ca162013-02-28 15:56:43 -0800788 if (flags & Instruction::kBranch) {
789 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
790 width, flags, code_ptr, code_end);
791 } else if (flags & Instruction::kReturn) {
792 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700793 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100794 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800795 /*
796 * Terminate the current block if there are instructions
797 * afterwards.
798 */
799 if (code_ptr < code_end) {
800 /*
801 * Create a fallthrough block for real instructions
802 * (incl. NOP).
803 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700804 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800805 }
806 } else if (flags & Instruction::kThrow) {
807 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
808 code_ptr, code_end);
809 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800810 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800811 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700812 if (verify_flags & Instruction::kVerifyVarArgRange ||
813 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800814 /*
815 * The Quick backend's runtime model includes a gap between a method's
816 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
817 * which spans the gap is somewhat complicated, and should not happen
818 * in normal usage of dx. Punt to the interpreter.
819 */
820 int first_reg_in_range = insn->dalvikInsn.vC;
821 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
822 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
823 punt_to_interpreter_ = true;
824 }
825 }
buzbee311ca162013-02-28 15:56:43 -0800826 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700827 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
828 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800829 if (next_block) {
830 /*
831 * The next instruction could be the target of a previously parsed
832 * forward branch so a block is already created. If the current
833 * instruction is not an unconditional branch, connect them through
834 * the fall-through link.
835 */
buzbee0d829482013-10-11 15:24:55 -0700836 DCHECK(cur_block->fall_through == NullBasicBlockId ||
837 GetBasicBlock(cur_block->fall_through) == next_block ||
838 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800839
buzbee0d829482013-10-11 15:24:55 -0700840 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
841 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100842 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800843 }
844 cur_block = next_block;
845 }
846 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000847 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000848
buzbee311ca162013-02-28 15:56:43 -0800849 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
850 DumpCFG("/sdcard/1_post_parse_cfg/", true);
851 }
852
853 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700854 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800855 }
856}
857
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700858void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800859 DCHECK(opcode_count_ != NULL);
860 LOG(INFO) << "Opcode Count";
861 for (int i = 0; i < kNumPackedOpcodes; i++) {
862 if (opcode_count_[i] != 0) {
863 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
864 << " " << opcode_count_[i];
865 }
866 }
867}
868
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700869uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
870 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
871 return oat_data_flow_attributes_[opcode];
872}
873
874uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
875 DCHECK(mir != nullptr);
876 Instruction::Code opcode = mir->dalvikInsn.opcode;
877 return GetDataFlowAttributes(opcode);
878}
879
Andreas Gampecee97e52014-12-19 15:30:11 -0800880// The path can easily surpass FS limits because of parameters etc. Use pathconf to get FS
881// restrictions here. Note that a successful invocation will return an actual value. If the path
882// is too long for some reason, the return will be ENAMETOOLONG. Then cut off part of the name.
883//
884// It's possible the path is not valid, or some other errors appear. In that case return false.
885static bool CreateDumpFile(std::string& fname, const char* dir_prefix, NarrowDexOffset start_offset,
886 const char *suffix, int nr, std::string* output) {
887 std::string dir = StringPrintf("./%s", dir_prefix);
888 int64_t max_name_length = pathconf(dir.c_str(), _PC_NAME_MAX);
889 if (max_name_length <= 0) {
890 PLOG(ERROR) << "Could not get file name restrictions for " << dir;
891 return false;
892 }
893
894 std::string name = StringPrintf("%s%x%s_%d.dot", fname.c_str(), start_offset,
895 suffix == nullptr ? "" : suffix, nr);
896 std::string fpath;
897 if (static_cast<int64_t>(name.size()) > max_name_length) {
898 std::string suffix_str = StringPrintf("_%d.dot", nr);
899 name = name.substr(0, static_cast<size_t>(max_name_length) - suffix_str.size()) + suffix_str;
900 }
901 // Sanity check.
902 DCHECK_LE(name.size(), static_cast<size_t>(max_name_length));
903
904 *output = StringPrintf("%s%s", dir_prefix, name.c_str());
905 return true;
906}
907
buzbee311ca162013-02-28 15:56:43 -0800908// TODO: use a configurable base prefix, and adjust callers to supply pass name.
909/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800910void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800911 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700912 static AtomicInteger cnt(0);
913
914 // Increment counter to get a unique file number.
915 cnt++;
Andreas Gampecee97e52014-12-19 15:30:11 -0800916 int nr = cnt.LoadRelaxed();
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700917
buzbee311ca162013-02-28 15:56:43 -0800918 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
919 ReplaceSpecialChars(fname);
Andreas Gampecee97e52014-12-19 15:30:11 -0800920 std::string fpath;
921 if (!CreateDumpFile(fname, dir_prefix, GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
922 suffix, nr, &fpath)) {
923 LOG(ERROR) << "Could not create dump file name for " << fname;
924 return;
925 }
926 file = fopen(fpath.c_str(), "w");
buzbee311ca162013-02-28 15:56:43 -0800927 if (file == NULL) {
Andreas Gampecee97e52014-12-19 15:30:11 -0800928 PLOG(ERROR) << "Could not open " << fpath << " for DumpCFG.";
buzbee311ca162013-02-28 15:56:43 -0800929 return;
930 }
931 fprintf(file, "digraph G {\n");
932
933 fprintf(file, " rankdir=TB\n");
934
935 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
936 int idx;
937
938 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100939 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700940 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700941 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800942 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700943 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800944 if (bb->block_type == kEntryBlock) {
945 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
946 } else if (bb->block_type == kExitBlock) {
947 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
948 } else if (bb->block_type == kDalvikByteCode) {
949 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
950 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700951 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800952 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
953 bb->first_mir_insn ? " | " : " ");
954 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
955 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800956 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400957 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700958 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
959 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400960 extended_mir_op_names_[opcode - kMirOpFirst],
961 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
962 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700963 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700964 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700965 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100966 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
967 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800968 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400969 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800970 }
971 fprintf(file, " }\"];\n\n");
972 } else if (bb->block_type == kExceptionHandling) {
973 char block_name[BLOCK_NAME_LEN];
974
975 GetBlockName(bb, block_name);
976 fprintf(file, " %s [shape=invhouse];\n", block_name);
977 }
978
979 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
980
buzbee0d829482013-10-11 15:24:55 -0700981 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800982 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700983 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800984 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
985 block_name1, block_name2);
986 }
buzbee0d829482013-10-11 15:24:55 -0700987 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800988 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700989 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800990 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
991 }
992
buzbee0d829482013-10-11 15:24:55 -0700993 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800994 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
995 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700996 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800997
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100998 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -0800999 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001000 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001001 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001002 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001003 succ_id,
buzbee311ca162013-02-28 15:56:43 -08001004 successor_block_info->key,
1005 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001006 (succ_id != last_succ_id) ? " | " : " ");
1007 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -08001008 }
1009 fprintf(file, " }\"];\n\n");
1010
1011 GetBlockName(bb, block_name1);
1012 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1013 block_name1, bb->start_offset, bb->id);
1014
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001015 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001016 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001017 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001018 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001019
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001020 GetBlockName(dest_block, block_name2);
1021 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1022 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001023 }
1024 }
1025 fprintf(file, "\n");
1026
1027 if (cu_->verbose) {
1028 /* Display the dominator tree */
1029 GetBlockName(bb, block_name1);
1030 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1031 block_name1, block_name1);
1032 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001033 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001034 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1035 }
1036 }
1037 }
1038 fprintf(file, "}\n");
1039 fclose(file);
1040}
1041
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001042/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001043void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001044 // Insert it after the last MIR.
1045 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001046}
1047
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001048void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1049 // Insert it after the last MIR.
1050 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1051}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001052
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001053void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1054 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1055 MIR* new_mir = *it;
1056
1057 // Add a copy of each MIR.
1058 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1059 }
buzbee1fd33462013-03-25 13:40:45 -07001060}
1061
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001062/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001063void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001064 InsertMIRListAfter(current_mir, new_mir, new_mir);
1065}
buzbee1fd33462013-03-25 13:40:45 -07001066
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001067void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1068 // If no MIR, we are done.
1069 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1070 return;
buzbee1fd33462013-03-25 13:40:45 -07001071 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001072
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001073 // If insert_after is null, assume BB is empty.
1074 if (insert_after == nullptr) {
1075 first_mir_insn = first_list_mir;
1076 last_mir_insn = last_list_mir;
1077 last_list_mir->next = nullptr;
1078 } else {
1079 MIR* after_list = insert_after->next;
1080 insert_after->next = first_list_mir;
1081 last_list_mir->next = after_list;
1082 if (after_list == nullptr) {
1083 last_mir_insn = last_list_mir;
1084 }
1085 }
1086
1087 // Set this BB to be the basic block of the MIRs.
1088 MIR* last = last_list_mir->next;
1089 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1090 mir->bb = id;
1091 }
1092}
1093
1094/* Insert an MIR instruction to the head of a basic block. */
1095void BasicBlock::PrependMIR(MIR* mir) {
1096 InsertMIRListBefore(first_mir_insn, mir, mir);
1097}
1098
1099void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1100 // Insert it before the first MIR.
1101 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1102}
1103
1104void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1105 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1106 MIR* mir = *it;
1107
1108 InsertMIRListBefore(first_mir_insn, mir, mir);
1109 }
1110}
1111
1112/* Insert a MIR instruction before the specified MIR. */
1113void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1114 // Insert as a single element list.
1115 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001116}
1117
1118MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1119 MIR* current = first_mir_insn;
1120
1121 while (current != nullptr) {
1122 MIR* next = current->next;
1123
1124 if (next == mir) {
1125 return current;
1126 }
1127
1128 current = next;
1129 }
1130
1131 return nullptr;
1132}
1133
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001134void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1135 // If no MIR, we are done.
1136 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1137 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001138 }
1139
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001140 // If insert_before is null, assume BB is empty.
1141 if (insert_before == nullptr) {
1142 first_mir_insn = first_list_mir;
1143 last_mir_insn = last_list_mir;
1144 last_list_mir->next = nullptr;
1145 } else {
1146 if (first_mir_insn == insert_before) {
1147 last_list_mir->next = first_mir_insn;
1148 first_mir_insn = first_list_mir;
1149 } else {
1150 // Find the preceding MIR.
1151 MIR* before_list = FindPreviousMIR(insert_before);
1152 DCHECK(before_list != nullptr);
1153 before_list->next = first_list_mir;
1154 last_list_mir->next = insert_before;
1155 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001156 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001157
1158 // Set this BB to be the basic block of the MIRs.
1159 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1160 mir->bb = id;
1161 }
1162}
1163
1164bool BasicBlock::RemoveMIR(MIR* mir) {
1165 // Remove as a single element list.
1166 return RemoveMIRList(mir, mir);
1167}
1168
1169bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1170 if (first_list_mir == nullptr) {
1171 return false;
1172 }
1173
1174 // Try to find the MIR.
1175 MIR* before_list = nullptr;
1176 MIR* after_list = nullptr;
1177
1178 // If we are removing from the beginning of the MIR list.
1179 if (first_mir_insn == first_list_mir) {
1180 before_list = nullptr;
1181 } else {
1182 before_list = FindPreviousMIR(first_list_mir);
1183 if (before_list == nullptr) {
1184 // We did not find the mir.
1185 return false;
1186 }
1187 }
1188
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001189 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001190 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001191 mir->bb = NullBasicBlockId;
1192 }
1193
1194 after_list = last_list_mir->next;
1195
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001196 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001197 if (before_list == nullptr) {
1198 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001199 } else {
1200 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001201 }
1202
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001203 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001204 if (after_list == nullptr) {
1205 last_mir_insn = before_list;
1206 }
1207
1208 return true;
buzbee1fd33462013-03-25 13:40:45 -07001209}
1210
Vladimir Marko26e7d452014-11-24 14:09:46 +00001211MIR* BasicBlock::GetFirstNonPhiInsn() {
1212 MIR* mir = first_mir_insn;
1213 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1214 mir = mir->next;
1215 }
1216 return mir;
1217}
1218
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001219MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001220 MIR* next_mir = nullptr;
1221
1222 if (current != nullptr) {
1223 next_mir = current->next;
1224 }
1225
1226 if (next_mir == nullptr) {
1227 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001228 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1229 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001230 }
1231 }
1232
1233 return next_mir;
1234}
1235
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001236static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1237 DCHECK(decoded_mir != nullptr);
1238 OpSize type = static_cast<OpSize>(type_size >> 16);
1239 uint16_t vect_size = (type_size & 0xFFFF);
1240
1241 // Now print the type and vector size.
1242 std::stringstream ss;
1243 ss << " (type:";
1244 ss << type;
1245 ss << " vectsize:";
1246 ss << vect_size;
1247 ss << ")";
1248
1249 decoded_mir->append(ss.str());
1250}
1251
1252void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1253 DCHECK(decoded_mir != nullptr);
1254 int opcode = mir->dalvikInsn.opcode;
1255 SSARepresentation* ssa_rep = mir->ssa_rep;
1256 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1257 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1258
Vladimirf41b92c2014-10-13 13:41:38 +07001259 if (opcode < kMirOpFirst) {
1260 return; // It is not an extended instruction.
1261 }
1262
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001263 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1264
1265 switch (opcode) {
1266 case kMirOpPhi: {
1267 if (defs > 0 && uses > 0) {
1268 BasicBlockId* incoming = mir->meta.phi_incoming;
1269 decoded_mir->append(StringPrintf(" %s = (%s",
1270 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1271 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1272 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1273 for (int i = 1; i < uses; i++) {
1274 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1275 }
1276 decoded_mir->append(")");
1277 }
1278 break;
1279 }
1280 case kMirOpCopy:
1281 if (ssa_rep != nullptr) {
1282 decoded_mir->append(" ");
1283 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1284 if (defs > 1) {
1285 decoded_mir->append(", ");
1286 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1287 }
1288 decoded_mir->append(" = ");
1289 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1290 if (uses > 1) {
1291 decoded_mir->append(", ");
1292 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1293 }
1294 } else {
1295 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1296 }
1297 break;
1298 case kMirOpFusedCmplFloat:
1299 case kMirOpFusedCmpgFloat:
1300 case kMirOpFusedCmplDouble:
1301 case kMirOpFusedCmpgDouble:
1302 case kMirOpFusedCmpLong:
1303 if (ssa_rep != nullptr) {
1304 decoded_mir->append(" ");
1305 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1306 for (int i = 1; i < uses; i++) {
1307 decoded_mir->append(", ");
1308 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1309 }
1310 } else {
1311 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1312 }
1313 break;
1314 case kMirOpMoveVector:
1315 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1316 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1317 break;
1318 case kMirOpPackedAddition:
1319 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1320 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1321 break;
1322 case kMirOpPackedMultiply:
1323 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1324 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1325 break;
1326 case kMirOpPackedSubtract:
1327 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1328 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1329 break;
1330 case kMirOpPackedAnd:
1331 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1332 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1333 break;
1334 case kMirOpPackedOr:
1335 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1336 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1337 break;
1338 case kMirOpPackedXor:
1339 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1340 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1341 break;
1342 case kMirOpPackedShiftLeft:
1343 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1344 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1345 break;
1346 case kMirOpPackedUnsignedShiftRight:
1347 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1348 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1349 break;
1350 case kMirOpPackedSignedShiftRight:
1351 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1352 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1353 break;
1354 case kMirOpConstVector:
1355 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1356 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1357 break;
1358 case kMirOpPackedSet:
1359 if (ssa_rep != nullptr) {
1360 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1361 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1362 if (uses > 1) {
1363 decoded_mir->append(", ");
1364 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1365 }
1366 } else {
1367 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1368 }
1369 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1370 break;
1371 case kMirOpPackedAddReduce:
1372 if (ssa_rep != nullptr) {
1373 decoded_mir->append(" ");
1374 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1375 if (defs > 1) {
1376 decoded_mir->append(", ");
1377 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1378 }
1379 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1380 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1381 if (uses > 1) {
1382 decoded_mir->append(", ");
1383 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1384 }
1385 } else {
1386 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1387 }
1388 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1389 break;
1390 case kMirOpPackedReduce:
1391 if (ssa_rep != nullptr) {
1392 decoded_mir->append(" ");
1393 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1394 if (defs > 1) {
1395 decoded_mir->append(", ");
1396 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1397 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001398 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001399 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001400 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1401 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001402 }
1403 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1404 break;
1405 case kMirOpReserveVectorRegisters:
1406 case kMirOpReturnVectorRegisters:
1407 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1408 break;
1409 case kMirOpMemBarrier: {
1410 decoded_mir->append(" type:");
1411 std::stringstream ss;
1412 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1413 decoded_mir->append(ss.str());
1414 break;
1415 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001416 case kMirOpPackedArrayGet:
1417 case kMirOpPackedArrayPut:
1418 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1419 if (ssa_rep != nullptr) {
1420 decoded_mir->append(StringPrintf(", %s[%s]",
1421 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1422 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1423 } else {
1424 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1425 }
1426 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1427 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001428 case kMirOpMaddInt:
1429 case kMirOpMsubInt:
1430 case kMirOpMaddLong:
1431 case kMirOpMsubLong:
1432 if (ssa_rep != nullptr) {
1433 decoded_mir->append(" ");
1434 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1435 if (defs > 1) {
1436 decoded_mir->append(", ");
1437 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1438 }
1439 for (int i = 0; i < uses; i++) {
1440 decoded_mir->append(", ");
1441 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1442 }
1443 } else {
1444 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1445 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1446 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1447 }
1448 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001449 default:
1450 break;
1451 }
1452}
1453
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001454char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001455 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001456 std::string str;
1457 int flags = 0;
1458 int opcode = insn.opcode;
1459 char* ret;
1460 bool nop = false;
1461 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001462 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001463
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001464 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001465 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1466 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1467 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001468 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001469 insn = mir->meta.throw_insn->dalvikInsn;
1470 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001471 opcode = insn.opcode;
1472 } else if (opcode == kMirOpNop) {
1473 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001474 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1475 // Recover original opcode.
1476 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1477 opcode = insn.opcode;
1478 }
buzbee1fd33462013-03-25 13:40:45 -07001479 nop = true;
1480 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001481 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1482 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001483
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001484 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001485 // Note that this does not check the MIR's opcode in all cases. In cases where it
1486 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1487 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001488 } else {
1489 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001490 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001491 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001492
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001493 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001494 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1495 (dalvik_format == Instruction::k3rc));
1496 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001497 str.append(" ");
1498 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1499 if (defs > 1) {
1500 str.append(", ");
1501 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1502 }
buzbee1fd33462013-03-25 13:40:45 -07001503 if (uses != 0) {
1504 str.append(", ");
1505 }
1506 }
1507 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001508 str.append(" ");
1509 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001510 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1511 // For the listing, skip the high sreg.
1512 i++;
1513 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001514 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001515 str.append(",");
1516 }
1517 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001518
buzbee1fd33462013-03-25 13:40:45 -07001519 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001520 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001521 case Instruction::k21s:
1522 case Instruction::k31i:
1523 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001524 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001525 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001526 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001527 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001528 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001529 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001530 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001531 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001532 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001533 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001534 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001535 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001536 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001537 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001538 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001539 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001540 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001541 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001542 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001543 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001544
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001545 if ((flags & Instruction::kBranch) != 0) {
1546 // For branches, decode the instructions to print out the branch targets.
1547 int offset = 0;
1548 switch (dalvik_format) {
1549 case Instruction::k21t:
1550 offset = insn.vB;
1551 break;
1552 case Instruction::k22t:
1553 offset = insn.vC;
1554 break;
1555 case Instruction::k10t:
1556 case Instruction::k20t:
1557 case Instruction::k30t:
1558 offset = insn.vA;
1559 break;
1560 default:
1561 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001562 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001563 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001564 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001565 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1566 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001567
1568 if (nop) {
1569 str.append("]--optimized away");
1570 }
buzbee1fd33462013-03-25 13:40:45 -07001571 }
1572 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001573 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001574 strncpy(ret, str.c_str(), length);
1575 return ret;
1576}
1577
1578/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001579void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001580 static const struct { const char before; const char after; } match[] = {
1581 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1582 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1583 };
buzbee1fd33462013-03-25 13:40:45 -07001584 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1585 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1586 }
1587}
1588
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001589std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001590 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1591 // the arena. We should be smarter and just place straight into the arena, or compute the
1592 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001593 int vreg = SRegToVReg(ssa_reg);
1594 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1595 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1596 } else {
1597 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1598 }
buzbee1fd33462013-03-25 13:40:45 -07001599}
1600
1601// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001602std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001603 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001604 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001605 return GetSSAName(ssa_reg);
1606 }
1607 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001608 if (!singles_only && reg_location_[ssa_reg].wide &&
1609 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001610 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001611 ConstantValueWide(reg_location_[ssa_reg]));
1612 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001613 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001614 ConstantValue(reg_location_[ssa_reg]));
1615 }
1616 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001617 int vreg = SRegToVReg(ssa_reg);
1618 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1619 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1620 } else {
1621 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1622 }
buzbee1fd33462013-03-25 13:40:45 -07001623 }
1624}
1625
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001626void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001627 switch (bb->block_type) {
1628 case kEntryBlock:
1629 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1630 break;
1631 case kExitBlock:
1632 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1633 break;
1634 case kDalvikByteCode:
1635 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1636 break;
1637 case kExceptionHandling:
1638 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1639 bb->id);
1640 break;
1641 default:
1642 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1643 break;
1644 }
1645}
1646
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001647const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001648 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001649 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1650 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1651}
1652
Serguei Katkov717a3e42014-11-13 17:19:42 +06001653const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1654 const DexFile::MethodId& method_id =
1655 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1656 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1657}
1658
buzbee1fd33462013-03-25 13:40:45 -07001659/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001660void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001661 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001662 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001663 "Entry Block",
1664 "Code Block",
1665 "Exit Block",
1666 "Exception Handling",
1667 "Catch Block"
1668 };
1669
1670 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001671 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001672 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001673
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001674 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001675 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1676 bb->id,
1677 block_type_names[bb->block_type],
1678 bb->start_offset,
1679 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1680 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001681 if (bb->taken != NullBasicBlockId) {
1682 LOG(INFO) << " Taken branch: block " << bb->taken
1683 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001684 }
buzbee0d829482013-10-11 15:24:55 -07001685 if (bb->fall_through != NullBasicBlockId) {
1686 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1687 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001688 }
1689 }
1690}
1691
1692/*
1693 * Build an array of location records for the incoming arguments.
1694 * Note: one location record per word of arguments, with dummy
1695 * high-word loc for wide arguments. Also pull up any following
1696 * MOVE_RESULT and incorporate it into the invoke.
1697 */
1698CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001699 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001700 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001701 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001702 MIR* move_result_mir = FindMoveResult(bb, mir);
1703 if (move_result_mir == NULL) {
1704 info->result.location = kLocInvalid;
1705 } else {
1706 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001707 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1708 }
1709 info->num_arg_words = mir->ssa_rep->num_uses;
1710 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001711 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001712 for (int i = 0; i < info->num_arg_words; i++) {
1713 info->args[i] = GetRawSrc(mir, i);
1714 }
1715 info->opt_flags = mir->optimization_flags;
1716 info->type = type;
1717 info->is_range = is_range;
1718 info->index = mir->dalvikInsn.vB;
1719 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001720 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001721 return info;
1722}
1723
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001724// Allocate a new MIR.
1725MIR* MIRGraph::NewMIR() {
1726 MIR* mir = new (arena_) MIR();
1727 return mir;
1728}
1729
buzbee862a7602013-04-05 10:58:54 -07001730// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001731BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001732 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001733
buzbee862a7602013-04-05 10:58:54 -07001734 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001735 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001736 block_id_map_.Put(block_id, block_id);
1737 return bb;
1738}
buzbee1fd33462013-03-25 13:40:45 -07001739
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001740void MIRGraph::InitializeConstantPropagation() {
1741 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001742 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001743}
1744
1745void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001746 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001747 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001748 use_counts_.clear();
1749 use_counts_.reserve(num_ssa_regs + 32);
1750 use_counts_.resize(num_ssa_regs, 0u);
1751 raw_use_counts_.clear();
1752 raw_use_counts_.reserve(num_ssa_regs + 32);
1753 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001754}
1755
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001756void MIRGraph::SSATransformationStart() {
1757 DCHECK(temp_scoped_alloc_.get() == nullptr);
1758 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001759 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1760 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1761 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001762}
1763
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001764void MIRGraph::SSATransformationEnd() {
1765 // Verify the dataflow information after the pass.
1766 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1767 VerifyDataflow();
1768 }
1769
Vladimir Markof585e542014-11-21 13:41:32 +00001770 temp_.ssa.num_vregs = 0u;
1771 temp_.ssa.work_live_vregs = nullptr;
1772 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001773 DCHECK(temp_scoped_alloc_.get() != nullptr);
1774 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001775
1776 // Update the maximum number of reachable blocks.
1777 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001778
1779 // Mark MIR SSA representations as up to date.
1780 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001781}
1782
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001783size_t MIRGraph::GetNumDalvikInsns() const {
1784 size_t cumulative_size = 0u;
1785 bool counted_current_item = false;
1786 const uint8_t size_for_null_code_item = 2u;
1787
1788 for (auto it : m_units_) {
1789 const DexFile::CodeItem* code_item = it->GetCodeItem();
1790 // Even if the code item is null, we still count non-zero value so that
1791 // each m_unit is counted as having impact.
1792 cumulative_size += (code_item == nullptr ?
1793 size_for_null_code_item : code_item->insns_size_in_code_units_);
1794 if (code_item == current_code_item_) {
1795 counted_current_item = true;
1796 }
1797 }
1798
1799 // If the current code item was not counted yet, count it now.
1800 // This can happen for example in unit tests where some fields like m_units_
1801 // are not initialized.
1802 if (counted_current_item == false) {
1803 cumulative_size += (current_code_item_ == nullptr ?
1804 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1805 }
1806
1807 return cumulative_size;
1808}
1809
Vladimir Marko55fff042014-07-10 12:42:52 +01001810static BasicBlock* SelectTopologicalSortOrderFallBack(
1811 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1812 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1813 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1814 // No true loop head has been found but there may be true loop heads after the mess we need
1815 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1816 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1817 BasicBlock* fall_back = nullptr;
1818 size_t fall_back_num_reachable = 0u;
1819 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1820 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1821 AllNodesIterator iter(mir_graph);
1822 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1823 if (candidate->hidden || // Hidden, or
1824 candidate->visited || // already processed, or
1825 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1826 (current_loop != nullptr && // outside current loop.
1827 !current_loop->IsBitSet(candidate->id))) {
1828 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001829 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001830 DCHECK(tmp_stack->empty());
1831 tmp_stack->push_back(candidate->id);
1832 candidate_reachable.ClearAllBits();
1833 size_t num_reachable = 0u;
1834 while (!tmp_stack->empty()) {
1835 BasicBlockId current_id = tmp_stack->back();
1836 tmp_stack->pop_back();
1837 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1838 DCHECK(current_bb != nullptr);
1839 ChildBlockIterator child_iter(current_bb, mir_graph);
1840 BasicBlock* child_bb = child_iter.Next();
1841 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1842 DCHECK(!child_bb->hidden);
1843 if (child_bb->visited || // Already processed, or
1844 (current_loop != nullptr && // outside current loop.
1845 !current_loop->IsBitSet(child_bb->id))) {
1846 continue;
1847 }
1848 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1849 candidate_reachable.SetBit(child_bb->id);
1850 tmp_stack->push_back(child_bb->id);
1851 num_reachable += 1u;
1852 }
1853 }
1854 }
1855 if (fall_back_num_reachable < num_reachable) {
1856 fall_back_num_reachable = num_reachable;
1857 fall_back = candidate;
1858 }
1859 }
1860 return fall_back;
1861}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001862
Vladimir Marko55fff042014-07-10 12:42:52 +01001863// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1864static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1865 ArenaBitVector* reachable,
1866 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1867 // NOTE: Loop heads indicated by the "visited" flag.
1868 DCHECK(tmp_stack->empty());
1869 reachable->ClearAllBits();
1870 tmp_stack->push_back(bb_id);
1871 while (!tmp_stack->empty()) {
1872 BasicBlockId current_id = tmp_stack->back();
1873 tmp_stack->pop_back();
1874 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1875 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001876 for (BasicBlockId pred_id : current_bb->predecessors) {
1877 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1878 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001879 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1880 reachable->SetBit(pred_bb->id);
1881 tmp_stack->push_back(pred_bb->id);
1882 }
1883 }
1884 }
1885}
1886
1887void MIRGraph::ComputeTopologicalSortOrder() {
1888 ScopedArenaAllocator allocator(&cu_->arena_stack);
1889 unsigned int num_blocks = GetNumBlocks();
1890
1891 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1892 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1893 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1894 size_t max_nested_loops = 0u;
1895 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1896 loop_exit_blocks.ClearAllBits();
1897
1898 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001899 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001900 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001901 if (bb->hidden == true) {
1902 continue;
1903 }
1904
Vladimir Marko55fff042014-07-10 12:42:52 +01001905 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001906
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001907 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001908 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001909 q.push(bb);
1910 }
1911 }
1912
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001913 // Clear the topological order arrays.
1914 topological_order_.clear();
1915 topological_order_.reserve(num_blocks);
1916 topological_order_loop_ends_.clear();
1917 topological_order_loop_ends_.resize(num_blocks, 0u);
1918 topological_order_indexes_.clear();
1919 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001920
1921 // Mark all blocks as unvisited.
1922 ClearAllVisitedFlags();
1923
1924 // For loop heads, keep track from which blocks they are reachable not going through other
1925 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1926 // in this set go into the loop body, the other children are jumping over the loop.
1927 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1928 loop_head_reachable_from.resize(num_blocks, nullptr);
1929 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1930 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1931
1932 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001933 BasicBlock* bb = nullptr;
1934 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001935 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001936 // Get top.
1937 bb = q.front();
1938 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001939 if (bb->visited) {
1940 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1941 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001942 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1943 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001944 DCHECK_EQ(loop_head_stack.back(), bb->id);
1945 loop_head_stack.pop_back();
1946 ArenaBitVector* reachable =
1947 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1948 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1949 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1950 q.push(GetBasicBlock(candidate_id));
1951 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1952 // so clearing the bit has no effect on the iterator.
1953 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001954 }
1955 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001956 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001957 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001958 } else {
1959 // Find the new loop head.
1960 AllNodesIterator iter(this);
1961 while (true) {
1962 BasicBlock* candidate = iter.Next();
1963 if (candidate == nullptr) {
1964 // We did not find a true loop head, fall back to a reachable block in any loop.
1965 ArenaBitVector* current_loop =
1966 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1967 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1968 &allocator, &tmp_stack);
1969 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1970 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1971 LOG(INFO) << "Topological sort order: Using fall-back in "
1972 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1973 << " @0x" << std::hex << bb->start_offset
1974 << ", num_blocks = " << std::dec << num_blocks;
1975 }
1976 break;
1977 }
1978 if (candidate->hidden || // Hidden, or
1979 candidate->visited || // already processed, or
1980 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1981 (!loop_head_stack.empty() && // outside current loop.
1982 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1983 continue;
1984 }
1985
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001986 for (BasicBlockId pred_id : candidate->predecessors) {
1987 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1988 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001989 if (pred_bb != candidate && !pred_bb->visited &&
1990 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001991 candidate = nullptr; // Set candidate to null to indicate failure.
1992 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001993 }
1994 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001995 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001996 bb = candidate;
1997 break;
1998 }
1999 }
2000 // Compute blocks from which the loop head is reachable and process those blocks first.
2001 ArenaBitVector* reachable =
2002 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
2003 loop_head_reachable_from[bb->id] = reachable;
2004 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
2005 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
2006 loop_head_stack.push_back(bb->id);
2007 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002008 }
2009
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002010 DCHECK_EQ(bb->hidden, false);
2011 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002012 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00002013 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002014
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002015 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002016 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
2017 topological_order_indexes_[bb->id] = idx;
2018 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002019
Vladimir Marko55fff042014-07-10 12:42:52 +01002020 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002021 ChildBlockIterator succIter(bb, this);
2022 BasicBlock* successor = succIter.Next();
2023 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002024 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002025 continue;
2026 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002027
Vladimir Marko55fff042014-07-10 12:42:52 +01002028 // One more predecessor was visited.
2029 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002030 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002031 if (loop_head_stack.empty() ||
2032 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
2033 q.push(successor);
2034 } else {
2035 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2036 loop_exit_blocks.SetBit(successor->id);
2037 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002038 }
2039 }
2040 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002041
2042 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002043 topological_order_loop_head_stack_.clear();
2044 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002045 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002046 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002047}
2048
2049bool BasicBlock::IsExceptionBlock() const {
2050 if (block_type == kExceptionHandling) {
2051 return true;
2052 }
2053 return false;
2054}
2055
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002056ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2057 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2058 visited_taken_(false), have_successors_(false) {
2059 // Check if we actually do have successors.
2060 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2061 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002062 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002063 }
2064}
2065
2066BasicBlock* ChildBlockIterator::Next() {
2067 // We check if we have a basic block. If we don't we cannot get next child.
2068 if (basic_block_ == nullptr) {
2069 return nullptr;
2070 }
2071
2072 // If we haven't visited fallthrough, return that.
2073 if (visited_fallthrough_ == false) {
2074 visited_fallthrough_ = true;
2075
2076 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2077 if (result != nullptr) {
2078 return result;
2079 }
2080 }
2081
2082 // If we haven't visited taken, return that.
2083 if (visited_taken_ == false) {
2084 visited_taken_ = true;
2085
2086 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2087 if (result != nullptr) {
2088 return result;
2089 }
2090 }
2091
2092 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2093 if (have_successors_ == true) {
2094 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002095 auto end = basic_block_->successor_blocks.cend();
2096 while (successor_iter_ != end) {
2097 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2098 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002099 // If block was replaced by zero block, take next one.
2100 if (successor_block_info->block != NullBasicBlockId) {
2101 return mir_graph_->GetBasicBlock(successor_block_info->block);
2102 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002103 }
2104 }
2105
2106 // We do not have anything.
2107 return nullptr;
2108}
2109
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002110BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2111 MIRGraph* mir_graph = c_unit->mir_graph.get();
2112 return Copy(mir_graph);
2113}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002114
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002115BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2116 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002117
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002118 // We don't do a memcpy style copy here because it would lead to a lot of things
2119 // to clean up. Let us do it by hand instead.
2120 // Copy in taken and fallthrough.
2121 result_bb->fall_through = fall_through;
2122 result_bb->taken = taken;
2123
2124 // Copy successor links if needed.
2125 ArenaAllocator* arena = mir_graph->GetArena();
2126
2127 result_bb->successor_block_list_type = successor_block_list_type;
2128 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002129 result_bb->successor_blocks.reserve(successor_blocks.size());
2130 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2131 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2132 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002133 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002134 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002135 }
2136 }
2137
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002138 // Copy offset, method.
2139 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002140
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002141 // Now copy instructions.
2142 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2143 // Get a copy first.
2144 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002145
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002146 // Append it.
2147 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002148 }
2149
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002150 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002151}
2152
2153MIR* MIR::Copy(MIRGraph* mir_graph) {
2154 MIR* res = mir_graph->NewMIR();
2155 *res = *this;
2156
2157 // Remove links
2158 res->next = nullptr;
2159 res->bb = NullBasicBlockId;
2160 res->ssa_rep = nullptr;
2161
2162 return res;
2163}
2164
2165MIR* MIR::Copy(CompilationUnit* c_unit) {
2166 return Copy(c_unit->mir_graph.get());
2167}
2168
2169uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2170 // Default result.
2171 int res = 0;
2172
2173 // We are basically setting the iputs to their igets counterparts.
2174 switch (opcode) {
2175 case Instruction::IPUT:
2176 case Instruction::IPUT_OBJECT:
2177 case Instruction::IPUT_BOOLEAN:
2178 case Instruction::IPUT_BYTE:
2179 case Instruction::IPUT_CHAR:
2180 case Instruction::IPUT_SHORT:
2181 case Instruction::IPUT_QUICK:
2182 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002183 case Instruction::IPUT_BOOLEAN_QUICK:
2184 case Instruction::IPUT_BYTE_QUICK:
2185 case Instruction::IPUT_CHAR_QUICK:
2186 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002187 case Instruction::APUT:
2188 case Instruction::APUT_OBJECT:
2189 case Instruction::APUT_BOOLEAN:
2190 case Instruction::APUT_BYTE:
2191 case Instruction::APUT_CHAR:
2192 case Instruction::APUT_SHORT:
2193 case Instruction::SPUT:
2194 case Instruction::SPUT_OBJECT:
2195 case Instruction::SPUT_BOOLEAN:
2196 case Instruction::SPUT_BYTE:
2197 case Instruction::SPUT_CHAR:
2198 case Instruction::SPUT_SHORT:
2199 // Skip the VR containing what to store.
2200 res = 1;
2201 break;
2202 case Instruction::IPUT_WIDE:
2203 case Instruction::IPUT_WIDE_QUICK:
2204 case Instruction::APUT_WIDE:
2205 case Instruction::SPUT_WIDE:
2206 // Skip the two VRs containing what to store.
2207 res = 2;
2208 break;
2209 default:
2210 // Do nothing in the general case.
2211 break;
2212 }
2213
2214 return res;
2215}
2216
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002217/**
2218 * @brief Given a decoded instruction, it checks whether the instruction
2219 * sets a constant and if it does, more information is provided about the
2220 * constant being set.
2221 * @param ptr_value pointer to a 64-bit holder for the constant.
2222 * @param wide Updated by function whether a wide constant is being set by bytecode.
2223 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2224 */
2225bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2226 bool sets_const = true;
2227 int64_t value = vB;
2228
2229 DCHECK(ptr_value != nullptr);
2230 DCHECK(wide != nullptr);
2231
2232 switch (opcode) {
2233 case Instruction::CONST_4:
2234 case Instruction::CONST_16:
2235 case Instruction::CONST:
2236 *wide = false;
2237 value <<= 32; // In order to get the sign extend.
2238 value >>= 32;
2239 break;
2240 case Instruction::CONST_HIGH16:
2241 *wide = false;
2242 value <<= 48; // In order to get the sign extend.
2243 value >>= 32;
2244 break;
2245 case Instruction::CONST_WIDE_16:
2246 case Instruction::CONST_WIDE_32:
2247 *wide = true;
2248 value <<= 32; // In order to get the sign extend.
2249 value >>= 32;
2250 break;
2251 case Instruction::CONST_WIDE:
2252 *wide = true;
2253 value = vB_wide;
2254 break;
2255 case Instruction::CONST_WIDE_HIGH16:
2256 *wide = true;
2257 value <<= 48; // In order to get the sign extend.
2258 break;
2259 default:
2260 sets_const = false;
2261 break;
2262 }
2263
2264 if (sets_const) {
2265 *ptr_value = value;
2266 }
2267
2268 return sets_const;
2269}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002270
2271void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2272 // Reset flags for all MIRs in bb.
2273 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2274 mir->optimization_flags &= (~reset_flags);
2275 }
2276}
2277
Vladimir Markocb873d82014-12-08 15:16:54 +00002278void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002279 for (BasicBlockId pred_id : predecessors) {
2280 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2281 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002282
2283 // Sadly we have to go through the children by hand here.
2284 pred_bb->ReplaceChild(id, NullBasicBlockId);
2285 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002286 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002287
Vladimir Marko312eb252014-10-07 15:01:57 +01002288 // Mark as dead and hidden.
2289 block_type = kDead;
2290 hidden = true;
2291
2292 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2293 // are updated to know that they no longer have a parent.
2294 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2295 mir->bb = NullBasicBlockId;
2296 }
2297 first_mir_insn = nullptr;
2298 last_mir_insn = nullptr;
2299
2300 data_flow_info = nullptr;
2301
2302 // Erase this bb from all children's predecessors and kill unreachable children.
2303 ChildBlockIterator iter(this, mir_graph);
2304 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2305 succ_bb->ErasePredecessor(id);
Vladimir Marko312eb252014-10-07 15:01:57 +01002306 }
2307
2308 // Remove links to children.
2309 fall_through = NullBasicBlockId;
2310 taken = NullBasicBlockId;
2311 successor_block_list_type = kNotUsed;
2312
2313 if (kIsDebugBuild) {
2314 if (catch_entry) {
2315 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2316 mir_graph->catches_.erase(start_offset);
2317 }
2318 }
2319}
2320
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002321bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2322 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2323 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2324 // then it is not live out of this BB.
2325 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2326
2327 int last_ssa_reg = -1;
2328
2329 // Walk through the MIRs backwards.
2330 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2331 // Get ssa rep.
2332 SSARepresentation *ssa_rep = mir->ssa_rep;
2333
2334 // Go through the defines for this MIR.
2335 for (int i = 0; i < ssa_rep->num_defs; i++) {
2336 DCHECK(ssa_rep->defs != nullptr);
2337
2338 // Get the ssa reg.
2339 int def_ssa_reg = ssa_rep->defs[i];
2340
2341 // Get dalvik reg.
2342 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2343
2344 // Compare dalvik regs.
2345 if (dalvik_reg == def_dalvik_reg) {
2346 // We found a def of the register that we are being asked about.
2347 // Remember it.
2348 last_ssa_reg = def_ssa_reg;
2349 }
2350 }
2351 }
2352
2353 if (last_ssa_reg == -1) {
2354 // If we get to this point we couldn't find a define of register user asked about.
2355 // Let's assume the user knows what he's doing so we can be safe and say that if we
2356 // couldn't find a def, it is live out.
2357 return true;
2358 }
2359
2360 // If it is not -1, we found a match, is it ssa_reg?
2361 return (ssa_reg == last_ssa_reg);
2362}
2363
2364bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2365 // We need to check taken, fall_through, and successor_blocks to replace.
2366 bool found = false;
2367 if (taken == old_bb) {
2368 taken = new_bb;
2369 found = true;
2370 }
2371
2372 if (fall_through == old_bb) {
2373 fall_through = new_bb;
2374 found = true;
2375 }
2376
2377 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002378 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002379 if (successor_block_info->block == old_bb) {
2380 successor_block_info->block = new_bb;
2381 found = true;
2382 }
2383 }
2384 }
2385
2386 return found;
2387}
2388
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002389void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2390 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2391 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002392 // It's faster to move the back() to *pos than erase(pos).
2393 *pos = predecessors.back();
2394 predecessors.pop_back();
2395 size_t idx = std::distance(predecessors.begin(), pos);
2396 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2397 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2398 break;
2399 }
2400 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2401 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2402 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2403 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2404 mir->ssa_rep->num_uses = predecessors.size();
2405 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002406}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002407
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002408void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2409 DCHECK_NE(new_pred, NullBasicBlockId);
2410 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002411 DCHECK(pos != predecessors.end());
2412 *pos = new_pred;
2413 size_t idx = std::distance(predecessors.begin(), pos);
2414 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2415 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2416 break;
2417 }
2418 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2419 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002420 }
2421}
2422
2423// Create a new basic block with block_id as num_blocks_ that is
2424// post-incremented.
2425BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002426 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2427 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002428 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002429 return res;
2430}
2431
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002432void MIRGraph::CalculateBasicBlockInformation() {
2433 PassDriverMEPostOpt driver(cu_);
2434 driver.Launch();
2435}
2436
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002437int MIR::DecodedInstruction::FlagsOf() const {
2438 // Calculate new index.
2439 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2440
2441 // Check if it is an extended or not.
2442 if (idx < 0) {
2443 return Instruction::FlagsOf(opcode);
2444 }
2445
2446 // For extended, we use a switch.
2447 switch (static_cast<int>(opcode)) {
2448 case kMirOpPhi:
2449 return Instruction::kContinue;
2450 case kMirOpCopy:
2451 return Instruction::kContinue;
2452 case kMirOpFusedCmplFloat:
2453 return Instruction::kContinue | Instruction::kBranch;
2454 case kMirOpFusedCmpgFloat:
2455 return Instruction::kContinue | Instruction::kBranch;
2456 case kMirOpFusedCmplDouble:
2457 return Instruction::kContinue | Instruction::kBranch;
2458 case kMirOpFusedCmpgDouble:
2459 return Instruction::kContinue | Instruction::kBranch;
2460 case kMirOpFusedCmpLong:
2461 return Instruction::kContinue | Instruction::kBranch;
2462 case kMirOpNop:
2463 return Instruction::kContinue;
2464 case kMirOpNullCheck:
2465 return Instruction::kContinue | Instruction::kThrow;
2466 case kMirOpRangeCheck:
2467 return Instruction::kContinue | Instruction::kThrow;
2468 case kMirOpDivZeroCheck:
2469 return Instruction::kContinue | Instruction::kThrow;
2470 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002471 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002472 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002473 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002474 case kMirOpSelect:
2475 return Instruction::kContinue;
2476 case kMirOpConstVector:
2477 return Instruction::kContinue;
2478 case kMirOpMoveVector:
2479 return Instruction::kContinue;
2480 case kMirOpPackedMultiply:
2481 return Instruction::kContinue;
2482 case kMirOpPackedAddition:
2483 return Instruction::kContinue;
2484 case kMirOpPackedSubtract:
2485 return Instruction::kContinue;
2486 case kMirOpPackedShiftLeft:
2487 return Instruction::kContinue;
2488 case kMirOpPackedSignedShiftRight:
2489 return Instruction::kContinue;
2490 case kMirOpPackedUnsignedShiftRight:
2491 return Instruction::kContinue;
2492 case kMirOpPackedAnd:
2493 return Instruction::kContinue;
2494 case kMirOpPackedOr:
2495 return Instruction::kContinue;
2496 case kMirOpPackedXor:
2497 return Instruction::kContinue;
2498 case kMirOpPackedAddReduce:
2499 return Instruction::kContinue;
2500 case kMirOpPackedReduce:
2501 return Instruction::kContinue;
2502 case kMirOpPackedSet:
2503 return Instruction::kContinue;
2504 case kMirOpReserveVectorRegisters:
2505 return Instruction::kContinue;
2506 case kMirOpReturnVectorRegisters:
2507 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002508 case kMirOpMemBarrier:
2509 return Instruction::kContinue;
2510 case kMirOpPackedArrayGet:
2511 return Instruction::kContinue | Instruction::kThrow;
2512 case kMirOpPackedArrayPut:
2513 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002514 case kMirOpMaddInt:
2515 case kMirOpMsubInt:
2516 case kMirOpMaddLong:
2517 case kMirOpMsubLong:
2518 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002519 default:
2520 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2521 return 0;
2522 }
2523}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002524} // namespace art