blob: 3103f96e4e19629b8fff3ac7fb0a3378d156fc71 [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"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080024#include "base/logging.h"
Ian Rogers6282dc12013-04-18 15:54:02 -070025#include "base/stl_util.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080026#include "base/stringprintf.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080027#include "base/scoped_arena_containers.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080028#include "compiler_ir.h"
buzbee311ca162013-02-28 15:56:43 -080029#include "dex_file-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080030#include "dex_flags.h"
Ian Rogers29a26482014-05-02 15:27:29 -070031#include "dex_instruction-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080032#include "driver/compiler_driver.h"
33#include "driver/dex_compilation_unit.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080034#include "dex/quick/quick_compiler.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000035#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070036#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070037#include "stack.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000038
buzbee311ca162013-02-28 15:56:43 -080039namespace art {
40
41#define MAX_PATTERN_LEN 5
42
buzbee1fd33462013-03-25 13:40:45 -070043const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
44 "Phi",
45 "Copy",
46 "FusedCmplFloat",
47 "FusedCmpgFloat",
48 "FusedCmplDouble",
49 "FusedCmpgDouble",
50 "FusedCmpLong",
51 "Nop",
52 "OpNullCheck",
53 "OpRangeCheck",
54 "OpDivZeroCheck",
55 "Check1",
56 "Check2",
57 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040058 "ConstVector",
59 "MoveVector",
60 "PackedMultiply",
61 "PackedAddition",
62 "PackedSubtract",
63 "PackedShiftLeft",
64 "PackedSignedShiftRight",
65 "PackedUnsignedShiftRight",
66 "PackedAnd",
67 "PackedOr",
68 "PackedXor",
69 "PackedAddReduce",
70 "PackedReduce",
71 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070072 "ReserveVectorRegisters",
73 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070074 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070075 "PackedArrayGet",
76 "PackedArrayPut",
Ningsheng Jiana262f772014-11-25 16:48:07 +080077 "MaddInt",
78 "MsubInt",
79 "MaddLong",
80 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070081};
82
buzbee862a7602013-04-05 10:58:54 -070083MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070084 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010085 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070086 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010087 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
88 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
Vladimir Marko1c6ea442014-12-19 18:11:35 +000089 vreg_to_ssa_map_(NULL),
90 ssa_last_defs_(NULL),
buzbee311ca162013-02-28 15:56:43 -080091 is_constant_v_(NULL),
92 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010093 use_counts_(arena->Adapter()),
94 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080095 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070096 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010097 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000098 domination_up_to_date_(false),
99 mir_ssa_rep_up_to_date_(false),
100 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100101 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
102 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
103 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
104 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
105 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
106 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
107 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100108 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -0800109 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000110 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100111 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800112 try_block_addr_(NULL),
113 entry_block_(NULL),
114 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800115 current_code_item_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100116 m_units_(arena->Adapter()),
117 method_stack_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -0800118 current_method_(kInvalidEntry),
119 current_offset_(kInvalidEntry),
120 def_count_(0),
121 opcode_count_(NULL),
buzbee1fd33462013-03-25 13:40:45 -0700122 num_ssa_regs_(0),
Vladimir Marko8081d2b2014-07-31 15:33:43 +0100123 extended_basic_blocks_(arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -0700124 method_sreg_(0),
buzbee862a7602013-04-05 10:58:54 -0700125 attributes_(METHOD_IS_LEAF), // Start with leaf assumption, change on encountering invoke.
126 checkstats_(NULL),
buzbeeb48819d2013-09-14 16:15:25 -0700127 arena_(arena),
128 backward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800129 forward_branches_(0),
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800130 num_non_special_compiler_temps_(0),
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700131 max_available_special_compiler_temps_(1), // We only need the method ptr as a special temp for now.
132 requested_backend_temp_(false),
133 compiler_temps_committed_(false),
Vladimir Markobe0e5462014-02-26 11:24:15 +0000134 punt_to_interpreter_(false),
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000135 merged_df_flags_(0u),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100136 ifield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
137 sfield_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
138 method_lowering_infos_(arena->Adapter(kArenaAllocLoweringInfo)),
Vladimir Marko8b858e12014-11-27 14:52:37 +0000139 suspend_checks_in_loops_(nullptr) {
Vladimir Markof585e542014-11-21 13:41:32 +0000140 memset(&temp_, 0, sizeof(temp_));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100141 use_counts_.reserve(256);
142 raw_use_counts_.reserve(256);
143 block_list_.reserve(100);
buzbee862a7602013-04-05 10:58:54 -0700144 try_block_addr_ = new (arena_) ArenaBitVector(arena_, 0, true /* expandable */);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700145
146
147 if (cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) {
148 // X86 requires a temp to keep track of the method address.
149 // TODO For x86_64, addressing can be done with RIP. When that is implemented,
150 // this needs to be updated to reserve 0 temps for BE.
151 max_available_non_special_compiler_temps_ = cu_->target64 ? 2 : 1;
152 reserved_temps_for_backend_ = max_available_non_special_compiler_temps_;
153 } else {
154 // Other architectures do not have a known lower bound for non-special temps.
155 // We allow the update of the max to happen at BE initialization stage and simply set 0 for now.
156 max_available_non_special_compiler_temps_ = 0;
157 reserved_temps_for_backend_ = 0;
158 }
buzbee311ca162013-02-28 15:56:43 -0800159}
160
Ian Rogers6282dc12013-04-18 15:54:02 -0700161MIRGraph::~MIRGraph() {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100162 STLDeleteElements(&block_list_);
Ian Rogers6282dc12013-04-18 15:54:02 -0700163 STLDeleteElements(&m_units_);
164}
165
buzbee311ca162013-02-28 15:56:43 -0800166/*
167 * Parse an instruction, return the length of the instruction
168 */
Ian Rogers29a26482014-05-02 15:27:29 -0700169int MIRGraph::ParseInsn(const uint16_t* code_ptr, MIR::DecodedInstruction* decoded_instruction) {
170 const Instruction* inst = Instruction::At(code_ptr);
171 decoded_instruction->opcode = inst->Opcode();
172 decoded_instruction->vA = inst->HasVRegA() ? inst->VRegA() : 0;
173 decoded_instruction->vB = inst->HasVRegB() ? inst->VRegB() : 0;
174 decoded_instruction->vB_wide = inst->HasWideVRegB() ? inst->WideVRegB() : 0;
175 decoded_instruction->vC = inst->HasVRegC() ? inst->VRegC() : 0;
176 if (inst->HasVarArgs()) {
177 inst->GetVarArgs(decoded_instruction->arg);
178 }
179 return inst->SizeInCodeUnits();
buzbee311ca162013-02-28 15:56:43 -0800180}
181
182
183/* Split an existing block from the specified code offset into two */
buzbee0d829482013-10-11 15:24:55 -0700184BasicBlock* MIRGraph::SplitBlock(DexOffset code_offset,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700185 BasicBlock* orig_block, BasicBlock** immed_pred_block_p) {
buzbee0d829482013-10-11 15:24:55 -0700186 DCHECK_GT(code_offset, orig_block->start_offset);
buzbee311ca162013-02-28 15:56:43 -0800187 MIR* insn = orig_block->first_mir_insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400188 MIR* prev = NULL; // Will be set to instruction before split.
buzbee311ca162013-02-28 15:56:43 -0800189 while (insn) {
190 if (insn->offset == code_offset) break;
buzbee0d829482013-10-11 15:24:55 -0700191 prev = insn;
buzbee311ca162013-02-28 15:56:43 -0800192 insn = insn->next;
193 }
194 if (insn == NULL) {
195 LOG(FATAL) << "Break split failed";
196 }
Mathew Zaleski33c17022014-09-15 09:44:14 -0400197 // Now insn is at the instruction where we want to split, namely
198 // insn will be the first instruction of the "bottom" block.
199 // Similarly, prev will be the last instruction of the "top" block
200
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100201 BasicBlock* bottom_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800202
203 bottom_block->start_offset = code_offset;
204 bottom_block->first_mir_insn = insn;
205 bottom_block->last_mir_insn = orig_block->last_mir_insn;
206
Junmo Park90223cc2014-08-04 18:51:21 +0900207 /* If this block was terminated by a return, conditional branch or throw,
208 * the flag needs to go with the bottom block
209 */
buzbee311ca162013-02-28 15:56:43 -0800210 bottom_block->terminated_by_return = orig_block->terminated_by_return;
211 orig_block->terminated_by_return = false;
212
Junmo Park90223cc2014-08-04 18:51:21 +0900213 bottom_block->conditional_branch = orig_block->conditional_branch;
214 orig_block->conditional_branch = false;
215
216 bottom_block->explicit_throw = orig_block->explicit_throw;
217 orig_block->explicit_throw = false;
218
buzbee311ca162013-02-28 15:56:43 -0800219 /* Handle the taken path */
220 bottom_block->taken = orig_block->taken;
buzbee0d829482013-10-11 15:24:55 -0700221 if (bottom_block->taken != NullBasicBlockId) {
222 orig_block->taken = NullBasicBlockId;
223 BasicBlock* bb_taken = GetBasicBlock(bottom_block->taken);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100224 bb_taken->ErasePredecessor(orig_block->id);
225 bb_taken->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800226 }
227
228 /* Handle the fallthrough path */
229 bottom_block->fall_through = orig_block->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700230 orig_block->fall_through = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100231 bottom_block->predecessors.push_back(orig_block->id);
buzbee0d829482013-10-11 15:24:55 -0700232 if (bottom_block->fall_through != NullBasicBlockId) {
233 BasicBlock* bb_fall_through = GetBasicBlock(bottom_block->fall_through);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100234 bb_fall_through->ErasePredecessor(orig_block->id);
235 bb_fall_through->predecessors.push_back(bottom_block->id);
buzbee311ca162013-02-28 15:56:43 -0800236 }
237
238 /* Handle the successor list */
buzbee0d829482013-10-11 15:24:55 -0700239 if (orig_block->successor_block_list_type != kNotUsed) {
240 bottom_block->successor_block_list_type = orig_block->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100241 bottom_block->successor_blocks.swap(orig_block->successor_blocks);
buzbee0d829482013-10-11 15:24:55 -0700242 orig_block->successor_block_list_type = kNotUsed;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100243 DCHECK(orig_block->successor_blocks.empty()); // Empty after the swap() above.
244 for (SuccessorBlockInfo* successor_block_info : bottom_block->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700245 BasicBlock* bb = GetBasicBlock(successor_block_info->block);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700246 if (bb != nullptr) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100247 bb->ErasePredecessor(orig_block->id);
248 bb->predecessors.push_back(bottom_block->id);
Niranjan Kumar989367a2014-06-12 12:15:48 -0700249 }
buzbee311ca162013-02-28 15:56:43 -0800250 }
251 }
252
buzbee0d829482013-10-11 15:24:55 -0700253 orig_block->last_mir_insn = prev;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700254 prev->next = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800255
buzbee311ca162013-02-28 15:56:43 -0800256 /*
257 * Update the immediate predecessor block pointer so that outgoing edges
258 * can be applied to the proper block.
259 */
260 if (immed_pred_block_p) {
261 DCHECK_EQ(*immed_pred_block_p, orig_block);
262 *immed_pred_block_p = bottom_block;
263 }
buzbeeb48819d2013-09-14 16:15:25 -0700264
265 // Associate dex instructions in the bottom block with the new container.
Vladimir Marko4376c872014-01-23 12:39:29 +0000266 DCHECK(insn != nullptr);
267 DCHECK(insn != orig_block->first_mir_insn);
268 DCHECK(insn == bottom_block->first_mir_insn);
269 DCHECK_EQ(insn->offset, bottom_block->start_offset);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400270 // Scan the "bottom" instructions, remapping them to the
271 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000272 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400273 p->bb = 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 }
279
buzbee311ca162013-02-28 15:56:43 -0800280 return bottom_block;
281}
282
283/*
284 * Given a code offset, find out the block that starts with it. If the offset
285 * is in the middle of an existing block, split it into two. If immed_pred_block_p
286 * is not non-null and is the block being split, update *immed_pred_block_p to
287 * point to the bottom block so that outgoing edges can be set up properly
288 * (by the caller)
289 * Utilizes a map for fast lookup of the typical cases.
290 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700291BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800292 BasicBlock** immed_pred_block_p,
293 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700294 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700295 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800296 }
buzbeeb48819d2013-09-14 16:15:25 -0700297
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800298 int block_id = (*dex_pc_to_block_map)[code_offset];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100299 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700300
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700301 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700302 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700303 return bb;
304 }
buzbee311ca162013-02-28 15:56:43 -0800305
buzbeeb48819d2013-09-14 16:15:25 -0700306 // No direct hit.
307 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700308 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800309 }
310
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700311 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700312 // The target exists somewhere in an existing block.
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800313 BasicBlock* bottom_block = SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
314 DCHECK(bottom_block != nullptr);
315 MIR* p = bottom_block->first_mir_insn;
316 BasicBlock* orig_block = bb;
317 DCHECK_EQ((*dex_pc_to_block_map)[p->offset], orig_block->id);
318 // Scan the "bottom" instructions, remapping them to the
319 // newly created "bottom" block.
320 (*dex_pc_to_block_map)[p->offset] = bottom_block->id;
321 while (p != bottom_block->last_mir_insn) {
322 p = p->next;
323 DCHECK(p != nullptr);
324 int opcode = p->dalvikInsn.opcode;
325 /*
326 * Some messiness here to ensure that we only enter real opcodes and only the
327 * first half of a potentially throwing instruction that has been split into
328 * CHECK and work portions. Since the 2nd half of a split operation is always
329 * the first in a BasicBlock, we can't hit it here.
330 */
331 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
332 BasicBlockId mapped_id = (*dex_pc_to_block_map)[p->offset];
333 // At first glance the instructions should all be mapped to orig_block.
334 // However, multiple instructions may correspond to the same dex, hence an earlier
335 // instruction may have already moved the mapping for dex to bottom_block.
336 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
337 (*dex_pc_to_block_map)[p->offset] = bottom_block->id;
338 }
339 }
340 return bottom_block;
buzbeeb48819d2013-09-14 16:15:25 -0700341 }
342
343 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100344 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800345 bb->start_offset = code_offset;
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800346 (*dex_pc_to_block_map)[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800347 return bb;
348}
349
buzbeeb48819d2013-09-14 16:15:25 -0700350
buzbee311ca162013-02-28 15:56:43 -0800351/* Identify code range in try blocks and set up the empty catch blocks */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800352void MIRGraph::ProcessTryCatchBlocks(ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
buzbee311ca162013-02-28 15:56:43 -0800353 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700354 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800355
356 if (tries_size == 0) {
357 return;
358 }
359
360 for (int i = 0; i < tries_size; i++) {
361 const DexFile::TryItem* pTry =
362 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700363 DexOffset start_offset = pTry->start_addr_;
364 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800365 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700366 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800367 }
368 }
369
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700370 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700371 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800372 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
373 for (uint32_t idx = 0; idx < handlers_size; idx++) {
374 CatchHandlerIterator iterator(handlers_ptr);
375 for (; iterator.HasNext(); iterator.Next()) {
376 uint32_t address = iterator.GetHandlerAddress();
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800377 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr, dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800378 }
379 handlers_ptr = iterator.EndDataPointer();
380 }
381}
382
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100383bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
384 NarrowDexOffset catch_offset) {
385 // Catches for monitor-exit during stack unwinding have the pattern
386 // move-exception (move)* (goto)? monitor-exit throw
387 // In the currently generated dex bytecode we see these catching a bytecode range including
388 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
389 // it's the case for a given monitor-exit and catch block so that we can ignore it.
390 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
391 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
392 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700393 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100394 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
395 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700396 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100397 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
398 if (check_insn->VRegA_11x() == monitor_reg) {
399 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
400 return false;
401 }
402 check_insn = check_insn->Next();
403 while (true) {
404 int dest = -1;
405 bool wide = false;
406 switch (check_insn->Opcode()) {
407 case Instruction::MOVE_WIDE:
408 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700409 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100410 case Instruction::MOVE_OBJECT:
411 case Instruction::MOVE:
412 dest = check_insn->VRegA_12x();
413 break;
414
415 case Instruction::MOVE_WIDE_FROM16:
416 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700417 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100418 case Instruction::MOVE_OBJECT_FROM16:
419 case Instruction::MOVE_FROM16:
420 dest = check_insn->VRegA_22x();
421 break;
422
423 case Instruction::MOVE_WIDE_16:
424 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700425 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100426 case Instruction::MOVE_OBJECT_16:
427 case Instruction::MOVE_16:
428 dest = check_insn->VRegA_32x();
429 break;
430
431 case Instruction::GOTO:
432 case Instruction::GOTO_16:
433 case Instruction::GOTO_32:
434 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700435 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100436 default:
437 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
438 check_insn->VRegA_11x() == monitor_reg;
439 }
440
441 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
442 return false;
443 }
444
445 check_insn = check_insn->Next();
446 }
447}
448
buzbee311ca162013-02-28 15:56:43 -0800449/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700450BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
451 int width, int flags, const uint16_t* code_ptr,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800452 const uint16_t* code_end,
453 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
buzbee0d829482013-10-11 15:24:55 -0700454 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800455 switch (insn->dalvikInsn.opcode) {
456 case Instruction::GOTO:
457 case Instruction::GOTO_16:
458 case Instruction::GOTO_32:
459 target += insn->dalvikInsn.vA;
460 break;
461 case Instruction::IF_EQ:
462 case Instruction::IF_NE:
463 case Instruction::IF_LT:
464 case Instruction::IF_GE:
465 case Instruction::IF_GT:
466 case Instruction::IF_LE:
467 cur_block->conditional_branch = true;
468 target += insn->dalvikInsn.vC;
469 break;
470 case Instruction::IF_EQZ:
471 case Instruction::IF_NEZ:
472 case Instruction::IF_LTZ:
473 case Instruction::IF_GEZ:
474 case Instruction::IF_GTZ:
475 case Instruction::IF_LEZ:
476 cur_block->conditional_branch = true;
477 target += insn->dalvikInsn.vB;
478 break;
479 default:
480 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
481 }
buzbeeb48819d2013-09-14 16:15:25 -0700482 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700483 BasicBlock* taken_block = FindBlock(target, /* create */ true,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800484 /* immed_pred_block_p */ &cur_block,
485 dex_pc_to_block_map);
buzbee0d829482013-10-11 15:24:55 -0700486 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100487 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800488
489 /* Always terminate the current block for conditional branches */
490 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700491 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800492 /* create */
493 true,
494 /* immed_pred_block_p */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800495 &cur_block,
496 dex_pc_to_block_map);
buzbee0d829482013-10-11 15:24:55 -0700497 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100498 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800499 } else if (code_ptr < code_end) {
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800500 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr, dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800501 }
502 return cur_block;
503}
504
505/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800506BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800507 int width, int flags,
508 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700509 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800510 const uint16_t* switch_data =
511 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
512 int size;
513 const int* keyTable;
514 const int* target_table;
515 int i;
516 int first_key;
517
518 /*
519 * Packed switch data format:
520 * ushort ident = 0x0100 magic value
521 * ushort size number of entries in the table
522 * int first_key first (and lowest) switch case value
523 * int targets[size] branch targets, relative to switch opcode
524 *
525 * Total size is (4+size*2) 16-bit code units.
526 */
527 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
528 DCHECK_EQ(static_cast<int>(switch_data[0]),
529 static_cast<int>(Instruction::kPackedSwitchSignature));
530 size = switch_data[1];
531 first_key = switch_data[2] | (switch_data[3] << 16);
532 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700533 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800534 /*
535 * Sparse switch data format:
536 * ushort ident = 0x0200 magic value
537 * ushort size number of entries in the table; > 0
538 * int keys[size] keys, sorted low-to-high; 32-bit aligned
539 * int targets[size] branch targets, relative to switch opcode
540 *
541 * Total size is (2+size*4) 16-bit code units.
542 */
543 } else {
544 DCHECK_EQ(static_cast<int>(switch_data[0]),
545 static_cast<int>(Instruction::kSparseSwitchSignature));
546 size = switch_data[1];
547 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
548 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700549 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800550 }
551
buzbee0d829482013-10-11 15:24:55 -0700552 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800553 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700554 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800555 }
buzbee0d829482013-10-11 15:24:55 -0700556 cur_block->successor_block_list_type =
557 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100558 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800559
560 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700561 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800562 /* immed_pred_block_p */ &cur_block,
563 dex_pc_to_block_map);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700564 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700565 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000566 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700567 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800568 successor_block_info->key =
569 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
570 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100571 cur_block->successor_blocks.push_back(successor_block_info);
572 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800573 }
574
575 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700576 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800577 /* immed_pred_block_p */ nullptr,
578 dex_pc_to_block_map);
buzbee0d829482013-10-11 15:24:55 -0700579 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100580 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800581 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800582}
583
584/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700585BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
586 int width, int flags, ArenaBitVector* try_block_addr,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800587 const uint16_t* code_ptr, const uint16_t* code_end,
588 ScopedArenaVector<uint16_t>* dex_pc_to_block_map) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700589 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700590 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800591 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800592
593 /* In try block */
594 if (in_try_block) {
595 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
596
buzbee0d829482013-10-11 15:24:55 -0700597 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800598 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
599 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700600 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800601 }
602
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700603 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700604 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800605 nullptr /* immed_pred_block_p */,
606 dex_pc_to_block_map);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100607 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
608 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
609 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
610 continue;
611 }
612 if (cur_block->successor_block_list_type == kNotUsed) {
613 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100614 }
buzbee311ca162013-02-28 15:56:43 -0800615 catch_block->catch_entry = true;
616 if (kIsDebugBuild) {
617 catches_.insert(catch_block->start_offset);
618 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700619 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000620 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700621 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800622 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100623 cur_block->successor_blocks.push_back(successor_block_info);
624 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800625 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100626 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
627 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100628 bool build_all_edges =
629 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100630 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100631 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700632 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800633 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100634 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800635 }
636
buzbee17189ac2013-11-08 11:07:02 -0800637 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800638 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700639 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700640 // Force creation of new block following THROW via side-effect.
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800641 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr, dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800642 }
643 if (!in_try_block) {
644 // Don't split a THROW that can't rethrow - we're done.
645 return cur_block;
646 }
647 }
648
buzbee17189ac2013-11-08 11:07:02 -0800649 if (!build_all_edges) {
650 /*
651 * Even though there is an exception edge here, control cannot return to this
652 * method. Thus, for the purposes of dataflow analysis and optimization, we can
653 * ignore the edge. Doing this reduces compile time, and increases the scope
654 * of the basic-block level optimization pass.
655 */
656 return cur_block;
657 }
658
buzbee311ca162013-02-28 15:56:43 -0800659 /*
660 * Split the potentially-throwing instruction into two parts.
661 * The first half will be a pseudo-op that captures the exception
662 * edges and terminates the basic block. It always falls through.
663 * Then, create a new basic block that begins with the throwing instruction
664 * (minus exceptions). Note: this new basic block must NOT be entered into
665 * the block_map. If the potentially-throwing instruction is the target of a
666 * future branch, we need to find the check psuedo half. The new
667 * basic block containing the work portion of the instruction should
668 * only be entered via fallthrough from the block containing the
669 * pseudo exception edge MIR. Note also that this new block is
670 * not automatically terminated after the work portion, and may
671 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700672 *
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800673 * Note also that the dex_pc_to_block_map entry for the potentially
buzbeeb48819d2013-09-14 16:15:25 -0700674 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800675 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100676 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800677 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700678 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100679 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700680 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800681 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700682 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700683 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800684 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700685 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800686 return new_block;
687}
688
689/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
690void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700691 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700692 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800693 current_code_item_ = code_item;
694 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
695 current_method_ = m_units_.size();
696 current_offset_ = 0;
697 // TODO: will need to snapshot stack image and use that as the mir context identification.
698 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000699 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
700 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800701 const uint16_t* code_ptr = current_code_item_->insns_;
702 const uint16_t* code_end =
703 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
704
705 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700706 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100707 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800708 // FindBlock lookup cache.
709 ScopedArenaAllocator allocator(&cu_->arena_stack);
710 ScopedArenaVector<uint16_t> dex_pc_to_block_map(allocator.Adapter());
711 dex_pc_to_block_map.resize(dex_pc_to_block_map.size() +
712 current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700713
buzbee311ca162013-02-28 15:56:43 -0800714 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700715 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
716 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800717
718 // If this is the first method, set up default entry and exit blocks.
719 if (current_method_ == 0) {
720 DCHECK(entry_block_ == NULL);
721 DCHECK(exit_block_ == NULL);
Vladimir Markoffda4992014-12-18 17:05:58 +0000722 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700723 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100724 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700725 DCHECK_EQ(null_block->id, NullBasicBlockId);
726 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100727 entry_block_ = CreateNewBB(kEntryBlock);
728 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800729 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
730 cu_->dex_file = &dex_file;
731 cu_->class_def_idx = class_def_idx;
732 cu_->method_idx = method_idx;
733 cu_->access_flags = access_flags;
734 cu_->invoke_type = invoke_type;
735 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800736 } else {
737 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
738 /*
739 * Will need to manage storage for ins & outs, push prevous state and update
740 * insert point.
741 */
742 }
743
744 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100745 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700746 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800747 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700748 // TODO: for inlining support, insert at the insert point rather than entry block.
749 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100750 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800751
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000752 /* Identify code range in try blocks and set up the empty catch blocks */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800753 ProcessTryCatchBlocks(&dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800754
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000755 uint64_t merged_df_flags = 0u;
756
buzbee311ca162013-02-28 15:56:43 -0800757 /* Parse all instructions and put them into containing basic blocks */
758 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700759 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800760 insn->offset = current_offset_;
761 insn->m_unit_index = current_method_;
762 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800763 Instruction::Code opcode = insn->dalvikInsn.opcode;
764 if (opcode_count_ != NULL) {
765 opcode_count_[static_cast<int>(opcode)]++;
766 }
767
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700768 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800769 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800770
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700771 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000772 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800773
774 if (df_flags & DF_HAS_DEFS) {
775 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
776 }
777
buzbee1da1e2f2013-11-15 13:37:01 -0800778 if (df_flags & DF_LVN) {
779 cur_block->use_lvn = true; // Run local value numbering on this basic block.
780 }
781
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700782 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700783 if (opcode == Instruction::NOP) {
784 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
785 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
786 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
787 uint16_t following_raw_instruction = code_ptr[1];
788 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
789 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
790 (following_raw_instruction == Instruction::kArrayDataSignature)) {
791 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
792 }
793 }
794 if (width == 1) {
795 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700796 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700797 } else {
buzbee0d829482013-10-11 15:24:55 -0700798 DCHECK(cur_block->fall_through == NullBasicBlockId);
799 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800800 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700801 flags &= ~Instruction::kContinue;
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800802 FindBlock(current_offset_ + width, /* create */ true,
803 /* immed_pred_block_p */ nullptr, &dex_pc_to_block_map);
buzbee27247762013-07-28 12:03:58 -0700804 }
805 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700806 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700807 }
808
buzbeeb48819d2013-09-14 16:15:25 -0700809 // Associate the starting dex_pc for this opcode with its containing basic block.
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800810 dex_pc_to_block_map[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700811
buzbee27247762013-07-28 12:03:58 -0700812 code_ptr += width;
813
buzbee311ca162013-02-28 15:56:43 -0800814 if (flags & Instruction::kBranch) {
815 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800816 width, flags, code_ptr, code_end, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800817 } else if (flags & Instruction::kReturn) {
818 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700819 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100820 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800821 /*
822 * Terminate the current block if there are instructions
823 * afterwards.
824 */
825 if (code_ptr < code_end) {
826 /*
827 * Create a fallthrough block for real instructions
828 * (incl. NOP).
829 */
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800830 FindBlock(current_offset_ + width, /* create */ true,
831 /* immed_pred_block_p */ nullptr, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800832 }
833 } else if (flags & Instruction::kThrow) {
834 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800835 code_ptr, code_end, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800836 } else if (flags & Instruction::kSwitch) {
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800837 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width,
838 flags, &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800839 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700840 if (verify_flags & Instruction::kVerifyVarArgRange ||
841 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800842 /*
843 * The Quick backend's runtime model includes a gap between a method's
844 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
845 * which spans the gap is somewhat complicated, and should not happen
846 * in normal usage of dx. Punt to the interpreter.
847 */
848 int first_reg_in_range = insn->dalvikInsn.vC;
849 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
850 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
851 punt_to_interpreter_ = true;
852 }
853 }
buzbee311ca162013-02-28 15:56:43 -0800854 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700855 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
Chao-ying Fu72f53af2014-11-11 16:48:40 -0800856 /* immed_pred_block_p */ nullptr,
857 &dex_pc_to_block_map);
buzbee311ca162013-02-28 15:56:43 -0800858 if (next_block) {
859 /*
860 * The next instruction could be the target of a previously parsed
861 * forward branch so a block is already created. If the current
862 * instruction is not an unconditional branch, connect them through
863 * the fall-through link.
864 */
buzbee0d829482013-10-11 15:24:55 -0700865 DCHECK(cur_block->fall_through == NullBasicBlockId ||
866 GetBasicBlock(cur_block->fall_through) == next_block ||
867 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800868
buzbee0d829482013-10-11 15:24:55 -0700869 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
870 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100871 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800872 }
873 cur_block = next_block;
874 }
875 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000876 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000877
buzbee311ca162013-02-28 15:56:43 -0800878 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
879 DumpCFG("/sdcard/1_post_parse_cfg/", true);
880 }
881
882 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700883 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800884 }
885}
886
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700887void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800888 DCHECK(opcode_count_ != NULL);
889 LOG(INFO) << "Opcode Count";
890 for (int i = 0; i < kNumPackedOpcodes; i++) {
891 if (opcode_count_[i] != 0) {
892 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
893 << " " << opcode_count_[i];
894 }
895 }
896}
897
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700898uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
899 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
900 return oat_data_flow_attributes_[opcode];
901}
902
903uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
904 DCHECK(mir != nullptr);
905 Instruction::Code opcode = mir->dalvikInsn.opcode;
906 return GetDataFlowAttributes(opcode);
907}
908
Andreas Gampecee97e52014-12-19 15:30:11 -0800909// The path can easily surpass FS limits because of parameters etc. Use pathconf to get FS
910// restrictions here. Note that a successful invocation will return an actual value. If the path
911// is too long for some reason, the return will be ENAMETOOLONG. Then cut off part of the name.
912//
913// It's possible the path is not valid, or some other errors appear. In that case return false.
914static bool CreateDumpFile(std::string& fname, const char* dir_prefix, NarrowDexOffset start_offset,
915 const char *suffix, int nr, std::string* output) {
916 std::string dir = StringPrintf("./%s", dir_prefix);
917 int64_t max_name_length = pathconf(dir.c_str(), _PC_NAME_MAX);
918 if (max_name_length <= 0) {
919 PLOG(ERROR) << "Could not get file name restrictions for " << dir;
920 return false;
921 }
922
923 std::string name = StringPrintf("%s%x%s_%d.dot", fname.c_str(), start_offset,
924 suffix == nullptr ? "" : suffix, nr);
925 std::string fpath;
926 if (static_cast<int64_t>(name.size()) > max_name_length) {
927 std::string suffix_str = StringPrintf("_%d.dot", nr);
928 name = name.substr(0, static_cast<size_t>(max_name_length) - suffix_str.size()) + suffix_str;
929 }
930 // Sanity check.
931 DCHECK_LE(name.size(), static_cast<size_t>(max_name_length));
932
933 *output = StringPrintf("%s%s", dir_prefix, name.c_str());
934 return true;
935}
936
buzbee311ca162013-02-28 15:56:43 -0800937// TODO: use a configurable base prefix, and adjust callers to supply pass name.
938/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800939void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800940 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700941 static AtomicInteger cnt(0);
942
943 // Increment counter to get a unique file number.
944 cnt++;
Andreas Gampecee97e52014-12-19 15:30:11 -0800945 int nr = cnt.LoadRelaxed();
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700946
buzbee311ca162013-02-28 15:56:43 -0800947 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
948 ReplaceSpecialChars(fname);
Andreas Gampecee97e52014-12-19 15:30:11 -0800949 std::string fpath;
950 if (!CreateDumpFile(fname, dir_prefix, GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
951 suffix, nr, &fpath)) {
952 LOG(ERROR) << "Could not create dump file name for " << fname;
953 return;
954 }
955 file = fopen(fpath.c_str(), "w");
buzbee311ca162013-02-28 15:56:43 -0800956 if (file == NULL) {
Andreas Gampecee97e52014-12-19 15:30:11 -0800957 PLOG(ERROR) << "Could not open " << fpath << " for DumpCFG.";
buzbee311ca162013-02-28 15:56:43 -0800958 return;
959 }
960 fprintf(file, "digraph G {\n");
961
962 fprintf(file, " rankdir=TB\n");
963
964 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
965 int idx;
966
967 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100968 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700969 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700970 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800971 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700972 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800973 if (bb->block_type == kEntryBlock) {
974 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
975 } else if (bb->block_type == kExitBlock) {
976 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
977 } else if (bb->block_type == kDalvikByteCode) {
978 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
979 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700980 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800981 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
982 bb->first_mir_insn ? " | " : " ");
983 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
984 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800985 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400986 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700987 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
988 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400989 extended_mir_op_names_[opcode - kMirOpFirst],
990 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
991 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700992 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700993 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700994 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100995 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
996 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800997 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400998 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800999 }
1000 fprintf(file, " }\"];\n\n");
1001 } else if (bb->block_type == kExceptionHandling) {
1002 char block_name[BLOCK_NAME_LEN];
1003
1004 GetBlockName(bb, block_name);
1005 fprintf(file, " %s [shape=invhouse];\n", block_name);
1006 }
1007
1008 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
1009
buzbee0d829482013-10-11 15:24:55 -07001010 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -08001011 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -07001012 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001013 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
1014 block_name1, block_name2);
1015 }
buzbee0d829482013-10-11 15:24:55 -07001016 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -08001017 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -07001018 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001019 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
1020 }
1021
buzbee0d829482013-10-11 15:24:55 -07001022 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -08001023 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
1024 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -07001025 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -08001026
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001027 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -08001028 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001029 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001030 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001031 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001032 succ_id,
buzbee311ca162013-02-28 15:56:43 -08001033 successor_block_info->key,
1034 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001035 (succ_id != last_succ_id) ? " | " : " ");
1036 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -08001037 }
1038 fprintf(file, " }\"];\n\n");
1039
1040 GetBlockName(bb, block_name1);
1041 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1042 block_name1, bb->start_offset, bb->id);
1043
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001044 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001045 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001046 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001047 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001048
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001049 GetBlockName(dest_block, block_name2);
1050 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1051 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001052 }
1053 }
1054 fprintf(file, "\n");
1055
1056 if (cu_->verbose) {
1057 /* Display the dominator tree */
1058 GetBlockName(bb, block_name1);
1059 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1060 block_name1, block_name1);
1061 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001062 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001063 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1064 }
1065 }
1066 }
1067 fprintf(file, "}\n");
1068 fclose(file);
1069}
1070
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001071/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001072void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001073 // Insert it after the last MIR.
1074 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001075}
1076
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001077void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1078 // Insert it after the last MIR.
1079 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1080}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001081
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001082void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1083 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1084 MIR* new_mir = *it;
1085
1086 // Add a copy of each MIR.
1087 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1088 }
buzbee1fd33462013-03-25 13:40:45 -07001089}
1090
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001091/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001092void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001093 InsertMIRListAfter(current_mir, new_mir, new_mir);
1094}
buzbee1fd33462013-03-25 13:40:45 -07001095
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001096void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1097 // If no MIR, we are done.
1098 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1099 return;
buzbee1fd33462013-03-25 13:40:45 -07001100 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001101
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001102 // If insert_after is null, assume BB is empty.
1103 if (insert_after == nullptr) {
1104 first_mir_insn = first_list_mir;
1105 last_mir_insn = last_list_mir;
1106 last_list_mir->next = nullptr;
1107 } else {
1108 MIR* after_list = insert_after->next;
1109 insert_after->next = first_list_mir;
1110 last_list_mir->next = after_list;
1111 if (after_list == nullptr) {
1112 last_mir_insn = last_list_mir;
1113 }
1114 }
1115
1116 // Set this BB to be the basic block of the MIRs.
1117 MIR* last = last_list_mir->next;
1118 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1119 mir->bb = id;
1120 }
1121}
1122
1123/* Insert an MIR instruction to the head of a basic block. */
1124void BasicBlock::PrependMIR(MIR* mir) {
1125 InsertMIRListBefore(first_mir_insn, mir, mir);
1126}
1127
1128void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1129 // Insert it before the first MIR.
1130 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1131}
1132
1133void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1134 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1135 MIR* mir = *it;
1136
1137 InsertMIRListBefore(first_mir_insn, mir, mir);
1138 }
1139}
1140
1141/* Insert a MIR instruction before the specified MIR. */
1142void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1143 // Insert as a single element list.
1144 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001145}
1146
1147MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1148 MIR* current = first_mir_insn;
1149
1150 while (current != nullptr) {
1151 MIR* next = current->next;
1152
1153 if (next == mir) {
1154 return current;
1155 }
1156
1157 current = next;
1158 }
1159
1160 return nullptr;
1161}
1162
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001163void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1164 // If no MIR, we are done.
1165 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1166 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001167 }
1168
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001169 // If insert_before is null, assume BB is empty.
1170 if (insert_before == nullptr) {
1171 first_mir_insn = first_list_mir;
1172 last_mir_insn = last_list_mir;
1173 last_list_mir->next = nullptr;
1174 } else {
1175 if (first_mir_insn == insert_before) {
1176 last_list_mir->next = first_mir_insn;
1177 first_mir_insn = first_list_mir;
1178 } else {
1179 // Find the preceding MIR.
1180 MIR* before_list = FindPreviousMIR(insert_before);
1181 DCHECK(before_list != nullptr);
1182 before_list->next = first_list_mir;
1183 last_list_mir->next = insert_before;
1184 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001185 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001186
1187 // Set this BB to be the basic block of the MIRs.
1188 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1189 mir->bb = id;
1190 }
1191}
1192
1193bool BasicBlock::RemoveMIR(MIR* mir) {
1194 // Remove as a single element list.
1195 return RemoveMIRList(mir, mir);
1196}
1197
1198bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1199 if (first_list_mir == nullptr) {
1200 return false;
1201 }
1202
1203 // Try to find the MIR.
1204 MIR* before_list = nullptr;
1205 MIR* after_list = nullptr;
1206
1207 // If we are removing from the beginning of the MIR list.
1208 if (first_mir_insn == first_list_mir) {
1209 before_list = nullptr;
1210 } else {
1211 before_list = FindPreviousMIR(first_list_mir);
1212 if (before_list == nullptr) {
1213 // We did not find the mir.
1214 return false;
1215 }
1216 }
1217
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001218 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001219 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001220 mir->bb = NullBasicBlockId;
1221 }
1222
1223 after_list = last_list_mir->next;
1224
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001225 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001226 if (before_list == nullptr) {
1227 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001228 } else {
1229 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001230 }
1231
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001232 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001233 if (after_list == nullptr) {
1234 last_mir_insn = before_list;
1235 }
1236
1237 return true;
buzbee1fd33462013-03-25 13:40:45 -07001238}
1239
Vladimir Marko26e7d452014-11-24 14:09:46 +00001240MIR* BasicBlock::GetFirstNonPhiInsn() {
1241 MIR* mir = first_mir_insn;
1242 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1243 mir = mir->next;
1244 }
1245 return mir;
1246}
1247
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001248MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001249 MIR* next_mir = nullptr;
1250
1251 if (current != nullptr) {
1252 next_mir = current->next;
1253 }
1254
1255 if (next_mir == nullptr) {
1256 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001257 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1258 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001259 }
1260 }
1261
1262 return next_mir;
1263}
1264
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001265static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1266 DCHECK(decoded_mir != nullptr);
1267 OpSize type = static_cast<OpSize>(type_size >> 16);
1268 uint16_t vect_size = (type_size & 0xFFFF);
1269
1270 // Now print the type and vector size.
1271 std::stringstream ss;
1272 ss << " (type:";
1273 ss << type;
1274 ss << " vectsize:";
1275 ss << vect_size;
1276 ss << ")";
1277
1278 decoded_mir->append(ss.str());
1279}
1280
1281void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1282 DCHECK(decoded_mir != nullptr);
1283 int opcode = mir->dalvikInsn.opcode;
1284 SSARepresentation* ssa_rep = mir->ssa_rep;
1285 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1286 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1287
Vladimirf41b92c2014-10-13 13:41:38 +07001288 if (opcode < kMirOpFirst) {
1289 return; // It is not an extended instruction.
1290 }
1291
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001292 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1293
1294 switch (opcode) {
1295 case kMirOpPhi: {
1296 if (defs > 0 && uses > 0) {
1297 BasicBlockId* incoming = mir->meta.phi_incoming;
1298 decoded_mir->append(StringPrintf(" %s = (%s",
1299 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1300 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1301 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1302 for (int i = 1; i < uses; i++) {
1303 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1304 }
1305 decoded_mir->append(")");
1306 }
1307 break;
1308 }
1309 case kMirOpCopy:
1310 if (ssa_rep != nullptr) {
1311 decoded_mir->append(" ");
1312 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1313 if (defs > 1) {
1314 decoded_mir->append(", ");
1315 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1316 }
1317 decoded_mir->append(" = ");
1318 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1319 if (uses > 1) {
1320 decoded_mir->append(", ");
1321 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1322 }
1323 } else {
1324 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1325 }
1326 break;
1327 case kMirOpFusedCmplFloat:
1328 case kMirOpFusedCmpgFloat:
1329 case kMirOpFusedCmplDouble:
1330 case kMirOpFusedCmpgDouble:
1331 case kMirOpFusedCmpLong:
1332 if (ssa_rep != nullptr) {
1333 decoded_mir->append(" ");
1334 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1335 for (int i = 1; i < uses; i++) {
1336 decoded_mir->append(", ");
1337 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1338 }
1339 } else {
1340 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1341 }
1342 break;
1343 case kMirOpMoveVector:
1344 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1345 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1346 break;
1347 case kMirOpPackedAddition:
1348 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1349 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1350 break;
1351 case kMirOpPackedMultiply:
1352 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1353 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1354 break;
1355 case kMirOpPackedSubtract:
1356 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1357 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1358 break;
1359 case kMirOpPackedAnd:
1360 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1361 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1362 break;
1363 case kMirOpPackedOr:
1364 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1365 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1366 break;
1367 case kMirOpPackedXor:
1368 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1369 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1370 break;
1371 case kMirOpPackedShiftLeft:
1372 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1373 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1374 break;
1375 case kMirOpPackedUnsignedShiftRight:
1376 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1377 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1378 break;
1379 case kMirOpPackedSignedShiftRight:
1380 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1381 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1382 break;
1383 case kMirOpConstVector:
1384 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1385 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1386 break;
1387 case kMirOpPackedSet:
1388 if (ssa_rep != nullptr) {
1389 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1390 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1391 if (uses > 1) {
1392 decoded_mir->append(", ");
1393 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1394 }
1395 } else {
1396 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1397 }
1398 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1399 break;
1400 case kMirOpPackedAddReduce:
1401 if (ssa_rep != nullptr) {
1402 decoded_mir->append(" ");
1403 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1404 if (defs > 1) {
1405 decoded_mir->append(", ");
1406 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1407 }
1408 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1409 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1410 if (uses > 1) {
1411 decoded_mir->append(", ");
1412 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1413 }
1414 } else {
1415 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1416 }
1417 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1418 break;
1419 case kMirOpPackedReduce:
1420 if (ssa_rep != nullptr) {
1421 decoded_mir->append(" ");
1422 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1423 if (defs > 1) {
1424 decoded_mir->append(", ");
1425 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1426 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001427 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001428 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001429 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1430 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001431 }
1432 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1433 break;
1434 case kMirOpReserveVectorRegisters:
1435 case kMirOpReturnVectorRegisters:
1436 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1437 break;
1438 case kMirOpMemBarrier: {
1439 decoded_mir->append(" type:");
1440 std::stringstream ss;
1441 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1442 decoded_mir->append(ss.str());
1443 break;
1444 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001445 case kMirOpPackedArrayGet:
1446 case kMirOpPackedArrayPut:
1447 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1448 if (ssa_rep != nullptr) {
1449 decoded_mir->append(StringPrintf(", %s[%s]",
1450 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1451 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1452 } else {
1453 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1454 }
1455 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1456 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001457 case kMirOpMaddInt:
1458 case kMirOpMsubInt:
1459 case kMirOpMaddLong:
1460 case kMirOpMsubLong:
1461 if (ssa_rep != nullptr) {
1462 decoded_mir->append(" ");
1463 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1464 if (defs > 1) {
1465 decoded_mir->append(", ");
1466 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1467 }
1468 for (int i = 0; i < uses; i++) {
1469 decoded_mir->append(", ");
1470 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1471 }
1472 } else {
1473 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1474 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1475 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1476 }
1477 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001478 default:
1479 break;
1480 }
1481}
1482
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001483char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001484 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001485 std::string str;
1486 int flags = 0;
1487 int opcode = insn.opcode;
1488 char* ret;
1489 bool nop = false;
1490 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001491 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001492
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001493 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001494 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1495 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1496 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001497 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001498 insn = mir->meta.throw_insn->dalvikInsn;
1499 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001500 opcode = insn.opcode;
1501 } else if (opcode == kMirOpNop) {
1502 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001503 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1504 // Recover original opcode.
1505 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1506 opcode = insn.opcode;
1507 }
buzbee1fd33462013-03-25 13:40:45 -07001508 nop = true;
1509 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001510 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1511 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001512
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001513 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001514 // Note that this does not check the MIR's opcode in all cases. In cases where it
1515 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1516 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001517 } else {
1518 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001519 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001520 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001521
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001522 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001523 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1524 (dalvik_format == Instruction::k3rc));
1525 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001526 str.append(" ");
1527 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1528 if (defs > 1) {
1529 str.append(", ");
1530 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1531 }
buzbee1fd33462013-03-25 13:40:45 -07001532 if (uses != 0) {
1533 str.append(", ");
1534 }
1535 }
1536 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001537 str.append(" ");
1538 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001539 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1540 // For the listing, skip the high sreg.
1541 i++;
1542 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001543 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001544 str.append(",");
1545 }
1546 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001547
buzbee1fd33462013-03-25 13:40:45 -07001548 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001549 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001550 case Instruction::k21s:
1551 case Instruction::k31i:
1552 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001553 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001554 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001555 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001556 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001557 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001558 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001559 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001560 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001561 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001562 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001563 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001564 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001565 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001566 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001567 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001568 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001569 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001570 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001571 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001572 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001573
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001574 if ((flags & Instruction::kBranch) != 0) {
1575 // For branches, decode the instructions to print out the branch targets.
1576 int offset = 0;
1577 switch (dalvik_format) {
1578 case Instruction::k21t:
1579 offset = insn.vB;
1580 break;
1581 case Instruction::k22t:
1582 offset = insn.vC;
1583 break;
1584 case Instruction::k10t:
1585 case Instruction::k20t:
1586 case Instruction::k30t:
1587 offset = insn.vA;
1588 break;
1589 default:
1590 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001591 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001592 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001593 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001594 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1595 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001596
1597 if (nop) {
1598 str.append("]--optimized away");
1599 }
buzbee1fd33462013-03-25 13:40:45 -07001600 }
1601 int length = str.length() + 1;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001602 ret = arena_->AllocArray<char>(length, kArenaAllocDFInfo);
buzbee1fd33462013-03-25 13:40:45 -07001603 strncpy(ret, str.c_str(), length);
1604 return ret;
1605}
1606
1607/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001608void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001609 static const struct { const char before; const char after; } match[] = {
1610 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1611 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1612 };
buzbee1fd33462013-03-25 13:40:45 -07001613 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1614 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1615 }
1616}
1617
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001618std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001619 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1620 // the arena. We should be smarter and just place straight into the arena, or compute the
1621 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001622 int vreg = SRegToVReg(ssa_reg);
1623 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1624 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1625 } else {
1626 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1627 }
buzbee1fd33462013-03-25 13:40:45 -07001628}
1629
1630// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001631std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001632 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001633 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001634 return GetSSAName(ssa_reg);
1635 }
1636 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001637 if (!singles_only && reg_location_[ssa_reg].wide &&
1638 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001639 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001640 ConstantValueWide(reg_location_[ssa_reg]));
1641 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001642 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001643 ConstantValue(reg_location_[ssa_reg]));
1644 }
1645 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001646 int vreg = SRegToVReg(ssa_reg);
1647 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1648 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1649 } else {
1650 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1651 }
buzbee1fd33462013-03-25 13:40:45 -07001652 }
1653}
1654
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001655void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001656 switch (bb->block_type) {
1657 case kEntryBlock:
1658 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1659 break;
1660 case kExitBlock:
1661 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1662 break;
1663 case kDalvikByteCode:
1664 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1665 break;
1666 case kExceptionHandling:
1667 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1668 bb->id);
1669 break;
1670 default:
1671 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1672 break;
1673 }
1674}
1675
Serguei Katkov717a3e42014-11-13 17:19:42 +06001676const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1677 const DexFile::MethodId& method_id =
1678 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1679 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1680}
1681
buzbee1fd33462013-03-25 13:40:45 -07001682/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001683void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001684 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001685 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001686 "Entry Block",
1687 "Code Block",
1688 "Exit Block",
1689 "Exception Handling",
1690 "Catch Block"
1691 };
1692
1693 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001694 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001695 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001696
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001697 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001698 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1699 bb->id,
1700 block_type_names[bb->block_type],
1701 bb->start_offset,
1702 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1703 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001704 if (bb->taken != NullBasicBlockId) {
1705 LOG(INFO) << " Taken branch: block " << bb->taken
1706 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001707 }
buzbee0d829482013-10-11 15:24:55 -07001708 if (bb->fall_through != NullBasicBlockId) {
1709 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1710 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001711 }
1712 }
1713}
1714
1715/*
1716 * Build an array of location records for the incoming arguments.
1717 * Note: one location record per word of arguments, with dummy
1718 * high-word loc for wide arguments. Also pull up any following
1719 * MOVE_RESULT and incorporate it into the invoke.
1720 */
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001721CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type, bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001722 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001723 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001724 MIR* move_result_mir = FindMoveResult(bb, mir);
1725 if (move_result_mir == NULL) {
1726 info->result.location = kLocInvalid;
1727 } else {
1728 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001729 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1730 }
1731 info->num_arg_words = mir->ssa_rep->num_uses;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001732 info->args = (info->num_arg_words == 0) ? nullptr :
1733 arena_->AllocArray<RegLocation>(info->num_arg_words, kArenaAllocMisc);
Vladimir Marko6ce3eba2015-02-16 13:05:59 +00001734 for (size_t i = 0; i < info->num_arg_words; i++) {
buzbee1fd33462013-03-25 13:40:45 -07001735 info->args[i] = GetRawSrc(mir, i);
1736 }
1737 info->opt_flags = mir->optimization_flags;
1738 info->type = type;
1739 info->is_range = is_range;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001740 if (IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) {
1741 const auto& method_info = GetMethodLoweringInfo(mir);
1742 info->method_ref = method_info.GetTargetMethod();
1743 } else {
1744 info->method_ref = MethodReference(GetCurrentDexCompilationUnit()->GetDexFile(),
1745 mir->dalvikInsn.vB);
1746 }
buzbee1fd33462013-03-25 13:40:45 -07001747 info->index = mir->dalvikInsn.vB;
1748 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001749 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001750 return info;
1751}
1752
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001753// Allocate a new MIR.
1754MIR* MIRGraph::NewMIR() {
1755 MIR* mir = new (arena_) MIR();
1756 return mir;
1757}
1758
buzbee862a7602013-04-05 10:58:54 -07001759// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001760BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001761 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001762
buzbee862a7602013-04-05 10:58:54 -07001763 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001764 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001765 block_id_map_.Put(block_id, block_id);
1766 return bb;
1767}
buzbee1fd33462013-03-25 13:40:45 -07001768
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001769void MIRGraph::InitializeConstantPropagation() {
1770 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001771 constant_values_ = arena_->AllocArray<int>(GetNumSSARegs(), kArenaAllocDFInfo);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001772}
1773
1774void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001775 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001776 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001777 use_counts_.clear();
1778 use_counts_.reserve(num_ssa_regs + 32);
1779 use_counts_.resize(num_ssa_regs, 0u);
1780 raw_use_counts_.clear();
1781 raw_use_counts_.reserve(num_ssa_regs + 32);
1782 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001783}
1784
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001785void MIRGraph::SSATransformationStart() {
1786 DCHECK(temp_scoped_alloc_.get() == nullptr);
1787 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001788 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1789 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1790 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001791}
1792
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001793void MIRGraph::SSATransformationEnd() {
1794 // Verify the dataflow information after the pass.
1795 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1796 VerifyDataflow();
1797 }
1798
Vladimir Markof585e542014-11-21 13:41:32 +00001799 temp_.ssa.num_vregs = 0u;
1800 temp_.ssa.work_live_vregs = nullptr;
Vladimir Marko6a8946b2015-02-09 12:35:05 +00001801 DCHECK(temp_.ssa.def_block_matrix == nullptr);
1802 temp_.ssa.phi_node_blocks = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001803 DCHECK(temp_scoped_alloc_.get() != nullptr);
1804 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001805
1806 // Update the maximum number of reachable blocks.
1807 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001808
1809 // Mark MIR SSA representations as up to date.
1810 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001811}
1812
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001813size_t MIRGraph::GetNumDalvikInsns() const {
1814 size_t cumulative_size = 0u;
1815 bool counted_current_item = false;
1816 const uint8_t size_for_null_code_item = 2u;
1817
1818 for (auto it : m_units_) {
1819 const DexFile::CodeItem* code_item = it->GetCodeItem();
1820 // Even if the code item is null, we still count non-zero value so that
1821 // each m_unit is counted as having impact.
1822 cumulative_size += (code_item == nullptr ?
1823 size_for_null_code_item : code_item->insns_size_in_code_units_);
1824 if (code_item == current_code_item_) {
1825 counted_current_item = true;
1826 }
1827 }
1828
1829 // If the current code item was not counted yet, count it now.
1830 // This can happen for example in unit tests where some fields like m_units_
1831 // are not initialized.
1832 if (counted_current_item == false) {
1833 cumulative_size += (current_code_item_ == nullptr ?
1834 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1835 }
1836
1837 return cumulative_size;
1838}
1839
Vladimir Marko55fff042014-07-10 12:42:52 +01001840static BasicBlock* SelectTopologicalSortOrderFallBack(
1841 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1842 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1843 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1844 // No true loop head has been found but there may be true loop heads after the mess we need
1845 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1846 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1847 BasicBlock* fall_back = nullptr;
1848 size_t fall_back_num_reachable = 0u;
1849 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1850 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1851 AllNodesIterator iter(mir_graph);
1852 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1853 if (candidate->hidden || // Hidden, or
1854 candidate->visited || // already processed, or
1855 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1856 (current_loop != nullptr && // outside current loop.
1857 !current_loop->IsBitSet(candidate->id))) {
1858 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001859 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001860 DCHECK(tmp_stack->empty());
1861 tmp_stack->push_back(candidate->id);
1862 candidate_reachable.ClearAllBits();
1863 size_t num_reachable = 0u;
1864 while (!tmp_stack->empty()) {
1865 BasicBlockId current_id = tmp_stack->back();
1866 tmp_stack->pop_back();
1867 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1868 DCHECK(current_bb != nullptr);
1869 ChildBlockIterator child_iter(current_bb, mir_graph);
1870 BasicBlock* child_bb = child_iter.Next();
1871 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1872 DCHECK(!child_bb->hidden);
1873 if (child_bb->visited || // Already processed, or
1874 (current_loop != nullptr && // outside current loop.
1875 !current_loop->IsBitSet(child_bb->id))) {
1876 continue;
1877 }
1878 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1879 candidate_reachable.SetBit(child_bb->id);
1880 tmp_stack->push_back(child_bb->id);
1881 num_reachable += 1u;
1882 }
1883 }
1884 }
1885 if (fall_back_num_reachable < num_reachable) {
1886 fall_back_num_reachable = num_reachable;
1887 fall_back = candidate;
1888 }
1889 }
1890 return fall_back;
1891}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001892
Vladimir Marko55fff042014-07-10 12:42:52 +01001893// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1894static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1895 ArenaBitVector* reachable,
1896 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1897 // NOTE: Loop heads indicated by the "visited" flag.
1898 DCHECK(tmp_stack->empty());
1899 reachable->ClearAllBits();
1900 tmp_stack->push_back(bb_id);
1901 while (!tmp_stack->empty()) {
1902 BasicBlockId current_id = tmp_stack->back();
1903 tmp_stack->pop_back();
1904 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1905 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001906 for (BasicBlockId pred_id : current_bb->predecessors) {
1907 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1908 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001909 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1910 reachable->SetBit(pred_bb->id);
1911 tmp_stack->push_back(pred_bb->id);
1912 }
1913 }
1914 }
1915}
1916
1917void MIRGraph::ComputeTopologicalSortOrder() {
1918 ScopedArenaAllocator allocator(&cu_->arena_stack);
1919 unsigned int num_blocks = GetNumBlocks();
1920
1921 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1922 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1923 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1924 size_t max_nested_loops = 0u;
1925 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1926 loop_exit_blocks.ClearAllBits();
1927
1928 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001929 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001930 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001931 if (bb->hidden == true) {
1932 continue;
1933 }
1934
Vladimir Marko55fff042014-07-10 12:42:52 +01001935 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001936
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001937 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001938 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001939 q.push(bb);
1940 }
1941 }
1942
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001943 // Clear the topological order arrays.
1944 topological_order_.clear();
1945 topological_order_.reserve(num_blocks);
1946 topological_order_loop_ends_.clear();
1947 topological_order_loop_ends_.resize(num_blocks, 0u);
1948 topological_order_indexes_.clear();
1949 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001950
1951 // Mark all blocks as unvisited.
1952 ClearAllVisitedFlags();
1953
1954 // For loop heads, keep track from which blocks they are reachable not going through other
1955 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1956 // in this set go into the loop body, the other children are jumping over the loop.
1957 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1958 loop_head_reachable_from.resize(num_blocks, nullptr);
1959 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1960 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1961
1962 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001963 BasicBlock* bb = nullptr;
1964 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001965 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001966 // Get top.
1967 bb = q.front();
1968 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001969 if (bb->visited) {
1970 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1971 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001972 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1973 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001974 DCHECK_EQ(loop_head_stack.back(), bb->id);
1975 loop_head_stack.pop_back();
1976 ArenaBitVector* reachable =
1977 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1978 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1979 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1980 q.push(GetBasicBlock(candidate_id));
1981 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1982 // so clearing the bit has no effect on the iterator.
1983 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001984 }
1985 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001986 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001987 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001988 } else {
1989 // Find the new loop head.
1990 AllNodesIterator iter(this);
1991 while (true) {
1992 BasicBlock* candidate = iter.Next();
1993 if (candidate == nullptr) {
1994 // We did not find a true loop head, fall back to a reachable block in any loop.
1995 ArenaBitVector* current_loop =
1996 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1997 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1998 &allocator, &tmp_stack);
1999 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
2000 if (kIsDebugBuild && cu_->dex_file != nullptr) {
2001 LOG(INFO) << "Topological sort order: Using fall-back in "
2002 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
2003 << " @0x" << std::hex << bb->start_offset
2004 << ", num_blocks = " << std::dec << num_blocks;
2005 }
2006 break;
2007 }
2008 if (candidate->hidden || // Hidden, or
2009 candidate->visited || // already processed, or
2010 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
2011 (!loop_head_stack.empty() && // outside current loop.
2012 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
2013 continue;
2014 }
2015
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002016 for (BasicBlockId pred_id : candidate->predecessors) {
2017 BasicBlock* pred_bb = GetBasicBlock(pred_id);
2018 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01002019 if (pred_bb != candidate && !pred_bb->visited &&
2020 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002021 candidate = nullptr; // Set candidate to null to indicate failure.
2022 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01002023 }
2024 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002025 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002026 bb = candidate;
2027 break;
2028 }
2029 }
2030 // Compute blocks from which the loop head is reachable and process those blocks first.
2031 ArenaBitVector* reachable =
2032 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
2033 loop_head_reachable_from[bb->id] = reachable;
2034 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
2035 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
2036 loop_head_stack.push_back(bb->id);
2037 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002038 }
2039
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002040 DCHECK_EQ(bb->hidden, false);
2041 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002042 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00002043 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002044
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002045 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002046 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
2047 topological_order_indexes_[bb->id] = idx;
2048 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002049
Vladimir Marko55fff042014-07-10 12:42:52 +01002050 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002051 ChildBlockIterator succIter(bb, this);
2052 BasicBlock* successor = succIter.Next();
2053 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002054 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002055 continue;
2056 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002057
Vladimir Marko55fff042014-07-10 12:42:52 +01002058 // One more predecessor was visited.
2059 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002060 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002061 if (loop_head_stack.empty() ||
2062 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
2063 q.push(successor);
2064 } else {
2065 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2066 loop_exit_blocks.SetBit(successor->id);
2067 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002068 }
2069 }
2070 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002071
2072 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002073 topological_order_loop_head_stack_.clear();
2074 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002075 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002076 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002077}
2078
2079bool BasicBlock::IsExceptionBlock() const {
2080 if (block_type == kExceptionHandling) {
2081 return true;
2082 }
2083 return false;
2084}
2085
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002086ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2087 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2088 visited_taken_(false), have_successors_(false) {
2089 // Check if we actually do have successors.
2090 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2091 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002092 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002093 }
2094}
2095
2096BasicBlock* ChildBlockIterator::Next() {
2097 // We check if we have a basic block. If we don't we cannot get next child.
2098 if (basic_block_ == nullptr) {
2099 return nullptr;
2100 }
2101
2102 // If we haven't visited fallthrough, return that.
2103 if (visited_fallthrough_ == false) {
2104 visited_fallthrough_ = true;
2105
2106 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2107 if (result != nullptr) {
2108 return result;
2109 }
2110 }
2111
2112 // If we haven't visited taken, return that.
2113 if (visited_taken_ == false) {
2114 visited_taken_ = true;
2115
2116 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2117 if (result != nullptr) {
2118 return result;
2119 }
2120 }
2121
2122 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2123 if (have_successors_ == true) {
2124 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002125 auto end = basic_block_->successor_blocks.cend();
2126 while (successor_iter_ != end) {
2127 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2128 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002129 // If block was replaced by zero block, take next one.
2130 if (successor_block_info->block != NullBasicBlockId) {
2131 return mir_graph_->GetBasicBlock(successor_block_info->block);
2132 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002133 }
2134 }
2135
2136 // We do not have anything.
2137 return nullptr;
2138}
2139
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002140BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2141 MIRGraph* mir_graph = c_unit->mir_graph.get();
2142 return Copy(mir_graph);
2143}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002144
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002145BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2146 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002147
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002148 // We don't do a memcpy style copy here because it would lead to a lot of things
2149 // to clean up. Let us do it by hand instead.
2150 // Copy in taken and fallthrough.
2151 result_bb->fall_through = fall_through;
2152 result_bb->taken = taken;
2153
2154 // Copy successor links if needed.
2155 ArenaAllocator* arena = mir_graph->GetArena();
2156
2157 result_bb->successor_block_list_type = successor_block_list_type;
2158 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002159 result_bb->successor_blocks.reserve(successor_blocks.size());
2160 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2161 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2162 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002163 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002164 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002165 }
2166 }
2167
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002168 // Copy offset, method.
2169 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002170
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002171 // Now copy instructions.
2172 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2173 // Get a copy first.
2174 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002175
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002176 // Append it.
2177 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002178 }
2179
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002180 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002181}
2182
2183MIR* MIR::Copy(MIRGraph* mir_graph) {
2184 MIR* res = mir_graph->NewMIR();
2185 *res = *this;
2186
2187 // Remove links
2188 res->next = nullptr;
2189 res->bb = NullBasicBlockId;
2190 res->ssa_rep = nullptr;
2191
2192 return res;
2193}
2194
2195MIR* MIR::Copy(CompilationUnit* c_unit) {
2196 return Copy(c_unit->mir_graph.get());
2197}
2198
2199uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2200 // Default result.
2201 int res = 0;
2202
2203 // We are basically setting the iputs to their igets counterparts.
2204 switch (opcode) {
2205 case Instruction::IPUT:
2206 case Instruction::IPUT_OBJECT:
2207 case Instruction::IPUT_BOOLEAN:
2208 case Instruction::IPUT_BYTE:
2209 case Instruction::IPUT_CHAR:
2210 case Instruction::IPUT_SHORT:
2211 case Instruction::IPUT_QUICK:
2212 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002213 case Instruction::IPUT_BOOLEAN_QUICK:
2214 case Instruction::IPUT_BYTE_QUICK:
2215 case Instruction::IPUT_CHAR_QUICK:
2216 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002217 case Instruction::APUT:
2218 case Instruction::APUT_OBJECT:
2219 case Instruction::APUT_BOOLEAN:
2220 case Instruction::APUT_BYTE:
2221 case Instruction::APUT_CHAR:
2222 case Instruction::APUT_SHORT:
2223 case Instruction::SPUT:
2224 case Instruction::SPUT_OBJECT:
2225 case Instruction::SPUT_BOOLEAN:
2226 case Instruction::SPUT_BYTE:
2227 case Instruction::SPUT_CHAR:
2228 case Instruction::SPUT_SHORT:
2229 // Skip the VR containing what to store.
2230 res = 1;
2231 break;
2232 case Instruction::IPUT_WIDE:
2233 case Instruction::IPUT_WIDE_QUICK:
2234 case Instruction::APUT_WIDE:
2235 case Instruction::SPUT_WIDE:
2236 // Skip the two VRs containing what to store.
2237 res = 2;
2238 break;
2239 default:
2240 // Do nothing in the general case.
2241 break;
2242 }
2243
2244 return res;
2245}
2246
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002247/**
2248 * @brief Given a decoded instruction, it checks whether the instruction
2249 * sets a constant and if it does, more information is provided about the
2250 * constant being set.
2251 * @param ptr_value pointer to a 64-bit holder for the constant.
2252 * @param wide Updated by function whether a wide constant is being set by bytecode.
2253 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2254 */
2255bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2256 bool sets_const = true;
2257 int64_t value = vB;
2258
2259 DCHECK(ptr_value != nullptr);
2260 DCHECK(wide != nullptr);
2261
2262 switch (opcode) {
2263 case Instruction::CONST_4:
2264 case Instruction::CONST_16:
2265 case Instruction::CONST:
2266 *wide = false;
2267 value <<= 32; // In order to get the sign extend.
2268 value >>= 32;
2269 break;
2270 case Instruction::CONST_HIGH16:
2271 *wide = false;
2272 value <<= 48; // In order to get the sign extend.
2273 value >>= 32;
2274 break;
2275 case Instruction::CONST_WIDE_16:
2276 case Instruction::CONST_WIDE_32:
2277 *wide = true;
2278 value <<= 32; // In order to get the sign extend.
2279 value >>= 32;
2280 break;
2281 case Instruction::CONST_WIDE:
2282 *wide = true;
2283 value = vB_wide;
2284 break;
2285 case Instruction::CONST_WIDE_HIGH16:
2286 *wide = true;
2287 value <<= 48; // In order to get the sign extend.
2288 break;
2289 default:
2290 sets_const = false;
2291 break;
2292 }
2293
2294 if (sets_const) {
2295 *ptr_value = value;
2296 }
2297
2298 return sets_const;
2299}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002300
2301void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2302 // Reset flags for all MIRs in bb.
2303 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2304 mir->optimization_flags &= (~reset_flags);
2305 }
2306}
2307
Vladimir Markocb873d82014-12-08 15:16:54 +00002308void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002309 for (BasicBlockId pred_id : predecessors) {
2310 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2311 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002312
2313 // Sadly we have to go through the children by hand here.
2314 pred_bb->ReplaceChild(id, NullBasicBlockId);
2315 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002316 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002317
Vladimir Marko312eb252014-10-07 15:01:57 +01002318 // Mark as dead and hidden.
2319 block_type = kDead;
2320 hidden = true;
2321
2322 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2323 // are updated to know that they no longer have a parent.
2324 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2325 mir->bb = NullBasicBlockId;
2326 }
2327 first_mir_insn = nullptr;
2328 last_mir_insn = nullptr;
2329
2330 data_flow_info = nullptr;
2331
2332 // Erase this bb from all children's predecessors and kill unreachable children.
2333 ChildBlockIterator iter(this, mir_graph);
2334 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2335 succ_bb->ErasePredecessor(id);
Vladimir Marko312eb252014-10-07 15:01:57 +01002336 }
2337
2338 // Remove links to children.
2339 fall_through = NullBasicBlockId;
2340 taken = NullBasicBlockId;
2341 successor_block_list_type = kNotUsed;
2342
2343 if (kIsDebugBuild) {
2344 if (catch_entry) {
2345 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2346 mir_graph->catches_.erase(start_offset);
2347 }
2348 }
2349}
2350
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002351bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2352 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2353 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2354 // then it is not live out of this BB.
2355 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2356
2357 int last_ssa_reg = -1;
2358
2359 // Walk through the MIRs backwards.
2360 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2361 // Get ssa rep.
2362 SSARepresentation *ssa_rep = mir->ssa_rep;
2363
2364 // Go through the defines for this MIR.
2365 for (int i = 0; i < ssa_rep->num_defs; i++) {
2366 DCHECK(ssa_rep->defs != nullptr);
2367
2368 // Get the ssa reg.
2369 int def_ssa_reg = ssa_rep->defs[i];
2370
2371 // Get dalvik reg.
2372 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2373
2374 // Compare dalvik regs.
2375 if (dalvik_reg == def_dalvik_reg) {
2376 // We found a def of the register that we are being asked about.
2377 // Remember it.
2378 last_ssa_reg = def_ssa_reg;
2379 }
2380 }
2381 }
2382
2383 if (last_ssa_reg == -1) {
2384 // If we get to this point we couldn't find a define of register user asked about.
2385 // Let's assume the user knows what he's doing so we can be safe and say that if we
2386 // couldn't find a def, it is live out.
2387 return true;
2388 }
2389
2390 // If it is not -1, we found a match, is it ssa_reg?
2391 return (ssa_reg == last_ssa_reg);
2392}
2393
2394bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2395 // We need to check taken, fall_through, and successor_blocks to replace.
2396 bool found = false;
2397 if (taken == old_bb) {
2398 taken = new_bb;
2399 found = true;
2400 }
2401
2402 if (fall_through == old_bb) {
2403 fall_through = new_bb;
2404 found = true;
2405 }
2406
2407 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002408 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002409 if (successor_block_info->block == old_bb) {
2410 successor_block_info->block = new_bb;
2411 found = true;
2412 }
2413 }
2414 }
2415
2416 return found;
2417}
2418
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002419void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2420 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2421 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002422 // It's faster to move the back() to *pos than erase(pos).
2423 *pos = predecessors.back();
2424 predecessors.pop_back();
2425 size_t idx = std::distance(predecessors.begin(), pos);
2426 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2427 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2428 break;
2429 }
2430 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2431 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2432 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2433 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2434 mir->ssa_rep->num_uses = predecessors.size();
2435 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002436}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002437
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002438void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2439 DCHECK_NE(new_pred, NullBasicBlockId);
2440 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002441 DCHECK(pos != predecessors.end());
2442 *pos = new_pred;
2443 size_t idx = std::distance(predecessors.begin(), pos);
2444 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2445 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2446 break;
2447 }
2448 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2449 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002450 }
2451}
2452
2453// Create a new basic block with block_id as num_blocks_ that is
2454// post-incremented.
2455BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002456 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2457 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002458 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002459 return res;
2460}
2461
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00002462void MIRGraph::CalculateBasicBlockInformation(const PassManager* const post_opt_pass_manager) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -08002463 /* Create the pass driver and launch it */
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00002464 PassDriverMEPostOpt driver(post_opt_pass_manager, cu_);
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002465 driver.Launch();
2466}
2467
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002468int MIR::DecodedInstruction::FlagsOf() const {
2469 // Calculate new index.
2470 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2471
2472 // Check if it is an extended or not.
2473 if (idx < 0) {
2474 return Instruction::FlagsOf(opcode);
2475 }
2476
2477 // For extended, we use a switch.
2478 switch (static_cast<int>(opcode)) {
2479 case kMirOpPhi:
2480 return Instruction::kContinue;
2481 case kMirOpCopy:
2482 return Instruction::kContinue;
2483 case kMirOpFusedCmplFloat:
2484 return Instruction::kContinue | Instruction::kBranch;
2485 case kMirOpFusedCmpgFloat:
2486 return Instruction::kContinue | Instruction::kBranch;
2487 case kMirOpFusedCmplDouble:
2488 return Instruction::kContinue | Instruction::kBranch;
2489 case kMirOpFusedCmpgDouble:
2490 return Instruction::kContinue | Instruction::kBranch;
2491 case kMirOpFusedCmpLong:
2492 return Instruction::kContinue | Instruction::kBranch;
2493 case kMirOpNop:
2494 return Instruction::kContinue;
2495 case kMirOpNullCheck:
2496 return Instruction::kContinue | Instruction::kThrow;
2497 case kMirOpRangeCheck:
2498 return Instruction::kContinue | Instruction::kThrow;
2499 case kMirOpDivZeroCheck:
2500 return Instruction::kContinue | Instruction::kThrow;
2501 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002502 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002503 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002504 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002505 case kMirOpSelect:
2506 return Instruction::kContinue;
2507 case kMirOpConstVector:
2508 return Instruction::kContinue;
2509 case kMirOpMoveVector:
2510 return Instruction::kContinue;
2511 case kMirOpPackedMultiply:
2512 return Instruction::kContinue;
2513 case kMirOpPackedAddition:
2514 return Instruction::kContinue;
2515 case kMirOpPackedSubtract:
2516 return Instruction::kContinue;
2517 case kMirOpPackedShiftLeft:
2518 return Instruction::kContinue;
2519 case kMirOpPackedSignedShiftRight:
2520 return Instruction::kContinue;
2521 case kMirOpPackedUnsignedShiftRight:
2522 return Instruction::kContinue;
2523 case kMirOpPackedAnd:
2524 return Instruction::kContinue;
2525 case kMirOpPackedOr:
2526 return Instruction::kContinue;
2527 case kMirOpPackedXor:
2528 return Instruction::kContinue;
2529 case kMirOpPackedAddReduce:
2530 return Instruction::kContinue;
2531 case kMirOpPackedReduce:
2532 return Instruction::kContinue;
2533 case kMirOpPackedSet:
2534 return Instruction::kContinue;
2535 case kMirOpReserveVectorRegisters:
2536 return Instruction::kContinue;
2537 case kMirOpReturnVectorRegisters:
2538 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002539 case kMirOpMemBarrier:
2540 return Instruction::kContinue;
2541 case kMirOpPackedArrayGet:
2542 return Instruction::kContinue | Instruction::kThrow;
2543 case kMirOpPackedArrayPut:
2544 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002545 case kMirOpMaddInt:
2546 case kMirOpMsubInt:
2547 case kMirOpMaddLong:
2548 case kMirOpMsubLong:
2549 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002550 default:
2551 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2552 return 0;
2553 }
2554}
Andreas Gampe0b9203e2015-01-22 20:39:27 -08002555
2556const uint16_t* MIRGraph::GetInsns(int m_unit_index) const {
2557 return m_units_[m_unit_index]->GetCodeItem()->insns_;
2558}
2559
Vladimir Marko7a01dc22015-01-02 17:00:44 +00002560void MIRGraph::SetPuntToInterpreter(bool val) {
2561 punt_to_interpreter_ = val;
2562 if (val) {
2563 // Disable all subsequent optimizations. They may not be safe to run. (For example,
2564 // LVN/GVN assumes there are no conflicts found by the type inference pass.)
2565 cu_->disable_opt = ~static_cast<decltype(cu_->disable_opt)>(0);
2566 }
2567}
2568
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002569} // namespace art