blob: db4141c348b86797ab6f4ad99267121c757b7db9 [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"
27#include "compiler_ir.h"
buzbee311ca162013-02-28 15:56:43 -080028#include "dex_file-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080029#include "dex_flags.h"
Ian Rogers29a26482014-05-02 15:27:29 -070030#include "dex_instruction-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080031#include "driver/compiler_driver.h"
32#include "driver/dex_compilation_unit.h"
Nicolas Geoffrayf3e2cc42014-02-18 18:37:26 +000033#include "leb128.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070034#include "pass_driver_me_post_opt.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070035#include "stack.h"
Vladimir Marko622bdbe2014-06-19 14:59:05 +010036#include "utils/scoped_arena_containers.h"
Vladimir Marko5816ed42013-11-27 17:04:20 +000037
buzbee311ca162013-02-28 15:56:43 -080038namespace art {
39
40#define MAX_PATTERN_LEN 5
41
buzbee1fd33462013-03-25 13:40:45 -070042const char* MIRGraph::extended_mir_op_names_[kMirOpLast - kMirOpFirst] = {
43 "Phi",
44 "Copy",
45 "FusedCmplFloat",
46 "FusedCmpgFloat",
47 "FusedCmplDouble",
48 "FusedCmpgDouble",
49 "FusedCmpLong",
50 "Nop",
51 "OpNullCheck",
52 "OpRangeCheck",
53 "OpDivZeroCheck",
54 "Check1",
55 "Check2",
56 "Select",
Mark Mendelld65c51a2014-04-29 16:55:20 -040057 "ConstVector",
58 "MoveVector",
59 "PackedMultiply",
60 "PackedAddition",
61 "PackedSubtract",
62 "PackedShiftLeft",
63 "PackedSignedShiftRight",
64 "PackedUnsignedShiftRight",
65 "PackedAnd",
66 "PackedOr",
67 "PackedXor",
68 "PackedAddReduce",
69 "PackedReduce",
70 "PackedSet",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -070071 "ReserveVectorRegisters",
72 "ReturnVectorRegisters",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -070073 "MemBarrier",
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -070074 "PackedArrayGet",
75 "PackedArrayPut",
Ningsheng Jiana262f772014-11-25 16:48:07 +080076 "MaddInt",
77 "MsubInt",
78 "MaddLong",
79 "MsubLong",
buzbee1fd33462013-03-25 13:40:45 -070080};
81
buzbee862a7602013-04-05 10:58:54 -070082MIRGraph::MIRGraph(CompilationUnit* cu, ArenaAllocator* arena)
buzbee1fd33462013-03-25 13:40:45 -070083 : reg_location_(NULL),
Vladimir Marko8081d2b2014-07-31 15:33:43 +010084 block_id_map_(std::less<unsigned int>(), arena->Adapter()),
buzbee1fd33462013-03-25 13:40:45 -070085 cu_(cu),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010086 ssa_base_vregs_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
87 ssa_subscripts_(arena->Adapter(kArenaAllocSSAToDalvikMap)),
Vladimir Marko1c6ea442014-12-19 18:11:35 +000088 vreg_to_ssa_map_(NULL),
89 ssa_last_defs_(NULL),
buzbee311ca162013-02-28 15:56:43 -080090 is_constant_v_(NULL),
91 constant_values_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +010092 use_counts_(arena->Adapter()),
93 raw_use_counts_(arena->Adapter()),
buzbee311ca162013-02-28 15:56:43 -080094 num_reachable_blocks_(0),
Jean Christophe Beyler4896d7b2014-05-01 15:36:22 -070095 max_num_reachable_blocks_(0),
Vladimir Marko312eb252014-10-07 15:01:57 +010096 dfs_orders_up_to_date_(false),
Vladimir Markoffda4992014-12-18 17:05:58 +000097 domination_up_to_date_(false),
98 mir_ssa_rep_up_to_date_(false),
99 topological_order_up_to_date_(false),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100100 dfs_order_(arena->Adapter(kArenaAllocDfsPreOrder)),
101 dfs_post_order_(arena->Adapter(kArenaAllocDfsPostOrder)),
102 dom_post_order_traversal_(arena->Adapter(kArenaAllocDomPostOrder)),
103 topological_order_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
104 topological_order_loop_ends_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
105 topological_order_indexes_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
106 topological_order_loop_head_stack_(arena->Adapter(kArenaAllocTopologicalSortOrder)),
Vladimir Marko415ac882014-09-30 18:09:14 +0100107 max_nested_loops_(0u),
buzbee311ca162013-02-28 15:56:43 -0800108 i_dom_list_(NULL),
Vladimir Markobfea9c22014-01-17 17:49:33 +0000109 temp_scoped_alloc_(),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100110 block_list_(arena->Adapter(kArenaAllocBBList)),
buzbee311ca162013-02-28 15:56:43 -0800111 try_block_addr_(NULL),
112 entry_block_(NULL),
113 exit_block_(NULL),
buzbee311ca162013-02-28 15:56:43 -0800114 current_code_item_(NULL),
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100115 dex_pc_to_block_map_(arena->Adapter()),
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);
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100270 DCHECK_EQ(dex_pc_to_block_map_[insn->offset], orig_block->id);
Mathew Zaleski33c17022014-09-15 09:44:14 -0400271 // Scan the "bottom" instructions, remapping them to the
272 // newly created "bottom" block.
Vladimir Marko4376c872014-01-23 12:39:29 +0000273 MIR* p = insn;
Mathew Zaleski33c17022014-09-15 09:44:14 -0400274 p->bb = bottom_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100275 dex_pc_to_block_map_[p->offset] = bottom_block->id;
Vladimir Marko4376c872014-01-23 12:39:29 +0000276 while (p != bottom_block->last_mir_insn) {
277 p = p->next;
278 DCHECK(p != nullptr);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700279 p->bb = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700280 int opcode = p->dalvikInsn.opcode;
281 /*
282 * Some messiness here to ensure that we only enter real opcodes and only the
283 * first half of a potentially throwing instruction that has been split into
Vladimir Marko4376c872014-01-23 12:39:29 +0000284 * CHECK and work portions. Since the 2nd half of a split operation is always
285 * the first in a BasicBlock, we can't hit it here.
buzbeeb48819d2013-09-14 16:15:25 -0700286 */
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700287 if ((opcode == kMirOpCheck) || !MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Mathew Zaleski33c17022014-09-15 09:44:14 -0400288 BasicBlockId mapped_id = dex_pc_to_block_map_[p->offset];
289 // At first glance the instructions should all be mapped to orig_block.
290 // However, multiple instructions may correspond to the same dex, hence an earlier
291 // instruction may have already moved the mapping for dex to bottom_block.
292 DCHECK((mapped_id == orig_block->id) || (mapped_id == bottom_block->id));
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100293 dex_pc_to_block_map_[p->offset] = bottom_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700294 }
buzbeeb48819d2013-09-14 16:15:25 -0700295 }
296
buzbee311ca162013-02-28 15:56:43 -0800297 return bottom_block;
298}
299
300/*
301 * Given a code offset, find out the block that starts with it. If the offset
302 * is in the middle of an existing block, split it into two. If immed_pred_block_p
303 * is not non-null and is the block being split, update *immed_pred_block_p to
304 * point to the bottom block so that outgoing edges can be set up properly
305 * (by the caller)
306 * Utilizes a map for fast lookup of the typical cases.
307 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700308BasicBlock* MIRGraph::FindBlock(DexOffset code_offset, bool create,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700309 BasicBlock** immed_pred_block_p) {
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700310 if (code_offset >= current_code_item_->insns_size_in_code_units_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700311 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800312 }
buzbeeb48819d2013-09-14 16:15:25 -0700313
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100314 int block_id = dex_pc_to_block_map_[code_offset];
315 BasicBlock* bb = GetBasicBlock(block_id);
buzbeeb48819d2013-09-14 16:15:25 -0700316
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700317 if ((bb != nullptr) && (bb->start_offset == code_offset)) {
buzbeeb48819d2013-09-14 16:15:25 -0700318 // Does this containing block start with the desired instruction?
buzbeebd663de2013-09-10 15:41:31 -0700319 return bb;
320 }
buzbee311ca162013-02-28 15:56:43 -0800321
buzbeeb48819d2013-09-14 16:15:25 -0700322 // No direct hit.
323 if (!create) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700324 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800325 }
326
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700327 if (bb != nullptr) {
buzbeeb48819d2013-09-14 16:15:25 -0700328 // The target exists somewhere in an existing block.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700329 return SplitBlock(code_offset, bb, bb == *immed_pred_block_p ? immed_pred_block_p : nullptr);
buzbeeb48819d2013-09-14 16:15:25 -0700330 }
331
332 // Create a new block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100333 bb = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800334 bb->start_offset = code_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100335 dex_pc_to_block_map_[bb->start_offset] = bb->id;
buzbee311ca162013-02-28 15:56:43 -0800336 return bb;
337}
338
buzbeeb48819d2013-09-14 16:15:25 -0700339
buzbee311ca162013-02-28 15:56:43 -0800340/* Identify code range in try blocks and set up the empty catch blocks */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700341void MIRGraph::ProcessTryCatchBlocks() {
buzbee311ca162013-02-28 15:56:43 -0800342 int tries_size = current_code_item_->tries_size_;
buzbee0d829482013-10-11 15:24:55 -0700343 DexOffset offset;
buzbee311ca162013-02-28 15:56:43 -0800344
345 if (tries_size == 0) {
346 return;
347 }
348
349 for (int i = 0; i < tries_size; i++) {
350 const DexFile::TryItem* pTry =
351 DexFile::GetTryItems(*current_code_item_, i);
buzbee0d829482013-10-11 15:24:55 -0700352 DexOffset start_offset = pTry->start_addr_;
353 DexOffset end_offset = start_offset + pTry->insn_count_;
buzbee311ca162013-02-28 15:56:43 -0800354 for (offset = start_offset; offset < end_offset; offset++) {
buzbee862a7602013-04-05 10:58:54 -0700355 try_block_addr_->SetBit(offset);
buzbee311ca162013-02-28 15:56:43 -0800356 }
357 }
358
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700359 // Iterate over each of the handlers to enqueue the empty Catch blocks.
Ian Rogers13735952014-10-08 12:43:28 -0700360 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*current_code_item_, 0);
buzbee311ca162013-02-28 15:56:43 -0800361 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
362 for (uint32_t idx = 0; idx < handlers_size; idx++) {
363 CatchHandlerIterator iterator(handlers_ptr);
364 for (; iterator.HasNext(); iterator.Next()) {
365 uint32_t address = iterator.GetHandlerAddress();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700366 FindBlock(address, true /*create*/, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800367 }
368 handlers_ptr = iterator.EndDataPointer();
369 }
370}
371
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100372bool MIRGraph::IsBadMonitorExitCatch(NarrowDexOffset monitor_exit_offset,
373 NarrowDexOffset catch_offset) {
374 // Catches for monitor-exit during stack unwinding have the pattern
375 // move-exception (move)* (goto)? monitor-exit throw
376 // In the currently generated dex bytecode we see these catching a bytecode range including
377 // either its own or an identical monitor-exit, http://b/15745363 . This function checks if
378 // it's the case for a given monitor-exit and catch block so that we can ignore it.
379 // (We don't want to ignore all monitor-exit catches since one could enclose a synchronized
380 // block in a try-block and catch the NPE, Error or Throwable and we should let it through;
381 // even though a throwing monitor-exit certainly indicates a bytecode error.)
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700382 const Instruction* monitor_exit = Instruction::At(current_code_item_->insns_ + monitor_exit_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100383 DCHECK(monitor_exit->Opcode() == Instruction::MONITOR_EXIT);
384 int monitor_reg = monitor_exit->VRegA_11x();
Razvan A Lupusoru09ae0222014-07-07 16:29:37 -0700385 const Instruction* check_insn = Instruction::At(current_code_item_->insns_ + catch_offset);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100386 DCHECK(check_insn->Opcode() == Instruction::MOVE_EXCEPTION);
387 if (check_insn->VRegA_11x() == monitor_reg) {
388 // Unexpected move-exception to the same register. Probably not the pattern we're looking for.
389 return false;
390 }
391 check_insn = check_insn->Next();
392 while (true) {
393 int dest = -1;
394 bool wide = false;
395 switch (check_insn->Opcode()) {
396 case Instruction::MOVE_WIDE:
397 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700398 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100399 case Instruction::MOVE_OBJECT:
400 case Instruction::MOVE:
401 dest = check_insn->VRegA_12x();
402 break;
403
404 case Instruction::MOVE_WIDE_FROM16:
405 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700406 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100407 case Instruction::MOVE_OBJECT_FROM16:
408 case Instruction::MOVE_FROM16:
409 dest = check_insn->VRegA_22x();
410 break;
411
412 case Instruction::MOVE_WIDE_16:
413 wide = true;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700414 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100415 case Instruction::MOVE_OBJECT_16:
416 case Instruction::MOVE_16:
417 dest = check_insn->VRegA_32x();
418 break;
419
420 case Instruction::GOTO:
421 case Instruction::GOTO_16:
422 case Instruction::GOTO_32:
423 check_insn = check_insn->RelativeAt(check_insn->GetTargetOffset());
Ian Rogersfc787ec2014-10-09 21:56:44 -0700424 FALLTHROUGH_INTENDED;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100425 default:
426 return check_insn->Opcode() == Instruction::MONITOR_EXIT &&
427 check_insn->VRegA_11x() == monitor_reg;
428 }
429
430 if (dest == monitor_reg || (wide && dest + 1 == monitor_reg)) {
431 return false;
432 }
433
434 check_insn = check_insn->Next();
435 }
436}
437
buzbee311ca162013-02-28 15:56:43 -0800438/* Process instructions with the kBranch flag */
buzbee0d829482013-10-11 15:24:55 -0700439BasicBlock* MIRGraph::ProcessCanBranch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
440 int width, int flags, const uint16_t* code_ptr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700441 const uint16_t* code_end) {
buzbee0d829482013-10-11 15:24:55 -0700442 DexOffset target = cur_offset;
buzbee311ca162013-02-28 15:56:43 -0800443 switch (insn->dalvikInsn.opcode) {
444 case Instruction::GOTO:
445 case Instruction::GOTO_16:
446 case Instruction::GOTO_32:
447 target += insn->dalvikInsn.vA;
448 break;
449 case Instruction::IF_EQ:
450 case Instruction::IF_NE:
451 case Instruction::IF_LT:
452 case Instruction::IF_GE:
453 case Instruction::IF_GT:
454 case Instruction::IF_LE:
455 cur_block->conditional_branch = true;
456 target += insn->dalvikInsn.vC;
457 break;
458 case Instruction::IF_EQZ:
459 case Instruction::IF_NEZ:
460 case Instruction::IF_LTZ:
461 case Instruction::IF_GEZ:
462 case Instruction::IF_GTZ:
463 case Instruction::IF_LEZ:
464 cur_block->conditional_branch = true;
465 target += insn->dalvikInsn.vB;
466 break;
467 default:
468 LOG(FATAL) << "Unexpected opcode(" << insn->dalvikInsn.opcode << ") with kBranch set";
469 }
buzbeeb48819d2013-09-14 16:15:25 -0700470 CountBranch(target);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700471 BasicBlock* taken_block = FindBlock(target, /* create */ true,
buzbee311ca162013-02-28 15:56:43 -0800472 /* immed_pred_block_p */ &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700473 cur_block->taken = taken_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100474 taken_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800475
476 /* Always terminate the current block for conditional branches */
477 if (flags & Instruction::kContinue) {
Jean Christophe Beyler2469e602014-05-06 20:36:55 -0700478 BasicBlock* fallthrough_block = FindBlock(cur_offset + width,
buzbee311ca162013-02-28 15:56:43 -0800479 /* create */
480 true,
481 /* immed_pred_block_p */
482 &cur_block);
buzbee0d829482013-10-11 15:24:55 -0700483 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100484 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800485 } else if (code_ptr < code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700486 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800487 }
488 return cur_block;
489}
490
491/* Process instructions with the kSwitch flag */
buzbee17189ac2013-11-08 11:07:02 -0800492BasicBlock* MIRGraph::ProcessCanSwitch(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
493 int width, int flags) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700494 UNUSED(flags);
buzbee311ca162013-02-28 15:56:43 -0800495 const uint16_t* switch_data =
496 reinterpret_cast<const uint16_t*>(GetCurrentInsns() + cur_offset + insn->dalvikInsn.vB);
497 int size;
498 const int* keyTable;
499 const int* target_table;
500 int i;
501 int first_key;
502
503 /*
504 * Packed switch data format:
505 * ushort ident = 0x0100 magic value
506 * ushort size number of entries in the table
507 * int first_key first (and lowest) switch case value
508 * int targets[size] branch targets, relative to switch opcode
509 *
510 * Total size is (4+size*2) 16-bit code units.
511 */
512 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
513 DCHECK_EQ(static_cast<int>(switch_data[0]),
514 static_cast<int>(Instruction::kPackedSwitchSignature));
515 size = switch_data[1];
516 first_key = switch_data[2] | (switch_data[3] << 16);
517 target_table = reinterpret_cast<const int*>(&switch_data[4]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700518 keyTable = NULL; // Make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800519 /*
520 * Sparse switch data format:
521 * ushort ident = 0x0200 magic value
522 * ushort size number of entries in the table; > 0
523 * int keys[size] keys, sorted low-to-high; 32-bit aligned
524 * int targets[size] branch targets, relative to switch opcode
525 *
526 * Total size is (2+size*4) 16-bit code units.
527 */
528 } else {
529 DCHECK_EQ(static_cast<int>(switch_data[0]),
530 static_cast<int>(Instruction::kSparseSwitchSignature));
531 size = switch_data[1];
532 keyTable = reinterpret_cast<const int*>(&switch_data[2]);
533 target_table = reinterpret_cast<const int*>(&switch_data[2 + size*2]);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700534 first_key = 0; // To make the compiler happy.
buzbee311ca162013-02-28 15:56:43 -0800535 }
536
buzbee0d829482013-10-11 15:24:55 -0700537 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800538 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700539 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800540 }
buzbee0d829482013-10-11 15:24:55 -0700541 cur_block->successor_block_list_type =
542 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ? kPackedSwitch : kSparseSwitch;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100543 cur_block->successor_blocks.reserve(size);
buzbee311ca162013-02-28 15:56:43 -0800544
545 for (i = 0; i < size; i++) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700546 BasicBlock* case_block = FindBlock(cur_offset + target_table[i], /* create */ true,
547 /* immed_pred_block_p */ &cur_block);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700548 SuccessorBlockInfo* successor_block_info =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700549 static_cast<SuccessorBlockInfo*>(arena_->Alloc(sizeof(SuccessorBlockInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000550 kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700551 successor_block_info->block = case_block->id;
buzbee311ca162013-02-28 15:56:43 -0800552 successor_block_info->key =
553 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
554 first_key + i : keyTable[i];
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100555 cur_block->successor_blocks.push_back(successor_block_info);
556 case_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800557 }
558
559 /* Fall-through case */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700560 BasicBlock* fallthrough_block = FindBlock(cur_offset + width, /* create */ true,
561 /* immed_pred_block_p */ nullptr);
buzbee0d829482013-10-11 15:24:55 -0700562 cur_block->fall_through = fallthrough_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100563 fallthrough_block->predecessors.push_back(cur_block->id);
buzbee17189ac2013-11-08 11:07:02 -0800564 return cur_block;
buzbee311ca162013-02-28 15:56:43 -0800565}
566
567/* Process instructions with the kThrow flag */
buzbee0d829482013-10-11 15:24:55 -0700568BasicBlock* MIRGraph::ProcessCanThrow(BasicBlock* cur_block, MIR* insn, DexOffset cur_offset,
569 int width, int flags, ArenaBitVector* try_block_addr,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700570 const uint16_t* code_ptr, const uint16_t* code_end) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700571 UNUSED(flags);
buzbee862a7602013-04-05 10:58:54 -0700572 bool in_try_block = try_block_addr->IsBitSet(cur_offset);
buzbee17189ac2013-11-08 11:07:02 -0800573 bool is_throw = (insn->dalvikInsn.opcode == Instruction::THROW);
buzbee311ca162013-02-28 15:56:43 -0800574
575 /* In try block */
576 if (in_try_block) {
577 CatchHandlerIterator iterator(*current_code_item_, cur_offset);
578
buzbee0d829482013-10-11 15:24:55 -0700579 if (cur_block->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800580 LOG(INFO) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
581 LOG(FATAL) << "Successor block list already in use: "
buzbee0d829482013-10-11 15:24:55 -0700582 << static_cast<int>(cur_block->successor_block_list_type);
buzbee311ca162013-02-28 15:56:43 -0800583 }
584
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700585 for (; iterator.HasNext(); iterator.Next()) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700586 BasicBlock* catch_block = FindBlock(iterator.GetHandlerAddress(), false /* create */,
587 nullptr /* immed_pred_block_p */);
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100588 if (insn->dalvikInsn.opcode == Instruction::MONITOR_EXIT &&
589 IsBadMonitorExitCatch(insn->offset, catch_block->start_offset)) {
590 // Don't allow monitor-exit to catch its own exception, http://b/15745363 .
591 continue;
592 }
593 if (cur_block->successor_block_list_type == kNotUsed) {
594 cur_block->successor_block_list_type = kCatch;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100595 }
buzbee311ca162013-02-28 15:56:43 -0800596 catch_block->catch_entry = true;
597 if (kIsDebugBuild) {
598 catches_.insert(catch_block->start_offset);
599 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700600 SuccessorBlockInfo* successor_block_info = reinterpret_cast<SuccessorBlockInfo*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000601 (arena_->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
buzbee0d829482013-10-11 15:24:55 -0700602 successor_block_info->block = catch_block->id;
buzbee311ca162013-02-28 15:56:43 -0800603 successor_block_info->key = iterator.GetHandlerTypeIndex();
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100604 cur_block->successor_blocks.push_back(successor_block_info);
605 catch_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800606 }
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100607 in_try_block = (cur_block->successor_block_list_type != kNotUsed);
608 }
Vladimir Markoe767f6c2014-10-01 17:38:02 +0100609 bool build_all_edges =
610 (cu_->disable_opt & (1 << kSuppressExceptionEdges)) || is_throw || in_try_block;
Vladimir Markoe8ae8142014-07-08 18:06:45 +0100611 if (!in_try_block && build_all_edges) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100612 BasicBlock* eh_block = CreateNewBB(kExceptionHandling);
buzbee0d829482013-10-11 15:24:55 -0700613 cur_block->taken = eh_block->id;
buzbee311ca162013-02-28 15:56:43 -0800614 eh_block->start_offset = cur_offset;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100615 eh_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800616 }
617
buzbee17189ac2013-11-08 11:07:02 -0800618 if (is_throw) {
buzbee311ca162013-02-28 15:56:43 -0800619 cur_block->explicit_throw = true;
buzbee27247762013-07-28 12:03:58 -0700620 if (code_ptr < code_end) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700621 // Force creation of new block following THROW via side-effect.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700622 FindBlock(cur_offset + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800623 }
624 if (!in_try_block) {
625 // Don't split a THROW that can't rethrow - we're done.
626 return cur_block;
627 }
628 }
629
buzbee17189ac2013-11-08 11:07:02 -0800630 if (!build_all_edges) {
631 /*
632 * Even though there is an exception edge here, control cannot return to this
633 * method. Thus, for the purposes of dataflow analysis and optimization, we can
634 * ignore the edge. Doing this reduces compile time, and increases the scope
635 * of the basic-block level optimization pass.
636 */
637 return cur_block;
638 }
639
buzbee311ca162013-02-28 15:56:43 -0800640 /*
641 * Split the potentially-throwing instruction into two parts.
642 * The first half will be a pseudo-op that captures the exception
643 * edges and terminates the basic block. It always falls through.
644 * Then, create a new basic block that begins with the throwing instruction
645 * (minus exceptions). Note: this new basic block must NOT be entered into
646 * the block_map. If the potentially-throwing instruction is the target of a
647 * future branch, we need to find the check psuedo half. The new
648 * basic block containing the work portion of the instruction should
649 * only be entered via fallthrough from the block containing the
650 * pseudo exception edge MIR. Note also that this new block is
651 * not automatically terminated after the work portion, and may
652 * contain following instructions.
buzbeeb48819d2013-09-14 16:15:25 -0700653 *
654 * Note also that the dex_pc_to_block_map_ entry for the potentially
655 * throwing instruction will refer to the original basic block.
buzbee311ca162013-02-28 15:56:43 -0800656 */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100657 BasicBlock* new_block = CreateNewBB(kDalvikByteCode);
buzbee311ca162013-02-28 15:56:43 -0800658 new_block->start_offset = insn->offset;
buzbee0d829482013-10-11 15:24:55 -0700659 cur_block->fall_through = new_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100660 new_block->predecessors.push_back(cur_block->id);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700661 MIR* new_insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800662 *new_insn = *insn;
buzbee35ba7f32014-05-31 08:59:01 -0700663 insn->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpCheck);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700664 // Associate the two halves.
buzbee311ca162013-02-28 15:56:43 -0800665 insn->meta.throw_insn = new_insn;
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700666 new_block->AppendMIR(new_insn);
buzbee311ca162013-02-28 15:56:43 -0800667 return new_block;
668}
669
670/* Parse a Dex method and insert it into the MIRGraph at the current insert point. */
671void MIRGraph::InlineMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700672 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700673 uint32_t method_idx, jobject class_loader, const DexFile& dex_file) {
buzbee311ca162013-02-28 15:56:43 -0800674 current_code_item_ = code_item;
675 method_stack_.push_back(std::make_pair(current_method_, current_offset_));
676 current_method_ = m_units_.size();
677 current_offset_ = 0;
678 // TODO: will need to snapshot stack image and use that as the mir context identification.
679 m_units_.push_back(new DexCompilationUnit(cu_, class_loader, Runtime::Current()->GetClassLinker(),
Vladimir Marko2730db02014-01-27 11:15:17 +0000680 dex_file, current_code_item_, class_def_idx, method_idx, access_flags,
681 cu_->compiler_driver->GetVerifiedMethod(&dex_file, method_idx)));
buzbee311ca162013-02-28 15:56:43 -0800682 const uint16_t* code_ptr = current_code_item_->insns_;
683 const uint16_t* code_end =
684 current_code_item_->insns_ + current_code_item_->insns_size_in_code_units_;
685
686 // TODO: need to rework expansion of block list & try_block_addr when inlining activated.
buzbeeb48819d2013-09-14 16:15:25 -0700687 // TUNING: use better estimate of basic blocks for following resize.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100688 block_list_.reserve(block_list_.size() + current_code_item_->insns_size_in_code_units_);
689 dex_pc_to_block_map_.resize(dex_pc_to_block_map_.size() + current_code_item_->insns_size_in_code_units_);
buzbeebd663de2013-09-10 15:41:31 -0700690
buzbee311ca162013-02-28 15:56:43 -0800691 // TODO: replace with explicit resize routine. Using automatic extension side effect for now.
buzbee862a7602013-04-05 10:58:54 -0700692 try_block_addr_->SetBit(current_code_item_->insns_size_in_code_units_);
693 try_block_addr_->ClearBit(current_code_item_->insns_size_in_code_units_);
buzbee311ca162013-02-28 15:56:43 -0800694
695 // If this is the first method, set up default entry and exit blocks.
696 if (current_method_ == 0) {
697 DCHECK(entry_block_ == NULL);
698 DCHECK(exit_block_ == NULL);
Vladimir Markoffda4992014-12-18 17:05:58 +0000699 DCHECK_EQ(GetNumBlocks(), 0U);
buzbee0d829482013-10-11 15:24:55 -0700700 // Use id 0 to represent a null block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100701 BasicBlock* null_block = CreateNewBB(kNullBlock);
buzbee0d829482013-10-11 15:24:55 -0700702 DCHECK_EQ(null_block->id, NullBasicBlockId);
703 null_block->hidden = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100704 entry_block_ = CreateNewBB(kEntryBlock);
705 exit_block_ = CreateNewBB(kExitBlock);
buzbee311ca162013-02-28 15:56:43 -0800706 // TODO: deprecate all "cu->" fields; move what's left to wherever CompilationUnit is allocated.
707 cu_->dex_file = &dex_file;
708 cu_->class_def_idx = class_def_idx;
709 cu_->method_idx = method_idx;
710 cu_->access_flags = access_flags;
711 cu_->invoke_type = invoke_type;
712 cu_->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
buzbee311ca162013-02-28 15:56:43 -0800713 } else {
714 UNIMPLEMENTED(FATAL) << "Nested inlining not implemented.";
715 /*
716 * Will need to manage storage for ins & outs, push prevous state and update
717 * insert point.
718 */
719 }
720
721 /* Current block to record parsed instructions */
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100722 BasicBlock* cur_block = CreateNewBB(kDalvikByteCode);
buzbee0d829482013-10-11 15:24:55 -0700723 DCHECK_EQ(current_offset_, 0U);
buzbee311ca162013-02-28 15:56:43 -0800724 cur_block->start_offset = current_offset_;
buzbee0d829482013-10-11 15:24:55 -0700725 // TODO: for inlining support, insert at the insert point rather than entry block.
726 entry_block_->fall_through = cur_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100727 cur_block->predecessors.push_back(entry_block_->id);
buzbee311ca162013-02-28 15:56:43 -0800728
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000729 /* Identify code range in try blocks and set up the empty catch blocks */
buzbee311ca162013-02-28 15:56:43 -0800730 ProcessTryCatchBlocks();
731
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000732 uint64_t merged_df_flags = 0u;
733
buzbee311ca162013-02-28 15:56:43 -0800734 /* Parse all instructions and put them into containing basic blocks */
735 while (code_ptr < code_end) {
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -0700736 MIR *insn = NewMIR();
buzbee311ca162013-02-28 15:56:43 -0800737 insn->offset = current_offset_;
738 insn->m_unit_index = current_method_;
739 int width = ParseInsn(code_ptr, &insn->dalvikInsn);
buzbee311ca162013-02-28 15:56:43 -0800740 Instruction::Code opcode = insn->dalvikInsn.opcode;
741 if (opcode_count_ != NULL) {
742 opcode_count_[static_cast<int>(opcode)]++;
743 }
744
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -0700745 int flags = insn->dalvikInsn.FlagsOf();
buzbeeb1f1d642014-02-27 12:55:32 -0800746 int verify_flags = Instruction::VerifyFlagsOf(insn->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800747
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700748 uint64_t df_flags = GetDataFlowAttributes(insn);
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000749 merged_df_flags |= df_flags;
buzbee311ca162013-02-28 15:56:43 -0800750
751 if (df_flags & DF_HAS_DEFS) {
752 def_count_ += (df_flags & DF_A_WIDE) ? 2 : 1;
753 }
754
buzbee1da1e2f2013-11-15 13:37:01 -0800755 if (df_flags & DF_LVN) {
756 cur_block->use_lvn = true; // Run local value numbering on this basic block.
757 }
758
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700759 // Check for inline data block signatures.
buzbee27247762013-07-28 12:03:58 -0700760 if (opcode == Instruction::NOP) {
761 // A simple NOP will have a width of 1 at this point, embedded data NOP > 1.
762 if ((width == 1) && ((current_offset_ & 0x1) == 0x1) && ((code_end - code_ptr) > 1)) {
763 // Could be an aligning nop. If an embedded data NOP follows, treat pair as single unit.
764 uint16_t following_raw_instruction = code_ptr[1];
765 if ((following_raw_instruction == Instruction::kSparseSwitchSignature) ||
766 (following_raw_instruction == Instruction::kPackedSwitchSignature) ||
767 (following_raw_instruction == Instruction::kArrayDataSignature)) {
768 width += Instruction::At(code_ptr + 1)->SizeInCodeUnits();
769 }
770 }
771 if (width == 1) {
772 // It is a simple nop - treat normally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700773 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700774 } else {
buzbee0d829482013-10-11 15:24:55 -0700775 DCHECK(cur_block->fall_through == NullBasicBlockId);
776 DCHECK(cur_block->taken == NullBasicBlockId);
buzbee6489d222014-11-25 10:52:19 -0800777 // Unreachable instruction, mark for no continuation and end basic block.
buzbee27247762013-07-28 12:03:58 -0700778 flags &= ~Instruction::kContinue;
buzbee6489d222014-11-25 10:52:19 -0800779 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee27247762013-07-28 12:03:58 -0700780 }
781 } else {
Jean Christophe Beylercdacac42014-03-13 14:54:59 -0700782 cur_block->AppendMIR(insn);
buzbee27247762013-07-28 12:03:58 -0700783 }
784
buzbeeb48819d2013-09-14 16:15:25 -0700785 // Associate the starting dex_pc for this opcode with its containing basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100786 dex_pc_to_block_map_[insn->offset] = cur_block->id;
buzbeeb48819d2013-09-14 16:15:25 -0700787
buzbee27247762013-07-28 12:03:58 -0700788 code_ptr += width;
789
buzbee311ca162013-02-28 15:56:43 -0800790 if (flags & Instruction::kBranch) {
791 cur_block = ProcessCanBranch(cur_block, insn, current_offset_,
792 width, flags, code_ptr, code_end);
793 } else if (flags & Instruction::kReturn) {
794 cur_block->terminated_by_return = true;
buzbee0d829482013-10-11 15:24:55 -0700795 cur_block->fall_through = exit_block_->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100796 exit_block_->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800797 /*
798 * Terminate the current block if there are instructions
799 * afterwards.
800 */
801 if (code_ptr < code_end) {
802 /*
803 * Create a fallthrough block for real instructions
804 * (incl. NOP).
805 */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700806 FindBlock(current_offset_ + width, /* create */ true, /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800807 }
808 } else if (flags & Instruction::kThrow) {
809 cur_block = ProcessCanThrow(cur_block, insn, current_offset_, width, flags, try_block_addr_,
810 code_ptr, code_end);
811 } else if (flags & Instruction::kSwitch) {
buzbee17189ac2013-11-08 11:07:02 -0800812 cur_block = ProcessCanSwitch(cur_block, insn, current_offset_, width, flags);
buzbee311ca162013-02-28 15:56:43 -0800813 }
Alexei Zavjalov688e7c52014-07-16 02:17:58 +0700814 if (verify_flags & Instruction::kVerifyVarArgRange ||
815 verify_flags & Instruction::kVerifyVarArgRangeNonZero) {
buzbeeb1f1d642014-02-27 12:55:32 -0800816 /*
817 * The Quick backend's runtime model includes a gap between a method's
818 * argument ("in") vregs and the rest of its vregs. Handling a range instruction
819 * which spans the gap is somewhat complicated, and should not happen
820 * in normal usage of dx. Punt to the interpreter.
821 */
822 int first_reg_in_range = insn->dalvikInsn.vC;
823 int last_reg_in_range = first_reg_in_range + insn->dalvikInsn.vA - 1;
824 if (IsInVReg(first_reg_in_range) != IsInVReg(last_reg_in_range)) {
825 punt_to_interpreter_ = true;
826 }
827 }
buzbee311ca162013-02-28 15:56:43 -0800828 current_offset_ += width;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700829 BasicBlock* next_block = FindBlock(current_offset_, /* create */ false,
830 /* immed_pred_block_p */ nullptr);
buzbee311ca162013-02-28 15:56:43 -0800831 if (next_block) {
832 /*
833 * The next instruction could be the target of a previously parsed
834 * forward branch so a block is already created. If the current
835 * instruction is not an unconditional branch, connect them through
836 * the fall-through link.
837 */
buzbee0d829482013-10-11 15:24:55 -0700838 DCHECK(cur_block->fall_through == NullBasicBlockId ||
839 GetBasicBlock(cur_block->fall_through) == next_block ||
840 GetBasicBlock(cur_block->fall_through) == exit_block_);
buzbee311ca162013-02-28 15:56:43 -0800841
buzbee0d829482013-10-11 15:24:55 -0700842 if ((cur_block->fall_through == NullBasicBlockId) && (flags & Instruction::kContinue)) {
843 cur_block->fall_through = next_block->id;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100844 next_block->predecessors.push_back(cur_block->id);
buzbee311ca162013-02-28 15:56:43 -0800845 }
846 cur_block = next_block;
847 }
848 }
Vladimir Marko3d73ba22014-03-06 15:18:04 +0000849 merged_df_flags_ = merged_df_flags;
Vladimir Marko5816ed42013-11-27 17:04:20 +0000850
buzbee311ca162013-02-28 15:56:43 -0800851 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
852 DumpCFG("/sdcard/1_post_parse_cfg/", true);
853 }
854
855 if (cu_->verbose) {
buzbee1fd33462013-03-25 13:40:45 -0700856 DumpMIRGraph();
buzbee311ca162013-02-28 15:56:43 -0800857 }
858}
859
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700860void MIRGraph::ShowOpcodeStats() {
buzbee311ca162013-02-28 15:56:43 -0800861 DCHECK(opcode_count_ != NULL);
862 LOG(INFO) << "Opcode Count";
863 for (int i = 0; i < kNumPackedOpcodes; i++) {
864 if (opcode_count_[i] != 0) {
865 LOG(INFO) << "-C- " << Instruction::Name(static_cast<Instruction::Code>(i))
866 << " " << opcode_count_[i];
867 }
868 }
869}
870
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700871uint64_t MIRGraph::GetDataFlowAttributes(Instruction::Code opcode) {
872 DCHECK_LT((size_t) opcode, (sizeof(oat_data_flow_attributes_) / sizeof(oat_data_flow_attributes_[0])));
873 return oat_data_flow_attributes_[opcode];
874}
875
876uint64_t MIRGraph::GetDataFlowAttributes(MIR* mir) {
877 DCHECK(mir != nullptr);
878 Instruction::Code opcode = mir->dalvikInsn.opcode;
879 return GetDataFlowAttributes(opcode);
880}
881
Andreas Gampecee97e52014-12-19 15:30:11 -0800882// The path can easily surpass FS limits because of parameters etc. Use pathconf to get FS
883// restrictions here. Note that a successful invocation will return an actual value. If the path
884// is too long for some reason, the return will be ENAMETOOLONG. Then cut off part of the name.
885//
886// It's possible the path is not valid, or some other errors appear. In that case return false.
887static bool CreateDumpFile(std::string& fname, const char* dir_prefix, NarrowDexOffset start_offset,
888 const char *suffix, int nr, std::string* output) {
889 std::string dir = StringPrintf("./%s", dir_prefix);
890 int64_t max_name_length = pathconf(dir.c_str(), _PC_NAME_MAX);
891 if (max_name_length <= 0) {
892 PLOG(ERROR) << "Could not get file name restrictions for " << dir;
893 return false;
894 }
895
896 std::string name = StringPrintf("%s%x%s_%d.dot", fname.c_str(), start_offset,
897 suffix == nullptr ? "" : suffix, nr);
898 std::string fpath;
899 if (static_cast<int64_t>(name.size()) > max_name_length) {
900 std::string suffix_str = StringPrintf("_%d.dot", nr);
901 name = name.substr(0, static_cast<size_t>(max_name_length) - suffix_str.size()) + suffix_str;
902 }
903 // Sanity check.
904 DCHECK_LE(name.size(), static_cast<size_t>(max_name_length));
905
906 *output = StringPrintf("%s%s", dir_prefix, name.c_str());
907 return true;
908}
909
buzbee311ca162013-02-28 15:56:43 -0800910// TODO: use a configurable base prefix, and adjust callers to supply pass name.
911/* Dump the CFG into a DOT graph */
Jean Christophe Beylerd0a51552014-01-10 14:18:31 -0800912void MIRGraph::DumpCFG(const char* dir_prefix, bool all_blocks, const char *suffix) {
buzbee311ca162013-02-28 15:56:43 -0800913 FILE* file;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700914 static AtomicInteger cnt(0);
915
916 // Increment counter to get a unique file number.
917 cnt++;
Andreas Gampecee97e52014-12-19 15:30:11 -0800918 int nr = cnt.LoadRelaxed();
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700919
buzbee311ca162013-02-28 15:56:43 -0800920 std::string fname(PrettyMethod(cu_->method_idx, *cu_->dex_file));
921 ReplaceSpecialChars(fname);
Andreas Gampecee97e52014-12-19 15:30:11 -0800922 std::string fpath;
923 if (!CreateDumpFile(fname, dir_prefix, GetBasicBlock(GetEntryBlock()->fall_through)->start_offset,
924 suffix, nr, &fpath)) {
925 LOG(ERROR) << "Could not create dump file name for " << fname;
926 return;
927 }
928 file = fopen(fpath.c_str(), "w");
buzbee311ca162013-02-28 15:56:43 -0800929 if (file == NULL) {
Andreas Gampecee97e52014-12-19 15:30:11 -0800930 PLOG(ERROR) << "Could not open " << fpath << " for DumpCFG.";
buzbee311ca162013-02-28 15:56:43 -0800931 return;
932 }
933 fprintf(file, "digraph G {\n");
934
935 fprintf(file, " rankdir=TB\n");
936
937 int num_blocks = all_blocks ? GetNumBlocks() : num_reachable_blocks_;
938 int idx;
939
940 for (idx = 0; idx < num_blocks; idx++) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100941 int block_idx = all_blocks ? idx : dfs_order_[idx];
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700942 BasicBlock* bb = GetBasicBlock(block_idx);
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -0700943 if (bb == NULL) continue;
buzbee311ca162013-02-28 15:56:43 -0800944 if (bb->block_type == kDead) continue;
Jean Christophe Beylera8869e62014-06-19 09:34:51 -0700945 if (bb->hidden) continue;
buzbee311ca162013-02-28 15:56:43 -0800946 if (bb->block_type == kEntryBlock) {
947 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
948 } else if (bb->block_type == kExitBlock) {
949 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
950 } else if (bb->block_type == kDalvikByteCode) {
951 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
952 bb->start_offset, bb->id);
Jean Christophe Beyler85127582014-05-11 23:36:41 -0700953 const MIR* mir;
buzbee311ca162013-02-28 15:56:43 -0800954 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
955 bb->first_mir_insn ? " | " : " ");
956 for (mir = bb->first_mir_insn; mir; mir = mir->next) {
957 int opcode = mir->dalvikInsn.opcode;
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800958 fprintf(file, " {%04x %s %s %s %s %s %s %s %s %s\\l}%s\\\n", mir->offset,
Mark Mendelld65c51a2014-04-29 16:55:20 -0400959 mir->ssa_rep ? GetDalvikDisassembly(mir) :
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700960 !MIR::DecodedInstruction::IsPseudoMirOp(opcode) ?
961 Instruction::Name(mir->dalvikInsn.opcode) :
Mark Mendelld65c51a2014-04-29 16:55:20 -0400962 extended_mir_op_names_[opcode - kMirOpFirst],
963 (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0 ? " no_rangecheck" : " ",
964 (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0 ? " no_nullcheck" : " ",
Udayan Banerji60bfe7b2014-07-08 19:59:43 -0700965 (mir->optimization_flags & MIR_IGNORE_SUSPEND_CHECK) != 0 ? " no_suspendcheck" : " ",
Jean Christophe Beylerb5bce7c2014-07-25 12:32:18 -0700966 (mir->optimization_flags & MIR_STORE_NON_TEMPORAL) != 0 ? " non_temporal" : " ",
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -0700967 (mir->optimization_flags & MIR_CALLEE) != 0 ? " inlined" : " ",
Vladimir Marko66c6d7b2014-10-16 15:41:48 +0100968 (mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0 ? " cl_inited" : " ",
969 (mir->optimization_flags & MIR_CLASS_IS_IN_DEX_CACHE) != 0 ? " cl_in_cache" : " ",
Razvan A Lupusorue0951142014-11-14 14:36:55 -0800970 (mir->optimization_flags & MIR_IGNORE_DIV_ZERO_CHECK) != 0 ? " no_div_check" : " ",
Mark Mendelld65c51a2014-04-29 16:55:20 -0400971 mir->next ? " | " : " ");
buzbee311ca162013-02-28 15:56:43 -0800972 }
973 fprintf(file, " }\"];\n\n");
974 } else if (bb->block_type == kExceptionHandling) {
975 char block_name[BLOCK_NAME_LEN];
976
977 GetBlockName(bb, block_name);
978 fprintf(file, " %s [shape=invhouse];\n", block_name);
979 }
980
981 char block_name1[BLOCK_NAME_LEN], block_name2[BLOCK_NAME_LEN];
982
buzbee0d829482013-10-11 15:24:55 -0700983 if (bb->taken != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800984 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700985 GetBlockName(GetBasicBlock(bb->taken), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800986 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
987 block_name1, block_name2);
988 }
buzbee0d829482013-10-11 15:24:55 -0700989 if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800990 GetBlockName(bb, block_name1);
buzbee0d829482013-10-11 15:24:55 -0700991 GetBlockName(GetBasicBlock(bb->fall_through), block_name2);
buzbee311ca162013-02-28 15:56:43 -0800992 fprintf(file, " %s:s -> %s:n\n", block_name1, block_name2);
993 }
994
buzbee0d829482013-10-11 15:24:55 -0700995 if (bb->successor_block_list_type != kNotUsed) {
buzbee311ca162013-02-28 15:56:43 -0800996 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
997 bb->start_offset, bb->id,
buzbee0d829482013-10-11 15:24:55 -0700998 (bb->successor_block_list_type == kCatch) ? "Mrecord" : "record");
buzbee311ca162013-02-28 15:56:43 -0800999
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001000 int last_succ_id = static_cast<int>(bb->successor_blocks.size() - 1u);
buzbee311ca162013-02-28 15:56:43 -08001001 int succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001002 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001003 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001004 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001005 succ_id,
buzbee311ca162013-02-28 15:56:43 -08001006 successor_block_info->key,
1007 dest_block->start_offset,
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001008 (succ_id != last_succ_id) ? " | " : " ");
1009 ++succ_id;
buzbee311ca162013-02-28 15:56:43 -08001010 }
1011 fprintf(file, " }\"];\n\n");
1012
1013 GetBlockName(bb, block_name1);
1014 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
1015 block_name1, bb->start_offset, bb->id);
1016
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001017 // Link the successor pseudo-block with all of its potential targets.
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001018 succ_id = 0;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001019 for (SuccessorBlockInfo* successor_block_info : bb->successor_blocks) {
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001020 BasicBlock* dest_block = GetBasicBlock(successor_block_info->block);
buzbee311ca162013-02-28 15:56:43 -08001021
Razvan A Lupusoru25bc2792014-03-19 14:27:59 -07001022 GetBlockName(dest_block, block_name2);
1023 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->start_offset,
1024 bb->id, succ_id++, block_name2);
buzbee311ca162013-02-28 15:56:43 -08001025 }
1026 }
1027 fprintf(file, "\n");
1028
1029 if (cu_->verbose) {
1030 /* Display the dominator tree */
1031 GetBlockName(bb, block_name1);
1032 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1033 block_name1, block_name1);
1034 if (bb->i_dom) {
buzbee0d829482013-10-11 15:24:55 -07001035 GetBlockName(GetBasicBlock(bb->i_dom), block_name2);
buzbee311ca162013-02-28 15:56:43 -08001036 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", block_name2, block_name1);
1037 }
1038 }
1039 }
1040 fprintf(file, "}\n");
1041 fclose(file);
1042}
1043
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001044/* Insert an MIR instruction to the end of a basic block. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001045void BasicBlock::AppendMIR(MIR* mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001046 // Insert it after the last MIR.
1047 InsertMIRListAfter(last_mir_insn, mir, mir);
buzbee1fd33462013-03-25 13:40:45 -07001048}
1049
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001050void BasicBlock::AppendMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1051 // Insert it after the last MIR.
1052 InsertMIRListAfter(last_mir_insn, first_list_mir, last_list_mir);
1053}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001054
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001055void BasicBlock::AppendMIRList(const std::vector<MIR*>& insns) {
1056 for (std::vector<MIR*>::const_iterator it = insns.begin(); it != insns.end(); it++) {
1057 MIR* new_mir = *it;
1058
1059 // Add a copy of each MIR.
1060 InsertMIRListAfter(last_mir_insn, new_mir, new_mir);
1061 }
buzbee1fd33462013-03-25 13:40:45 -07001062}
1063
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001064/* Insert a MIR instruction after the specified MIR. */
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001065void BasicBlock::InsertMIRAfter(MIR* current_mir, MIR* new_mir) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001066 InsertMIRListAfter(current_mir, new_mir, new_mir);
1067}
buzbee1fd33462013-03-25 13:40:45 -07001068
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001069void BasicBlock::InsertMIRListAfter(MIR* insert_after, MIR* first_list_mir, MIR* last_list_mir) {
1070 // If no MIR, we are done.
1071 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1072 return;
buzbee1fd33462013-03-25 13:40:45 -07001073 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001074
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001075 // If insert_after is null, assume BB is empty.
1076 if (insert_after == nullptr) {
1077 first_mir_insn = first_list_mir;
1078 last_mir_insn = last_list_mir;
1079 last_list_mir->next = nullptr;
1080 } else {
1081 MIR* after_list = insert_after->next;
1082 insert_after->next = first_list_mir;
1083 last_list_mir->next = after_list;
1084 if (after_list == nullptr) {
1085 last_mir_insn = last_list_mir;
1086 }
1087 }
1088
1089 // Set this BB to be the basic block of the MIRs.
1090 MIR* last = last_list_mir->next;
1091 for (MIR* mir = first_list_mir; mir != last; mir = mir->next) {
1092 mir->bb = id;
1093 }
1094}
1095
1096/* Insert an MIR instruction to the head of a basic block. */
1097void BasicBlock::PrependMIR(MIR* mir) {
1098 InsertMIRListBefore(first_mir_insn, mir, mir);
1099}
1100
1101void BasicBlock::PrependMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1102 // Insert it before the first MIR.
1103 InsertMIRListBefore(first_mir_insn, first_list_mir, last_list_mir);
1104}
1105
1106void BasicBlock::PrependMIRList(const std::vector<MIR*>& to_add) {
1107 for (std::vector<MIR*>::const_iterator it = to_add.begin(); it != to_add.end(); it++) {
1108 MIR* mir = *it;
1109
1110 InsertMIRListBefore(first_mir_insn, mir, mir);
1111 }
1112}
1113
1114/* Insert a MIR instruction before the specified MIR. */
1115void BasicBlock::InsertMIRBefore(MIR* current_mir, MIR* new_mir) {
1116 // Insert as a single element list.
1117 return InsertMIRListBefore(current_mir, new_mir, new_mir);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001118}
1119
1120MIR* BasicBlock::FindPreviousMIR(MIR* mir) {
1121 MIR* current = first_mir_insn;
1122
1123 while (current != nullptr) {
1124 MIR* next = current->next;
1125
1126 if (next == mir) {
1127 return current;
1128 }
1129
1130 current = next;
1131 }
1132
1133 return nullptr;
1134}
1135
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001136void BasicBlock::InsertMIRListBefore(MIR* insert_before, MIR* first_list_mir, MIR* last_list_mir) {
1137 // If no MIR, we are done.
1138 if (first_list_mir == nullptr || last_list_mir == nullptr) {
1139 return;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001140 }
1141
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001142 // If insert_before is null, assume BB is empty.
1143 if (insert_before == nullptr) {
1144 first_mir_insn = first_list_mir;
1145 last_mir_insn = last_list_mir;
1146 last_list_mir->next = nullptr;
1147 } else {
1148 if (first_mir_insn == insert_before) {
1149 last_list_mir->next = first_mir_insn;
1150 first_mir_insn = first_list_mir;
1151 } else {
1152 // Find the preceding MIR.
1153 MIR* before_list = FindPreviousMIR(insert_before);
1154 DCHECK(before_list != nullptr);
1155 before_list->next = first_list_mir;
1156 last_list_mir->next = insert_before;
1157 }
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001158 }
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001159
1160 // Set this BB to be the basic block of the MIRs.
1161 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
1162 mir->bb = id;
1163 }
1164}
1165
1166bool BasicBlock::RemoveMIR(MIR* mir) {
1167 // Remove as a single element list.
1168 return RemoveMIRList(mir, mir);
1169}
1170
1171bool BasicBlock::RemoveMIRList(MIR* first_list_mir, MIR* last_list_mir) {
1172 if (first_list_mir == nullptr) {
1173 return false;
1174 }
1175
1176 // Try to find the MIR.
1177 MIR* before_list = nullptr;
1178 MIR* after_list = nullptr;
1179
1180 // If we are removing from the beginning of the MIR list.
1181 if (first_mir_insn == first_list_mir) {
1182 before_list = nullptr;
1183 } else {
1184 before_list = FindPreviousMIR(first_list_mir);
1185 if (before_list == nullptr) {
1186 // We did not find the mir.
1187 return false;
1188 }
1189 }
1190
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001191 // Remove the BB information and also find the after_list.
Chao-ying Fu590c6a42014-09-23 14:54:32 -07001192 for (MIR* mir = first_list_mir; mir != last_list_mir->next; mir = mir->next) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001193 mir->bb = NullBasicBlockId;
1194 }
1195
1196 after_list = last_list_mir->next;
1197
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001198 // If there is nothing before the list, after_list is the first_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001199 if (before_list == nullptr) {
1200 first_mir_insn = after_list;
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001201 } else {
1202 before_list->next = after_list;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001203 }
1204
Jean Christophe Beylera4307ac2014-06-02 09:04:32 -07001205 // If there is nothing after the list, before_list is last_mir.
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001206 if (after_list == nullptr) {
1207 last_mir_insn = before_list;
1208 }
1209
1210 return true;
buzbee1fd33462013-03-25 13:40:45 -07001211}
1212
Vladimir Marko26e7d452014-11-24 14:09:46 +00001213MIR* BasicBlock::GetFirstNonPhiInsn() {
1214 MIR* mir = first_mir_insn;
1215 while (mir != nullptr && static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
1216 mir = mir->next;
1217 }
1218 return mir;
1219}
1220
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001221MIR* BasicBlock::GetNextUnconditionalMir(MIRGraph* mir_graph, MIR* current) {
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001222 MIR* next_mir = nullptr;
1223
1224 if (current != nullptr) {
1225 next_mir = current->next;
1226 }
1227
1228 if (next_mir == nullptr) {
1229 // Only look for next MIR that follows unconditionally.
Jean Christophe Beylercdacac42014-03-13 14:54:59 -07001230 if ((taken == NullBasicBlockId) && (fall_through != NullBasicBlockId)) {
1231 next_mir = mir_graph->GetBasicBlock(fall_through)->first_mir_insn;
Razvan A Lupusoru3bc01742014-02-06 13:18:43 -08001232 }
1233 }
1234
1235 return next_mir;
1236}
1237
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001238static void FillTypeSizeString(uint32_t type_size, std::string* decoded_mir) {
1239 DCHECK(decoded_mir != nullptr);
1240 OpSize type = static_cast<OpSize>(type_size >> 16);
1241 uint16_t vect_size = (type_size & 0xFFFF);
1242
1243 // Now print the type and vector size.
1244 std::stringstream ss;
1245 ss << " (type:";
1246 ss << type;
1247 ss << " vectsize:";
1248 ss << vect_size;
1249 ss << ")";
1250
1251 decoded_mir->append(ss.str());
1252}
1253
1254void MIRGraph::DisassembleExtendedInstr(const MIR* mir, std::string* decoded_mir) {
1255 DCHECK(decoded_mir != nullptr);
1256 int opcode = mir->dalvikInsn.opcode;
1257 SSARepresentation* ssa_rep = mir->ssa_rep;
1258 int defs = (ssa_rep != nullptr) ? ssa_rep->num_defs : 0;
1259 int uses = (ssa_rep != nullptr) ? ssa_rep->num_uses : 0;
1260
Vladimirf41b92c2014-10-13 13:41:38 +07001261 if (opcode < kMirOpFirst) {
1262 return; // It is not an extended instruction.
1263 }
1264
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001265 decoded_mir->append(extended_mir_op_names_[opcode - kMirOpFirst]);
1266
1267 switch (opcode) {
1268 case kMirOpPhi: {
1269 if (defs > 0 && uses > 0) {
1270 BasicBlockId* incoming = mir->meta.phi_incoming;
1271 decoded_mir->append(StringPrintf(" %s = (%s",
1272 GetSSANameWithConst(ssa_rep->defs[0], true).c_str(),
1273 GetSSANameWithConst(ssa_rep->uses[0], true).c_str()));
1274 decoded_mir->append(StringPrintf(":%d", incoming[0]));
1275 for (int i = 1; i < uses; i++) {
1276 decoded_mir->append(StringPrintf(", %s:%d", GetSSANameWithConst(ssa_rep->uses[i], true).c_str(), incoming[i]));
1277 }
1278 decoded_mir->append(")");
1279 }
1280 break;
1281 }
1282 case kMirOpCopy:
1283 if (ssa_rep != nullptr) {
1284 decoded_mir->append(" ");
1285 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1286 if (defs > 1) {
1287 decoded_mir->append(", ");
1288 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1289 }
1290 decoded_mir->append(" = ");
1291 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1292 if (uses > 1) {
1293 decoded_mir->append(", ");
1294 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1295 }
1296 } else {
1297 decoded_mir->append(StringPrintf(" v%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1298 }
1299 break;
1300 case kMirOpFusedCmplFloat:
1301 case kMirOpFusedCmpgFloat:
1302 case kMirOpFusedCmplDouble:
1303 case kMirOpFusedCmpgDouble:
1304 case kMirOpFusedCmpLong:
1305 if (ssa_rep != nullptr) {
1306 decoded_mir->append(" ");
1307 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[0], false));
1308 for (int i = 1; i < uses; i++) {
1309 decoded_mir->append(", ");
1310 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1311 }
1312 } else {
1313 decoded_mir->append(StringPrintf(" v%d, v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1314 }
1315 break;
1316 case kMirOpMoveVector:
1317 decoded_mir->append(StringPrintf(" vect%d = vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1318 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1319 break;
1320 case kMirOpPackedAddition:
1321 decoded_mir->append(StringPrintf(" vect%d = vect%d + vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1322 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1323 break;
1324 case kMirOpPackedMultiply:
1325 decoded_mir->append(StringPrintf(" vect%d = vect%d * vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1326 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1327 break;
1328 case kMirOpPackedSubtract:
1329 decoded_mir->append(StringPrintf(" vect%d = vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1330 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1331 break;
1332 case kMirOpPackedAnd:
1333 decoded_mir->append(StringPrintf(" vect%d = vect%d & vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1334 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1335 break;
1336 case kMirOpPackedOr:
1337 decoded_mir->append(StringPrintf(" vect%d = vect%d \\| vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1338 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1339 break;
1340 case kMirOpPackedXor:
1341 decoded_mir->append(StringPrintf(" vect%d = vect%d ^ vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1342 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1343 break;
1344 case kMirOpPackedShiftLeft:
1345 decoded_mir->append(StringPrintf(" vect%d = vect%d \\<\\< %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1346 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1347 break;
1348 case kMirOpPackedUnsignedShiftRight:
1349 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1350 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1351 break;
1352 case kMirOpPackedSignedShiftRight:
1353 decoded_mir->append(StringPrintf(" vect%d = vect%d \\>\\> %d", mir->dalvikInsn.vA, mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1354 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1355 break;
1356 case kMirOpConstVector:
1357 decoded_mir->append(StringPrintf(" vect%d = %x, %x, %x, %x", mir->dalvikInsn.vA, mir->dalvikInsn.arg[0],
1358 mir->dalvikInsn.arg[1], mir->dalvikInsn.arg[2], mir->dalvikInsn.arg[3]));
1359 break;
1360 case kMirOpPackedSet:
1361 if (ssa_rep != nullptr) {
1362 decoded_mir->append(StringPrintf(" vect%d = %s", mir->dalvikInsn.vA,
1363 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1364 if (uses > 1) {
1365 decoded_mir->append(", ");
1366 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1367 }
1368 } else {
1369 decoded_mir->append(StringPrintf(" vect%d = v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1370 }
1371 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1372 break;
1373 case kMirOpPackedAddReduce:
1374 if (ssa_rep != nullptr) {
1375 decoded_mir->append(" ");
1376 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1377 if (defs > 1) {
1378 decoded_mir->append(", ");
1379 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1380 }
1381 decoded_mir->append(StringPrintf(" = vect%d + %s", mir->dalvikInsn.vB,
1382 GetSSANameWithConst(ssa_rep->uses[0], false).c_str()));
1383 if (uses > 1) {
1384 decoded_mir->append(", ");
1385 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[1], false));
1386 }
1387 } else {
1388 decoded_mir->append(StringPrintf("v%d = vect%d + v%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB, mir->dalvikInsn.vA));
1389 }
1390 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1391 break;
1392 case kMirOpPackedReduce:
1393 if (ssa_rep != nullptr) {
1394 decoded_mir->append(" ");
1395 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1396 if (defs > 1) {
1397 decoded_mir->append(", ");
1398 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1399 }
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001400 decoded_mir->append(StringPrintf(" = vect%d (extr_idx:%d)", mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001401 } else {
Razvan A Lupusorub72c7232014-10-28 19:29:52 -07001402 decoded_mir->append(StringPrintf(" v%d = vect%d (extr_idx:%d)", mir->dalvikInsn.vA,
1403 mir->dalvikInsn.vB, mir->dalvikInsn.arg[0]));
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001404 }
1405 FillTypeSizeString(mir->dalvikInsn.vC, decoded_mir);
1406 break;
1407 case kMirOpReserveVectorRegisters:
1408 case kMirOpReturnVectorRegisters:
1409 decoded_mir->append(StringPrintf(" vect%d - vect%d", mir->dalvikInsn.vA, mir->dalvikInsn.vB));
1410 break;
1411 case kMirOpMemBarrier: {
1412 decoded_mir->append(" type:");
1413 std::stringstream ss;
1414 ss << static_cast<MemBarrierKind>(mir->dalvikInsn.vA);
1415 decoded_mir->append(ss.str());
1416 break;
1417 }
Lupusoru, Razvan Ab3a84e22014-07-28 14:11:01 -07001418 case kMirOpPackedArrayGet:
1419 case kMirOpPackedArrayPut:
1420 decoded_mir->append(StringPrintf(" vect%d", mir->dalvikInsn.vA));
1421 if (ssa_rep != nullptr) {
1422 decoded_mir->append(StringPrintf(", %s[%s]",
1423 GetSSANameWithConst(ssa_rep->uses[0], false).c_str(),
1424 GetSSANameWithConst(ssa_rep->uses[1], false).c_str()));
1425 } else {
1426 decoded_mir->append(StringPrintf(", v%d[v%d]", mir->dalvikInsn.vB, mir->dalvikInsn.vC));
1427 }
1428 FillTypeSizeString(mir->dalvikInsn.arg[0], decoded_mir);
1429 break;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001430 case kMirOpMaddInt:
1431 case kMirOpMsubInt:
1432 case kMirOpMaddLong:
1433 case kMirOpMsubLong:
1434 if (ssa_rep != nullptr) {
1435 decoded_mir->append(" ");
1436 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[0], false));
1437 if (defs > 1) {
1438 decoded_mir->append(", ");
1439 decoded_mir->append(GetSSANameWithConst(ssa_rep->defs[1], false));
1440 }
1441 for (int i = 0; i < uses; i++) {
1442 decoded_mir->append(", ");
1443 decoded_mir->append(GetSSANameWithConst(ssa_rep->uses[i], false));
1444 }
1445 } else {
1446 decoded_mir->append(StringPrintf(" v%d, v%d, v%d, v%d",
1447 mir->dalvikInsn.vA, mir->dalvikInsn.vB,
1448 mir->dalvikInsn.vC, mir->dalvikInsn.arg[0]));
1449 }
1450 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001451 default:
1452 break;
1453 }
1454}
1455
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001456char* MIRGraph::GetDalvikDisassembly(const MIR* mir) {
Ian Rogers29a26482014-05-02 15:27:29 -07001457 MIR::DecodedInstruction insn = mir->dalvikInsn;
buzbee1fd33462013-03-25 13:40:45 -07001458 std::string str;
1459 int flags = 0;
1460 int opcode = insn.opcode;
1461 char* ret;
1462 bool nop = false;
1463 SSARepresentation* ssa_rep = mir->ssa_rep;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001464 Instruction::Format dalvik_format = Instruction::k10x; // Default to no-operand format.
buzbee1fd33462013-03-25 13:40:45 -07001465
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001466 // Handle special cases that recover the original dalvik instruction.
buzbee1fd33462013-03-25 13:40:45 -07001467 if ((opcode == kMirOpCheck) || (opcode == kMirOpCheckPart2)) {
1468 str.append(extended_mir_op_names_[opcode - kMirOpFirst]);
1469 str.append(": ");
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001470 // Recover the original Dex instruction.
buzbee1fd33462013-03-25 13:40:45 -07001471 insn = mir->meta.throw_insn->dalvikInsn;
1472 ssa_rep = mir->meta.throw_insn->ssa_rep;
buzbee1fd33462013-03-25 13:40:45 -07001473 opcode = insn.opcode;
1474 } else if (opcode == kMirOpNop) {
1475 str.append("[");
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001476 if (mir->offset < current_code_item_->insns_size_in_code_units_) {
1477 // Recover original opcode.
1478 insn.opcode = Instruction::At(current_code_item_->insns_ + mir->offset)->Opcode();
1479 opcode = insn.opcode;
1480 }
buzbee1fd33462013-03-25 13:40:45 -07001481 nop = true;
1482 }
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001483 int defs = (ssa_rep != NULL) ? ssa_rep->num_defs : 0;
1484 int uses = (ssa_rep != NULL) ? ssa_rep->num_uses : 0;
buzbee1fd33462013-03-25 13:40:45 -07001485
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001486 if (MIR::DecodedInstruction::IsPseudoMirOp(opcode)) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001487 // Note that this does not check the MIR's opcode in all cases. In cases where it
1488 // recovered dalvik instruction, it uses opcode of that instead of the extended one.
1489 DisassembleExtendedInstr(mir, &str);
buzbee1fd33462013-03-25 13:40:45 -07001490 } else {
1491 dalvik_format = Instruction::FormatOf(insn.opcode);
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001492 flags = insn.FlagsOf();
buzbee1fd33462013-03-25 13:40:45 -07001493 str.append(Instruction::Name(insn.opcode));
buzbee1fd33462013-03-25 13:40:45 -07001494
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001495 // For invokes-style formats, treat wide regs as a pair of singles.
buzbee1fd33462013-03-25 13:40:45 -07001496 bool show_singles = ((dalvik_format == Instruction::k35c) ||
1497 (dalvik_format == Instruction::k3rc));
1498 if (defs != 0) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001499 str.append(" ");
1500 str.append(GetSSANameWithConst(ssa_rep->defs[0], false));
1501 if (defs > 1) {
1502 str.append(", ");
1503 str.append(GetSSANameWithConst(ssa_rep->defs[1], false));
1504 }
buzbee1fd33462013-03-25 13:40:45 -07001505 if (uses != 0) {
1506 str.append(", ");
1507 }
1508 }
1509 for (int i = 0; i < uses; i++) {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001510 str.append(" ");
1511 str.append(GetSSANameWithConst(ssa_rep->uses[i], show_singles));
buzbee1fd33462013-03-25 13:40:45 -07001512 if (!show_singles && (reg_location_ != NULL) && reg_location_[i].wide) {
1513 // For the listing, skip the high sreg.
1514 i++;
1515 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001516 if (i != (uses - 1)) {
buzbee1fd33462013-03-25 13:40:45 -07001517 str.append(",");
1518 }
1519 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001520
buzbee1fd33462013-03-25 13:40:45 -07001521 switch (dalvik_format) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001522 case Instruction::k11n: // Add one immediate from vB.
buzbee1fd33462013-03-25 13:40:45 -07001523 case Instruction::k21s:
1524 case Instruction::k31i:
1525 case Instruction::k21h:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001526 str.append(StringPrintf(", #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001527 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001528 case Instruction::k51l: // Add one wide immediate.
Ian Rogers23b03b52014-01-24 11:10:03 -08001529 str.append(StringPrintf(", #%" PRId64, insn.vB_wide));
buzbee1fd33462013-03-25 13:40:45 -07001530 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001531 case Instruction::k21c: // One register, one string/type/method index.
buzbee1fd33462013-03-25 13:40:45 -07001532 case Instruction::k31c:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001533 str.append(StringPrintf(", index #0x%x", insn.vB));
buzbee1fd33462013-03-25 13:40:45 -07001534 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001535 case Instruction::k22c: // Two registers, one string/type/method index.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001536 str.append(StringPrintf(", index #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001537 break;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001538 case Instruction::k22s: // Add one immediate from vC.
buzbee1fd33462013-03-25 13:40:45 -07001539 case Instruction::k22b:
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001540 str.append(StringPrintf(", #0x%x", insn.vC));
buzbee1fd33462013-03-25 13:40:45 -07001541 break;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001542 default:
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001543 // Nothing left to print.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001544 break;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001545 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001546
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001547 if ((flags & Instruction::kBranch) != 0) {
1548 // For branches, decode the instructions to print out the branch targets.
1549 int offset = 0;
1550 switch (dalvik_format) {
1551 case Instruction::k21t:
1552 offset = insn.vB;
1553 break;
1554 case Instruction::k22t:
1555 offset = insn.vC;
1556 break;
1557 case Instruction::k10t:
1558 case Instruction::k20t:
1559 case Instruction::k30t:
1560 offset = insn.vA;
1561 break;
1562 default:
1563 LOG(FATAL) << "Unexpected branch format " << dalvik_format << " from " << insn.opcode;
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001564 break;
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001565 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001566 str.append(StringPrintf(", 0x%x (%c%x)", mir->offset + offset,
Serguei Katkov0f3e4982014-08-21 16:43:54 +07001567 offset > 0 ? '+' : '-', offset > 0 ? offset : -offset));
1568 }
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001569
1570 if (nop) {
1571 str.append("]--optimized away");
1572 }
buzbee1fd33462013-03-25 13:40:45 -07001573 }
1574 int length = str.length() + 1;
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001575 ret = static_cast<char*>(arena_->Alloc(length, kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001576 strncpy(ret, str.c_str(), length);
1577 return ret;
1578}
1579
1580/* Turn method name into a legal Linux file name */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001581void MIRGraph::ReplaceSpecialChars(std::string& str) {
Brian Carlstrom9b7085a2013-07-18 15:15:21 -07001582 static const struct { const char before; const char after; } match[] = {
1583 {'/', '-'}, {';', '#'}, {' ', '#'}, {'$', '+'},
1584 {'(', '@'}, {')', '@'}, {'<', '='}, {'>', '='}
1585 };
buzbee1fd33462013-03-25 13:40:45 -07001586 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
1587 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
1588 }
1589}
1590
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001591std::string MIRGraph::GetSSAName(int ssa_reg) {
Ian Rogers39ebcb82013-05-30 16:57:23 -07001592 // TODO: This value is needed for LLVM and debugging. Currently, we compute this and then copy to
1593 // the arena. We should be smarter and just place straight into the arena, or compute the
1594 // value more lazily.
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001595 int vreg = SRegToVReg(ssa_reg);
1596 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1597 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1598 } else {
1599 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1600 }
buzbee1fd33462013-03-25 13:40:45 -07001601}
1602
1603// Similar to GetSSAName, but if ssa name represents an immediate show that as well.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001604std::string MIRGraph::GetSSANameWithConst(int ssa_reg, bool singles_only) {
buzbee1fd33462013-03-25 13:40:45 -07001605 if (reg_location_ == NULL) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001606 // Pre-SSA - just use the standard name.
buzbee1fd33462013-03-25 13:40:45 -07001607 return GetSSAName(ssa_reg);
1608 }
1609 if (IsConst(reg_location_[ssa_reg])) {
Mark Mendell9944b3b2014-10-06 10:58:54 -04001610 if (!singles_only && reg_location_[ssa_reg].wide &&
1611 !reg_location_[ssa_reg].high_word) {
Ian Rogers23b03b52014-01-24 11:10:03 -08001612 return StringPrintf("v%d_%d#0x%" PRIx64, SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001613 ConstantValueWide(reg_location_[ssa_reg]));
1614 } else {
Brian Carlstromb1eba212013-07-17 18:07:19 -07001615 return StringPrintf("v%d_%d#0x%x", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg),
buzbee1fd33462013-03-25 13:40:45 -07001616 ConstantValue(reg_location_[ssa_reg]));
1617 }
1618 } else {
Razvan A Lupusoru1500e6f2014-08-22 15:39:50 -07001619 int vreg = SRegToVReg(ssa_reg);
1620 if (vreg >= static_cast<int>(GetFirstTempVR())) {
1621 return StringPrintf("t%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1622 } else {
1623 return StringPrintf("v%d_%d", SRegToVReg(ssa_reg), GetSSASubscript(ssa_reg));
1624 }
buzbee1fd33462013-03-25 13:40:45 -07001625 }
1626}
1627
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001628void MIRGraph::GetBlockName(BasicBlock* bb, char* name) {
buzbee1fd33462013-03-25 13:40:45 -07001629 switch (bb->block_type) {
1630 case kEntryBlock:
1631 snprintf(name, BLOCK_NAME_LEN, "entry_%d", bb->id);
1632 break;
1633 case kExitBlock:
1634 snprintf(name, BLOCK_NAME_LEN, "exit_%d", bb->id);
1635 break;
1636 case kDalvikByteCode:
1637 snprintf(name, BLOCK_NAME_LEN, "block%04x_%d", bb->start_offset, bb->id);
1638 break;
1639 case kExceptionHandling:
1640 snprintf(name, BLOCK_NAME_LEN, "exception%04x_%d", bb->start_offset,
1641 bb->id);
1642 break;
1643 default:
1644 snprintf(name, BLOCK_NAME_LEN, "_%d", bb->id);
1645 break;
1646 }
1647}
1648
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001649const char* MIRGraph::GetShortyFromTargetIdx(int target_idx) {
buzbee0d829482013-10-11 15:24:55 -07001650 // TODO: for inlining support, use current code unit.
buzbee1fd33462013-03-25 13:40:45 -07001651 const DexFile::MethodId& method_id = cu_->dex_file->GetMethodId(target_idx);
1652 return cu_->dex_file->GetShorty(method_id.proto_idx_);
1653}
1654
Serguei Katkov717a3e42014-11-13 17:19:42 +06001655const char* MIRGraph::GetShortyFromMethodReference(const MethodReference& target_method) {
1656 const DexFile::MethodId& method_id =
1657 target_method.dex_file->GetMethodId(target_method.dex_method_index);
1658 return target_method.dex_file->GetShorty(method_id.proto_idx_);
1659}
1660
buzbee1fd33462013-03-25 13:40:45 -07001661/* Debug Utility - dump a compilation unit */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001662void MIRGraph::DumpMIRGraph() {
buzbee1fd33462013-03-25 13:40:45 -07001663 const char* block_type_names[] = {
buzbee17189ac2013-11-08 11:07:02 -08001664 "Null Block",
buzbee1fd33462013-03-25 13:40:45 -07001665 "Entry Block",
1666 "Code Block",
1667 "Exit Block",
1668 "Exception Handling",
1669 "Catch Block"
1670 };
1671
1672 LOG(INFO) << "Compiling " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -07001673 LOG(INFO) << GetInsns(0) << " insns";
buzbee1fd33462013-03-25 13:40:45 -07001674 LOG(INFO) << GetNumBlocks() << " blocks in total";
buzbee1fd33462013-03-25 13:40:45 -07001675
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001676 for (BasicBlock* bb : block_list_) {
buzbee1fd33462013-03-25 13:40:45 -07001677 LOG(INFO) << StringPrintf("Block %d (%s) (insn %04x - %04x%s)",
1678 bb->id,
1679 block_type_names[bb->block_type],
1680 bb->start_offset,
1681 bb->last_mir_insn ? bb->last_mir_insn->offset : bb->start_offset,
1682 bb->last_mir_insn ? "" : " empty");
buzbee0d829482013-10-11 15:24:55 -07001683 if (bb->taken != NullBasicBlockId) {
1684 LOG(INFO) << " Taken branch: block " << bb->taken
1685 << "(0x" << std::hex << GetBasicBlock(bb->taken)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001686 }
buzbee0d829482013-10-11 15:24:55 -07001687 if (bb->fall_through != NullBasicBlockId) {
1688 LOG(INFO) << " Fallthrough : block " << bb->fall_through
1689 << " (0x" << std::hex << GetBasicBlock(bb->fall_through)->start_offset << ")";
buzbee1fd33462013-03-25 13:40:45 -07001690 }
1691 }
1692}
1693
1694/*
1695 * Build an array of location records for the incoming arguments.
1696 * Note: one location record per word of arguments, with dummy
1697 * high-word loc for wide arguments. Also pull up any following
1698 * MOVE_RESULT and incorporate it into the invoke.
1699 */
1700CallInfo* MIRGraph::NewMemCallInfo(BasicBlock* bb, MIR* mir, InvokeType type,
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001701 bool is_range) {
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -07001702 CallInfo* info = static_cast<CallInfo*>(arena_->Alloc(sizeof(CallInfo),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001703 kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001704 MIR* move_result_mir = FindMoveResult(bb, mir);
1705 if (move_result_mir == NULL) {
1706 info->result.location = kLocInvalid;
1707 } else {
1708 info->result = GetRawDest(move_result_mir);
buzbee1fd33462013-03-25 13:40:45 -07001709 move_result_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1710 }
1711 info->num_arg_words = mir->ssa_rep->num_uses;
1712 info->args = (info->num_arg_words == 0) ? NULL : static_cast<RegLocation*>
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001713 (arena_->Alloc(sizeof(RegLocation) * info->num_arg_words, kArenaAllocMisc));
buzbee1fd33462013-03-25 13:40:45 -07001714 for (int i = 0; i < info->num_arg_words; i++) {
1715 info->args[i] = GetRawSrc(mir, i);
1716 }
1717 info->opt_flags = mir->optimization_flags;
1718 info->type = type;
1719 info->is_range = is_range;
1720 info->index = mir->dalvikInsn.vB;
1721 info->offset = mir->offset;
Vladimir Markof096aad2014-01-23 15:51:58 +00001722 info->mir = mir;
buzbee1fd33462013-03-25 13:40:45 -07001723 return info;
1724}
1725
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07001726// Allocate a new MIR.
1727MIR* MIRGraph::NewMIR() {
1728 MIR* mir = new (arena_) MIR();
1729 return mir;
1730}
1731
buzbee862a7602013-04-05 10:58:54 -07001732// Allocate a new basic block.
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001733BasicBlock* MIRGraph::NewMemBB(BBType block_type, int block_id) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001734 BasicBlock* bb = new (arena_) BasicBlock(block_id, block_type, arena_);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001735
buzbee862a7602013-04-05 10:58:54 -07001736 // TUNING: better estimate of the exit block predecessors?
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001737 bb->predecessors.reserve((block_type == kExitBlock) ? 2048 : 2);
buzbee862a7602013-04-05 10:58:54 -07001738 block_id_map_.Put(block_id, block_id);
1739 return bb;
1740}
buzbee1fd33462013-03-25 13:40:45 -07001741
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001742void MIRGraph::InitializeConstantPropagation() {
1743 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001744 constant_values_ = static_cast<int*>(arena_->Alloc(sizeof(int) * GetNumSSARegs(), kArenaAllocDFInfo));
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001745}
1746
1747void MIRGraph::InitializeMethodUses() {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07001748 // The gate starts by initializing the use counts.
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001749 int num_ssa_regs = GetNumSSARegs();
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001750 use_counts_.clear();
1751 use_counts_.reserve(num_ssa_regs + 32);
1752 use_counts_.resize(num_ssa_regs, 0u);
1753 raw_use_counts_.clear();
1754 raw_use_counts_.reserve(num_ssa_regs + 32);
1755 raw_use_counts_.resize(num_ssa_regs, 0u);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001756}
1757
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001758void MIRGraph::SSATransformationStart() {
1759 DCHECK(temp_scoped_alloc_.get() == nullptr);
1760 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001761 temp_.ssa.num_vregs = GetNumOfCodeAndTempVRs();
1762 temp_.ssa.work_live_vregs = new (temp_scoped_alloc_.get()) ArenaBitVector(
1763 temp_scoped_alloc_.get(), temp_.ssa.num_vregs, false, kBitMapRegisterV);
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001764}
1765
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001766void MIRGraph::SSATransformationEnd() {
1767 // Verify the dataflow information after the pass.
1768 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
1769 VerifyDataflow();
1770 }
1771
Vladimir Markof585e542014-11-21 13:41:32 +00001772 temp_.ssa.num_vregs = 0u;
1773 temp_.ssa.work_live_vregs = nullptr;
1774 temp_.ssa.def_block_matrix = nullptr;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001775 DCHECK(temp_scoped_alloc_.get() != nullptr);
1776 temp_scoped_alloc_.reset();
Johnny Qiuc029c982014-06-04 07:23:49 +00001777
1778 // Update the maximum number of reachable blocks.
1779 max_num_reachable_blocks_ = num_reachable_blocks_;
Vladimir Markoffda4992014-12-18 17:05:58 +00001780
1781 // Mark MIR SSA representations as up to date.
1782 mir_ssa_rep_up_to_date_ = true;
Vladimir Markoa5b8fde2014-05-23 15:16:44 +01001783}
1784
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001785size_t MIRGraph::GetNumDalvikInsns() const {
1786 size_t cumulative_size = 0u;
1787 bool counted_current_item = false;
1788 const uint8_t size_for_null_code_item = 2u;
1789
1790 for (auto it : m_units_) {
1791 const DexFile::CodeItem* code_item = it->GetCodeItem();
1792 // Even if the code item is null, we still count non-zero value so that
1793 // each m_unit is counted as having impact.
1794 cumulative_size += (code_item == nullptr ?
1795 size_for_null_code_item : code_item->insns_size_in_code_units_);
1796 if (code_item == current_code_item_) {
1797 counted_current_item = true;
1798 }
1799 }
1800
1801 // If the current code item was not counted yet, count it now.
1802 // This can happen for example in unit tests where some fields like m_units_
1803 // are not initialized.
1804 if (counted_current_item == false) {
1805 cumulative_size += (current_code_item_ == nullptr ?
1806 size_for_null_code_item : current_code_item_->insns_size_in_code_units_);
1807 }
1808
1809 return cumulative_size;
1810}
1811
Vladimir Marko55fff042014-07-10 12:42:52 +01001812static BasicBlock* SelectTopologicalSortOrderFallBack(
1813 MIRGraph* mir_graph, const ArenaBitVector* current_loop,
1814 const ScopedArenaVector<size_t>* visited_cnt_values, ScopedArenaAllocator* allocator,
1815 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1816 // No true loop head has been found but there may be true loop heads after the mess we need
1817 // to resolve. To avoid taking one of those, pick the candidate with the highest number of
1818 // reachable unvisited nodes. That candidate will surely be a part of a loop.
1819 BasicBlock* fall_back = nullptr;
1820 size_t fall_back_num_reachable = 0u;
1821 // Reuse the same bit vector for each candidate to mark reachable unvisited blocks.
1822 ArenaBitVector candidate_reachable(allocator, mir_graph->GetNumBlocks(), false, kBitMapMisc);
1823 AllNodesIterator iter(mir_graph);
1824 for (BasicBlock* candidate = iter.Next(); candidate != nullptr; candidate = iter.Next()) {
1825 if (candidate->hidden || // Hidden, or
1826 candidate->visited || // already processed, or
1827 (*visited_cnt_values)[candidate->id] == 0u || // no processed predecessors, or
1828 (current_loop != nullptr && // outside current loop.
1829 !current_loop->IsBitSet(candidate->id))) {
1830 continue;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001831 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001832 DCHECK(tmp_stack->empty());
1833 tmp_stack->push_back(candidate->id);
1834 candidate_reachable.ClearAllBits();
1835 size_t num_reachable = 0u;
1836 while (!tmp_stack->empty()) {
1837 BasicBlockId current_id = tmp_stack->back();
1838 tmp_stack->pop_back();
1839 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1840 DCHECK(current_bb != nullptr);
1841 ChildBlockIterator child_iter(current_bb, mir_graph);
1842 BasicBlock* child_bb = child_iter.Next();
1843 for ( ; child_bb != nullptr; child_bb = child_iter.Next()) {
1844 DCHECK(!child_bb->hidden);
1845 if (child_bb->visited || // Already processed, or
1846 (current_loop != nullptr && // outside current loop.
1847 !current_loop->IsBitSet(child_bb->id))) {
1848 continue;
1849 }
1850 if (!candidate_reachable.IsBitSet(child_bb->id)) {
1851 candidate_reachable.SetBit(child_bb->id);
1852 tmp_stack->push_back(child_bb->id);
1853 num_reachable += 1u;
1854 }
1855 }
1856 }
1857 if (fall_back_num_reachable < num_reachable) {
1858 fall_back_num_reachable = num_reachable;
1859 fall_back = candidate;
1860 }
1861 }
1862 return fall_back;
1863}
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001864
Vladimir Marko55fff042014-07-10 12:42:52 +01001865// Compute from which unvisited blocks is bb_id reachable through unvisited blocks.
1866static void ComputeUnvisitedReachableFrom(MIRGraph* mir_graph, BasicBlockId bb_id,
1867 ArenaBitVector* reachable,
1868 ScopedArenaVector<BasicBlockId>* tmp_stack) {
1869 // NOTE: Loop heads indicated by the "visited" flag.
1870 DCHECK(tmp_stack->empty());
1871 reachable->ClearAllBits();
1872 tmp_stack->push_back(bb_id);
1873 while (!tmp_stack->empty()) {
1874 BasicBlockId current_id = tmp_stack->back();
1875 tmp_stack->pop_back();
1876 BasicBlock* current_bb = mir_graph->GetBasicBlock(current_id);
1877 DCHECK(current_bb != nullptr);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001878 for (BasicBlockId pred_id : current_bb->predecessors) {
1879 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
1880 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001881 if (!pred_bb->visited && !reachable->IsBitSet(pred_bb->id)) {
1882 reachable->SetBit(pred_bb->id);
1883 tmp_stack->push_back(pred_bb->id);
1884 }
1885 }
1886 }
1887}
1888
1889void MIRGraph::ComputeTopologicalSortOrder() {
1890 ScopedArenaAllocator allocator(&cu_->arena_stack);
1891 unsigned int num_blocks = GetNumBlocks();
1892
1893 ScopedArenaQueue<BasicBlock*> q(allocator.Adapter());
1894 ScopedArenaVector<size_t> visited_cnt_values(num_blocks, 0u, allocator.Adapter());
1895 ScopedArenaVector<BasicBlockId> loop_head_stack(allocator.Adapter());
1896 size_t max_nested_loops = 0u;
1897 ArenaBitVector loop_exit_blocks(&allocator, num_blocks, false, kBitMapMisc);
1898 loop_exit_blocks.ClearAllBits();
1899
1900 // Count the number of blocks to process and add the entry block(s).
Vladimir Marko55fff042014-07-10 12:42:52 +01001901 unsigned int num_blocks_to_process = 0u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001902 for (BasicBlock* bb : block_list_) {
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001903 if (bb->hidden == true) {
1904 continue;
1905 }
1906
Vladimir Marko55fff042014-07-10 12:42:52 +01001907 num_blocks_to_process += 1u;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001908
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001909 if (bb->predecessors.size() == 0u) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001910 // Add entry block to the queue.
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07001911 q.push(bb);
1912 }
1913 }
1914
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001915 // Clear the topological order arrays.
1916 topological_order_.clear();
1917 topological_order_.reserve(num_blocks);
1918 topological_order_loop_ends_.clear();
1919 topological_order_loop_ends_.resize(num_blocks, 0u);
1920 topological_order_indexes_.clear();
1921 topological_order_indexes_.resize(num_blocks, static_cast<uint16_t>(-1));
Vladimir Marko55fff042014-07-10 12:42:52 +01001922
1923 // Mark all blocks as unvisited.
1924 ClearAllVisitedFlags();
1925
1926 // For loop heads, keep track from which blocks they are reachable not going through other
1927 // loop heads. Other loop heads are excluded to detect the heads of nested loops. The children
1928 // in this set go into the loop body, the other children are jumping over the loop.
1929 ScopedArenaVector<ArenaBitVector*> loop_head_reachable_from(allocator.Adapter());
1930 loop_head_reachable_from.resize(num_blocks, nullptr);
1931 // Reuse the same temp stack whenever calculating a loop_head_reachable_from[loop_head_id].
1932 ScopedArenaVector<BasicBlockId> tmp_stack(allocator.Adapter());
1933
1934 while (num_blocks_to_process != 0u) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001935 BasicBlock* bb = nullptr;
1936 if (!q.empty()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001937 num_blocks_to_process -= 1u;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001938 // Get top.
1939 bb = q.front();
1940 q.pop();
Vladimir Marko55fff042014-07-10 12:42:52 +01001941 if (bb->visited) {
1942 // Loop head: it was already processed, mark end and copy exit blocks to the queue.
1943 DCHECK(q.empty()) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001944 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
1945 topological_order_loop_ends_[topological_order_indexes_[bb->id]] = idx;
Vladimir Marko55fff042014-07-10 12:42:52 +01001946 DCHECK_EQ(loop_head_stack.back(), bb->id);
1947 loop_head_stack.pop_back();
1948 ArenaBitVector* reachable =
1949 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1950 for (BasicBlockId candidate_id : loop_exit_blocks.Indexes()) {
1951 if (reachable == nullptr || reachable->IsBitSet(candidate_id)) {
1952 q.push(GetBasicBlock(candidate_id));
1953 // NOTE: The BitVectorSet::IndexIterator will not check the pointed-to bit again,
1954 // so clearing the bit has no effect on the iterator.
1955 loop_exit_blocks.ClearBit(candidate_id);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001956 }
1957 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001958 continue;
Vladimir Marko622bdbe2014-06-19 14:59:05 +01001959 }
Vladimir Marko55fff042014-07-10 12:42:52 +01001960 } else {
1961 // Find the new loop head.
1962 AllNodesIterator iter(this);
1963 while (true) {
1964 BasicBlock* candidate = iter.Next();
1965 if (candidate == nullptr) {
1966 // We did not find a true loop head, fall back to a reachable block in any loop.
1967 ArenaBitVector* current_loop =
1968 loop_head_stack.empty() ? nullptr : loop_head_reachable_from[loop_head_stack.back()];
1969 bb = SelectTopologicalSortOrderFallBack(this, current_loop, &visited_cnt_values,
1970 &allocator, &tmp_stack);
1971 DCHECK(bb != nullptr) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1972 if (kIsDebugBuild && cu_->dex_file != nullptr) {
1973 LOG(INFO) << "Topological sort order: Using fall-back in "
1974 << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " BB #" << bb->id
1975 << " @0x" << std::hex << bb->start_offset
1976 << ", num_blocks = " << std::dec << num_blocks;
1977 }
1978 break;
1979 }
1980 if (candidate->hidden || // Hidden, or
1981 candidate->visited || // already processed, or
1982 visited_cnt_values[candidate->id] == 0u || // no processed predecessors, or
1983 (!loop_head_stack.empty() && // outside current loop.
1984 !loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(candidate->id))) {
1985 continue;
1986 }
1987
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001988 for (BasicBlockId pred_id : candidate->predecessors) {
1989 BasicBlock* pred_bb = GetBasicBlock(pred_id);
1990 DCHECK(pred_bb != nullptr);
Vladimir Marko55fff042014-07-10 12:42:52 +01001991 if (pred_bb != candidate && !pred_bb->visited &&
1992 !pred_bb->dominators->IsBitSet(candidate->id)) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001993 candidate = nullptr; // Set candidate to null to indicate failure.
1994 break;
Vladimir Marko55fff042014-07-10 12:42:52 +01001995 }
1996 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001997 if (candidate != nullptr) {
Vladimir Marko55fff042014-07-10 12:42:52 +01001998 bb = candidate;
1999 break;
2000 }
2001 }
2002 // Compute blocks from which the loop head is reachable and process those blocks first.
2003 ArenaBitVector* reachable =
2004 new (&allocator) ArenaBitVector(&allocator, num_blocks, false, kBitMapMisc);
2005 loop_head_reachable_from[bb->id] = reachable;
2006 ComputeUnvisitedReachableFrom(this, bb->id, reachable, &tmp_stack);
2007 // Now mark as loop head. (Even if it's only a fall back when we don't find a true loop.)
2008 loop_head_stack.push_back(bb->id);
2009 max_nested_loops = std::max(max_nested_loops, loop_head_stack.size());
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002010 }
2011
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002012 DCHECK_EQ(bb->hidden, false);
2013 DCHECK_EQ(bb->visited, false);
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002014 bb->visited = true;
Vladimir Marko8b858e12014-11-27 14:52:37 +00002015 bb->nesting_depth = loop_head_stack.size();
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002016
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002017 // Now add the basic block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002018 uint16_t idx = static_cast<uint16_t>(topological_order_.size());
2019 topological_order_indexes_[bb->id] = idx;
2020 topological_order_.push_back(bb->id);
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002021
Vladimir Marko55fff042014-07-10 12:42:52 +01002022 // Update visited_cnt_values for children.
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002023 ChildBlockIterator succIter(bb, this);
2024 BasicBlock* successor = succIter.Next();
2025 for ( ; successor != nullptr; successor = succIter.Next()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002026 if (successor->hidden) {
Vladimir Marko622bdbe2014-06-19 14:59:05 +01002027 continue;
2028 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002029
Vladimir Marko55fff042014-07-10 12:42:52 +01002030 // One more predecessor was visited.
2031 visited_cnt_values[successor->id] += 1u;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002032 if (visited_cnt_values[successor->id] == successor->predecessors.size()) {
Vladimir Marko55fff042014-07-10 12:42:52 +01002033 if (loop_head_stack.empty() ||
2034 loop_head_reachable_from[loop_head_stack.back()]->IsBitSet(successor->id)) {
2035 q.push(successor);
2036 } else {
2037 DCHECK(!loop_exit_blocks.IsBitSet(successor->id));
2038 loop_exit_blocks.SetBit(successor->id);
2039 }
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002040 }
2041 }
2042 }
Vladimir Marko55fff042014-07-10 12:42:52 +01002043
2044 // Prepare the loop head stack for iteration.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002045 topological_order_loop_head_stack_.clear();
2046 topological_order_loop_head_stack_.reserve(max_nested_loops);
Vladimir Marko415ac882014-09-30 18:09:14 +01002047 max_nested_loops_ = max_nested_loops;
Vladimir Markoffda4992014-12-18 17:05:58 +00002048 topological_order_up_to_date_ = true;
Jean Christophe Beyler44e5bde2014-04-29 14:40:41 -07002049}
2050
2051bool BasicBlock::IsExceptionBlock() const {
2052 if (block_type == kExceptionHandling) {
2053 return true;
2054 }
2055 return false;
2056}
2057
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002058ChildBlockIterator::ChildBlockIterator(BasicBlock* bb, MIRGraph* mir_graph)
2059 : basic_block_(bb), mir_graph_(mir_graph), visited_fallthrough_(false),
2060 visited_taken_(false), have_successors_(false) {
2061 // Check if we actually do have successors.
2062 if (basic_block_ != 0 && basic_block_->successor_block_list_type != kNotUsed) {
2063 have_successors_ = true;
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002064 successor_iter_ = basic_block_->successor_blocks.cbegin();
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002065 }
2066}
2067
2068BasicBlock* ChildBlockIterator::Next() {
2069 // We check if we have a basic block. If we don't we cannot get next child.
2070 if (basic_block_ == nullptr) {
2071 return nullptr;
2072 }
2073
2074 // If we haven't visited fallthrough, return that.
2075 if (visited_fallthrough_ == false) {
2076 visited_fallthrough_ = true;
2077
2078 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->fall_through);
2079 if (result != nullptr) {
2080 return result;
2081 }
2082 }
2083
2084 // If we haven't visited taken, return that.
2085 if (visited_taken_ == false) {
2086 visited_taken_ = true;
2087
2088 BasicBlock* result = mir_graph_->GetBasicBlock(basic_block_->taken);
2089 if (result != nullptr) {
2090 return result;
2091 }
2092 }
2093
2094 // We visited both taken and fallthrough. Now check if we have successors we need to visit.
2095 if (have_successors_ == true) {
2096 // Get information about next successor block.
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002097 auto end = basic_block_->successor_blocks.cend();
2098 while (successor_iter_ != end) {
2099 SuccessorBlockInfo* successor_block_info = *successor_iter_;
2100 ++successor_iter_;
Niranjan Kumar989367a2014-06-12 12:15:48 -07002101 // If block was replaced by zero block, take next one.
2102 if (successor_block_info->block != NullBasicBlockId) {
2103 return mir_graph_->GetBasicBlock(successor_block_info->block);
2104 }
Jean Christophe Beylerf8c762b2014-05-02 12:54:37 -07002105 }
2106 }
2107
2108 // We do not have anything.
2109 return nullptr;
2110}
2111
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002112BasicBlock* BasicBlock::Copy(CompilationUnit* c_unit) {
2113 MIRGraph* mir_graph = c_unit->mir_graph.get();
2114 return Copy(mir_graph);
2115}
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002116
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002117BasicBlock* BasicBlock::Copy(MIRGraph* mir_graph) {
2118 BasicBlock* result_bb = mir_graph->CreateNewBB(block_type);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002119
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002120 // We don't do a memcpy style copy here because it would lead to a lot of things
2121 // to clean up. Let us do it by hand instead.
2122 // Copy in taken and fallthrough.
2123 result_bb->fall_through = fall_through;
2124 result_bb->taken = taken;
2125
2126 // Copy successor links if needed.
2127 ArenaAllocator* arena = mir_graph->GetArena();
2128
2129 result_bb->successor_block_list_type = successor_block_list_type;
2130 if (result_bb->successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002131 result_bb->successor_blocks.reserve(successor_blocks.size());
2132 for (SuccessorBlockInfo* sbi_old : successor_blocks) {
2133 SuccessorBlockInfo* sbi_new = static_cast<SuccessorBlockInfo*>(
2134 arena->Alloc(sizeof(SuccessorBlockInfo), kArenaAllocSuccessor));
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002135 memcpy(sbi_new, sbi_old, sizeof(SuccessorBlockInfo));
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002136 result_bb->successor_blocks.push_back(sbi_new);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002137 }
2138 }
2139
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002140 // Copy offset, method.
2141 result_bb->start_offset = start_offset;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002142
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002143 // Now copy instructions.
2144 for (MIR* mir = first_mir_insn; mir != 0; mir = mir->next) {
2145 // Get a copy first.
2146 MIR* copy = mir->Copy(mir_graph);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002147
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002148 // Append it.
2149 result_bb->AppendMIR(copy);
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002150 }
2151
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002152 return result_bb;
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002153}
2154
2155MIR* MIR::Copy(MIRGraph* mir_graph) {
2156 MIR* res = mir_graph->NewMIR();
2157 *res = *this;
2158
2159 // Remove links
2160 res->next = nullptr;
2161 res->bb = NullBasicBlockId;
2162 res->ssa_rep = nullptr;
2163
2164 return res;
2165}
2166
2167MIR* MIR::Copy(CompilationUnit* c_unit) {
2168 return Copy(c_unit->mir_graph.get());
2169}
2170
2171uint32_t SSARepresentation::GetStartUseIndex(Instruction::Code opcode) {
2172 // Default result.
2173 int res = 0;
2174
2175 // We are basically setting the iputs to their igets counterparts.
2176 switch (opcode) {
2177 case Instruction::IPUT:
2178 case Instruction::IPUT_OBJECT:
2179 case Instruction::IPUT_BOOLEAN:
2180 case Instruction::IPUT_BYTE:
2181 case Instruction::IPUT_CHAR:
2182 case Instruction::IPUT_SHORT:
2183 case Instruction::IPUT_QUICK:
2184 case Instruction::IPUT_OBJECT_QUICK:
Fred Shih37f05ef2014-07-16 18:38:08 -07002185 case Instruction::IPUT_BOOLEAN_QUICK:
2186 case Instruction::IPUT_BYTE_QUICK:
2187 case Instruction::IPUT_CHAR_QUICK:
2188 case Instruction::IPUT_SHORT_QUICK:
Jean Christophe Beyler3aa57732014-04-17 12:47:24 -07002189 case Instruction::APUT:
2190 case Instruction::APUT_OBJECT:
2191 case Instruction::APUT_BOOLEAN:
2192 case Instruction::APUT_BYTE:
2193 case Instruction::APUT_CHAR:
2194 case Instruction::APUT_SHORT:
2195 case Instruction::SPUT:
2196 case Instruction::SPUT_OBJECT:
2197 case Instruction::SPUT_BOOLEAN:
2198 case Instruction::SPUT_BYTE:
2199 case Instruction::SPUT_CHAR:
2200 case Instruction::SPUT_SHORT:
2201 // Skip the VR containing what to store.
2202 res = 1;
2203 break;
2204 case Instruction::IPUT_WIDE:
2205 case Instruction::IPUT_WIDE_QUICK:
2206 case Instruction::APUT_WIDE:
2207 case Instruction::SPUT_WIDE:
2208 // Skip the two VRs containing what to store.
2209 res = 2;
2210 break;
2211 default:
2212 // Do nothing in the general case.
2213 break;
2214 }
2215
2216 return res;
2217}
2218
Jean Christophe Beylerc3db20b2014-05-05 21:09:40 -07002219/**
2220 * @brief Given a decoded instruction, it checks whether the instruction
2221 * sets a constant and if it does, more information is provided about the
2222 * constant being set.
2223 * @param ptr_value pointer to a 64-bit holder for the constant.
2224 * @param wide Updated by function whether a wide constant is being set by bytecode.
2225 * @return Returns false if the decoded instruction does not represent a constant bytecode.
2226 */
2227bool MIR::DecodedInstruction::GetConstant(int64_t* ptr_value, bool* wide) const {
2228 bool sets_const = true;
2229 int64_t value = vB;
2230
2231 DCHECK(ptr_value != nullptr);
2232 DCHECK(wide != nullptr);
2233
2234 switch (opcode) {
2235 case Instruction::CONST_4:
2236 case Instruction::CONST_16:
2237 case Instruction::CONST:
2238 *wide = false;
2239 value <<= 32; // In order to get the sign extend.
2240 value >>= 32;
2241 break;
2242 case Instruction::CONST_HIGH16:
2243 *wide = false;
2244 value <<= 48; // In order to get the sign extend.
2245 value >>= 32;
2246 break;
2247 case Instruction::CONST_WIDE_16:
2248 case Instruction::CONST_WIDE_32:
2249 *wide = true;
2250 value <<= 32; // In order to get the sign extend.
2251 value >>= 32;
2252 break;
2253 case Instruction::CONST_WIDE:
2254 *wide = true;
2255 value = vB_wide;
2256 break;
2257 case Instruction::CONST_WIDE_HIGH16:
2258 *wide = true;
2259 value <<= 48; // In order to get the sign extend.
2260 break;
2261 default:
2262 sets_const = false;
2263 break;
2264 }
2265
2266 if (sets_const) {
2267 *ptr_value = value;
2268 }
2269
2270 return sets_const;
2271}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002272
2273void BasicBlock::ResetOptimizationFlags(uint16_t reset_flags) {
2274 // Reset flags for all MIRs in bb.
2275 for (MIR* mir = first_mir_insn; mir != NULL; mir = mir->next) {
2276 mir->optimization_flags &= (~reset_flags);
2277 }
2278}
2279
Vladimir Markocb873d82014-12-08 15:16:54 +00002280void BasicBlock::Kill(MIRGraph* mir_graph) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002281 for (BasicBlockId pred_id : predecessors) {
2282 BasicBlock* pred_bb = mir_graph->GetBasicBlock(pred_id);
2283 DCHECK(pred_bb != nullptr);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002284
2285 // Sadly we have to go through the children by hand here.
2286 pred_bb->ReplaceChild(id, NullBasicBlockId);
2287 }
Vladimir Markocb873d82014-12-08 15:16:54 +00002288 predecessors.clear();
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002289
Vladimir Marko312eb252014-10-07 15:01:57 +01002290 // Mark as dead and hidden.
2291 block_type = kDead;
2292 hidden = true;
2293
2294 // Detach it from its MIRs so we don't generate code for them. Also detached MIRs
2295 // are updated to know that they no longer have a parent.
2296 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2297 mir->bb = NullBasicBlockId;
2298 }
2299 first_mir_insn = nullptr;
2300 last_mir_insn = nullptr;
2301
2302 data_flow_info = nullptr;
2303
2304 // Erase this bb from all children's predecessors and kill unreachable children.
2305 ChildBlockIterator iter(this, mir_graph);
2306 for (BasicBlock* succ_bb = iter.Next(); succ_bb != nullptr; succ_bb = iter.Next()) {
2307 succ_bb->ErasePredecessor(id);
Vladimir Marko312eb252014-10-07 15:01:57 +01002308 }
2309
2310 // Remove links to children.
2311 fall_through = NullBasicBlockId;
2312 taken = NullBasicBlockId;
2313 successor_block_list_type = kNotUsed;
2314
2315 if (kIsDebugBuild) {
2316 if (catch_entry) {
2317 DCHECK_EQ(mir_graph->catches_.count(start_offset), 1u);
2318 mir_graph->catches_.erase(start_offset);
2319 }
2320 }
2321}
2322
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002323bool BasicBlock::IsSSALiveOut(const CompilationUnit* c_unit, int ssa_reg) {
2324 // In order to determine if the ssa reg is live out, we scan all the MIRs. We remember
2325 // the last SSA number of the same dalvik register. At the end, if it is different than ssa_reg,
2326 // then it is not live out of this BB.
2327 int dalvik_reg = c_unit->mir_graph->SRegToVReg(ssa_reg);
2328
2329 int last_ssa_reg = -1;
2330
2331 // Walk through the MIRs backwards.
2332 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2333 // Get ssa rep.
2334 SSARepresentation *ssa_rep = mir->ssa_rep;
2335
2336 // Go through the defines for this MIR.
2337 for (int i = 0; i < ssa_rep->num_defs; i++) {
2338 DCHECK(ssa_rep->defs != nullptr);
2339
2340 // Get the ssa reg.
2341 int def_ssa_reg = ssa_rep->defs[i];
2342
2343 // Get dalvik reg.
2344 int def_dalvik_reg = c_unit->mir_graph->SRegToVReg(def_ssa_reg);
2345
2346 // Compare dalvik regs.
2347 if (dalvik_reg == def_dalvik_reg) {
2348 // We found a def of the register that we are being asked about.
2349 // Remember it.
2350 last_ssa_reg = def_ssa_reg;
2351 }
2352 }
2353 }
2354
2355 if (last_ssa_reg == -1) {
2356 // If we get to this point we couldn't find a define of register user asked about.
2357 // Let's assume the user knows what he's doing so we can be safe and say that if we
2358 // couldn't find a def, it is live out.
2359 return true;
2360 }
2361
2362 // If it is not -1, we found a match, is it ssa_reg?
2363 return (ssa_reg == last_ssa_reg);
2364}
2365
2366bool BasicBlock::ReplaceChild(BasicBlockId old_bb, BasicBlockId new_bb) {
2367 // We need to check taken, fall_through, and successor_blocks to replace.
2368 bool found = false;
2369 if (taken == old_bb) {
2370 taken = new_bb;
2371 found = true;
2372 }
2373
2374 if (fall_through == old_bb) {
2375 fall_through = new_bb;
2376 found = true;
2377 }
2378
2379 if (successor_block_list_type != kNotUsed) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002380 for (SuccessorBlockInfo* successor_block_info : successor_blocks) {
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002381 if (successor_block_info->block == old_bb) {
2382 successor_block_info->block = new_bb;
2383 found = true;
2384 }
2385 }
2386 }
2387
2388 return found;
2389}
2390
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002391void BasicBlock::ErasePredecessor(BasicBlockId old_pred) {
2392 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
2393 DCHECK(pos != predecessors.end());
Vladimir Marko312eb252014-10-07 15:01:57 +01002394 // It's faster to move the back() to *pos than erase(pos).
2395 *pos = predecessors.back();
2396 predecessors.pop_back();
2397 size_t idx = std::distance(predecessors.begin(), pos);
2398 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2399 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2400 break;
2401 }
2402 DCHECK_EQ(mir->ssa_rep->num_uses - 1u, predecessors.size());
2403 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2404 mir->meta.phi_incoming[idx] = mir->meta.phi_incoming[predecessors.size()];
2405 mir->ssa_rep->uses[idx] = mir->ssa_rep->uses[predecessors.size()];
2406 mir->ssa_rep->num_uses = predecessors.size();
2407 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002408}
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002409
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002410void BasicBlock::UpdatePredecessor(BasicBlockId old_pred, BasicBlockId new_pred) {
2411 DCHECK_NE(new_pred, NullBasicBlockId);
2412 auto pos = std::find(predecessors.begin(), predecessors.end(), old_pred);
Vladimir Marko312eb252014-10-07 15:01:57 +01002413 DCHECK(pos != predecessors.end());
2414 *pos = new_pred;
2415 size_t idx = std::distance(predecessors.begin(), pos);
2416 for (MIR* mir = first_mir_insn; mir != nullptr; mir = mir->next) {
2417 if (static_cast<int>(mir->dalvikInsn.opcode) != kMirOpPhi) {
2418 break;
2419 }
2420 DCHECK_EQ(mir->meta.phi_incoming[idx], old_pred);
2421 mir->meta.phi_incoming[idx] = new_pred;
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002422 }
2423}
2424
2425// Create a new basic block with block_id as num_blocks_ that is
2426// post-incremented.
2427BasicBlock* MIRGraph::CreateNewBB(BBType block_type) {
Vladimir Markoffda4992014-12-18 17:05:58 +00002428 BasicBlockId id = static_cast<BasicBlockId>(block_list_.size());
2429 BasicBlock* res = NewMemBB(block_type, id);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01002430 block_list_.push_back(res);
Jean Christophe Beyler85127582014-05-11 23:36:41 -07002431 return res;
2432}
2433
Jean Christophe Beyler2469e602014-05-06 20:36:55 -07002434void MIRGraph::CalculateBasicBlockInformation() {
2435 PassDriverMEPostOpt driver(cu_);
2436 driver.Launch();
2437}
2438
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002439int MIR::DecodedInstruction::FlagsOf() const {
2440 // Calculate new index.
2441 int idx = static_cast<int>(opcode) - kNumPackedOpcodes;
2442
2443 // Check if it is an extended or not.
2444 if (idx < 0) {
2445 return Instruction::FlagsOf(opcode);
2446 }
2447
2448 // For extended, we use a switch.
2449 switch (static_cast<int>(opcode)) {
2450 case kMirOpPhi:
2451 return Instruction::kContinue;
2452 case kMirOpCopy:
2453 return Instruction::kContinue;
2454 case kMirOpFusedCmplFloat:
2455 return Instruction::kContinue | Instruction::kBranch;
2456 case kMirOpFusedCmpgFloat:
2457 return Instruction::kContinue | Instruction::kBranch;
2458 case kMirOpFusedCmplDouble:
2459 return Instruction::kContinue | Instruction::kBranch;
2460 case kMirOpFusedCmpgDouble:
2461 return Instruction::kContinue | Instruction::kBranch;
2462 case kMirOpFusedCmpLong:
2463 return Instruction::kContinue | Instruction::kBranch;
2464 case kMirOpNop:
2465 return Instruction::kContinue;
2466 case kMirOpNullCheck:
2467 return Instruction::kContinue | Instruction::kThrow;
2468 case kMirOpRangeCheck:
2469 return Instruction::kContinue | Instruction::kThrow;
2470 case kMirOpDivZeroCheck:
2471 return Instruction::kContinue | Instruction::kThrow;
2472 case kMirOpCheck:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002473 return Instruction::kContinue | Instruction::kThrow;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002474 case kMirOpCheckPart2:
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002475 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002476 case kMirOpSelect:
2477 return Instruction::kContinue;
2478 case kMirOpConstVector:
2479 return Instruction::kContinue;
2480 case kMirOpMoveVector:
2481 return Instruction::kContinue;
2482 case kMirOpPackedMultiply:
2483 return Instruction::kContinue;
2484 case kMirOpPackedAddition:
2485 return Instruction::kContinue;
2486 case kMirOpPackedSubtract:
2487 return Instruction::kContinue;
2488 case kMirOpPackedShiftLeft:
2489 return Instruction::kContinue;
2490 case kMirOpPackedSignedShiftRight:
2491 return Instruction::kContinue;
2492 case kMirOpPackedUnsignedShiftRight:
2493 return Instruction::kContinue;
2494 case kMirOpPackedAnd:
2495 return Instruction::kContinue;
2496 case kMirOpPackedOr:
2497 return Instruction::kContinue;
2498 case kMirOpPackedXor:
2499 return Instruction::kContinue;
2500 case kMirOpPackedAddReduce:
2501 return Instruction::kContinue;
2502 case kMirOpPackedReduce:
2503 return Instruction::kContinue;
2504 case kMirOpPackedSet:
2505 return Instruction::kContinue;
2506 case kMirOpReserveVectorRegisters:
2507 return Instruction::kContinue;
2508 case kMirOpReturnVectorRegisters:
2509 return Instruction::kContinue;
Udayan Banerjib7fc6292014-09-09 16:49:34 -07002510 case kMirOpMemBarrier:
2511 return Instruction::kContinue;
2512 case kMirOpPackedArrayGet:
2513 return Instruction::kContinue | Instruction::kThrow;
2514 case kMirOpPackedArrayPut:
2515 return Instruction::kContinue | Instruction::kThrow;
Ningsheng Jiana262f772014-11-25 16:48:07 +08002516 case kMirOpMaddInt:
2517 case kMirOpMsubInt:
2518 case kMirOpMaddLong:
2519 case kMirOpMsubLong:
2520 return Instruction::kContinue;
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07002521 default:
2522 LOG(WARNING) << "ExtendedFlagsOf: Unhandled case: " << static_cast<int> (opcode);
2523 return 0;
2524 }
2525}
Andreas Gampe0b9203e2015-01-22 20:39:27 -08002526
2527const uint16_t* MIRGraph::GetInsns(int m_unit_index) const {
2528 return m_units_[m_unit_index]->GetCodeItem()->insns_;
2529}
2530
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002531} // namespace art