blob: 6658848570261a47f7e00076b249ffea75fcf01a [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2011 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
Ian Rogerse77493c2014-08-20 15:08:45 -070017#include "base/bit_vector-inl.h"
buzbee311ca162013-02-28 15:56:43 -080018#include "compiler_internals.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010019#include "global_value_numbering.h"
buzbee311ca162013-02-28 15:56:43 -080020#include "local_value_numbering.h"
Ian Rogers8d3a1172013-06-04 01:13:28 -070021#include "dataflow_iterator-inl.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010022#include "dex/global_value_numbering.h"
Vladimir Marko9820b7c2014-01-02 16:40:37 +000023#include "dex/quick/dex_file_method_inliner.h"
24#include "dex/quick/dex_file_to_method_inliner_map.h"
Vladimir Marko69f08ba2014-04-11 12:28:11 +010025#include "utils/scoped_arena_containers.h"
buzbee311ca162013-02-28 15:56:43 -080026
27namespace art {
28
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070029static unsigned int Predecessors(BasicBlock* bb) {
buzbee862a7602013-04-05 10:58:54 -070030 return bb->predecessors->Size();
buzbee311ca162013-02-28 15:56:43 -080031}
32
33/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070034void MIRGraph::SetConstant(int32_t ssa_reg, int value) {
buzbee862a7602013-04-05 10:58:54 -070035 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080036 constant_values_[ssa_reg] = value;
37}
38
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070039void MIRGraph::SetConstantWide(int ssa_reg, int64_t value) {
buzbee862a7602013-04-05 10:58:54 -070040 is_constant_v_->SetBit(ssa_reg);
Serguei Katkov597da1f2014-07-15 17:25:46 +070041 is_constant_v_->SetBit(ssa_reg + 1);
buzbee311ca162013-02-28 15:56:43 -080042 constant_values_[ssa_reg] = Low32Bits(value);
43 constant_values_[ssa_reg + 1] = High32Bits(value);
44}
45
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -080046void MIRGraph::DoConstantPropagation(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -080047 MIR* mir;
buzbee311ca162013-02-28 15:56:43 -080048
49 for (mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070050 // Skip pass if BB has MIR without SSA representation.
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070051 if (mir->ssa_rep == nullptr) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070052 return;
53 }
54
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070055 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -080056
Ian Rogers29a26482014-05-02 15:27:29 -070057 MIR::DecodedInstruction* d_insn = &mir->dalvikInsn;
buzbee311ca162013-02-28 15:56:43 -080058
59 if (!(df_attributes & DF_HAS_DEFS)) continue;
60
61 /* Handle instructions that set up constants directly */
62 if (df_attributes & DF_SETS_CONST) {
63 if (df_attributes & DF_DA) {
64 int32_t vB = static_cast<int32_t>(d_insn->vB);
65 switch (d_insn->opcode) {
66 case Instruction::CONST_4:
67 case Instruction::CONST_16:
68 case Instruction::CONST:
69 SetConstant(mir->ssa_rep->defs[0], vB);
70 break;
71 case Instruction::CONST_HIGH16:
72 SetConstant(mir->ssa_rep->defs[0], vB << 16);
73 break;
74 case Instruction::CONST_WIDE_16:
75 case Instruction::CONST_WIDE_32:
76 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
77 break;
78 case Instruction::CONST_WIDE:
Brian Carlstromb1eba212013-07-17 18:07:19 -070079 SetConstantWide(mir->ssa_rep->defs[0], d_insn->vB_wide);
buzbee311ca162013-02-28 15:56:43 -080080 break;
81 case Instruction::CONST_WIDE_HIGH16:
82 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
83 break;
84 default:
85 break;
86 }
87 }
88 /* Handle instructions that set up constants directly */
89 } else if (df_attributes & DF_IS_MOVE) {
90 int i;
91
92 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
buzbee862a7602013-04-05 10:58:54 -070093 if (!is_constant_v_->IsBitSet(mir->ssa_rep->uses[i])) break;
buzbee311ca162013-02-28 15:56:43 -080094 }
95 /* Move a register holding a constant to another register */
96 if (i == mir->ssa_rep->num_uses) {
97 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
98 if (df_attributes & DF_A_WIDE) {
99 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
100 }
101 }
102 }
103 }
104 /* TODO: implement code to handle arithmetic operations */
buzbee311ca162013-02-28 15:56:43 -0800105}
106
buzbee311ca162013-02-28 15:56:43 -0800107/* Advance to next strictly dominated MIR node in an extended basic block */
buzbee0d829482013-10-11 15:24:55 -0700108MIR* MIRGraph::AdvanceMIR(BasicBlock** p_bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800109 BasicBlock* bb = *p_bb;
110 if (mir != NULL) {
111 mir = mir->next;
112 if (mir == NULL) {
buzbee0d829482013-10-11 15:24:55 -0700113 bb = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800114 if ((bb == NULL) || Predecessors(bb) != 1) {
115 mir = NULL;
116 } else {
117 *p_bb = bb;
118 mir = bb->first_mir_insn;
119 }
120 }
121 }
122 return mir;
123}
124
125/*
126 * To be used at an invoke mir. If the logically next mir node represents
127 * a move-result, return it. Else, return NULL. If a move-result exists,
128 * it is required to immediately follow the invoke with no intervening
129 * opcodes or incoming arcs. However, if the result of the invoke is not
130 * used, a move-result may not be present.
131 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700132MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800133 BasicBlock* tbb = bb;
134 mir = AdvanceMIR(&tbb, mir);
135 while (mir != NULL) {
buzbee311ca162013-02-28 15:56:43 -0800136 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
137 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
138 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
139 break;
140 }
141 // Keep going if pseudo op, otherwise terminate
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700142 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee311ca162013-02-28 15:56:43 -0800143 mir = AdvanceMIR(&tbb, mir);
buzbee35ba7f32014-05-31 08:59:01 -0700144 } else {
145 mir = NULL;
buzbee311ca162013-02-28 15:56:43 -0800146 }
147 }
148 return mir;
149}
150
buzbee0d829482013-10-11 15:24:55 -0700151BasicBlock* MIRGraph::NextDominatedBlock(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800152 if (bb->block_type == kDead) {
153 return NULL;
154 }
155 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
156 || (bb->block_type == kExitBlock));
buzbee0d829482013-10-11 15:24:55 -0700157 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
158 BasicBlock* bb_fall_through = GetBasicBlock(bb->fall_through);
buzbee1da1e2f2013-11-15 13:37:01 -0800159 if (((bb_fall_through == NULL) && (bb_taken != NULL)) &&
buzbee0d829482013-10-11 15:24:55 -0700160 ((bb_taken->block_type == kDalvikByteCode) || (bb_taken->block_type == kExitBlock))) {
buzbeecbcfaf32013-08-19 07:37:40 -0700161 // Follow simple unconditional branches.
buzbee0d829482013-10-11 15:24:55 -0700162 bb = bb_taken;
buzbeecbcfaf32013-08-19 07:37:40 -0700163 } else {
164 // Follow simple fallthrough
buzbee0d829482013-10-11 15:24:55 -0700165 bb = (bb_taken != NULL) ? NULL : bb_fall_through;
buzbeecbcfaf32013-08-19 07:37:40 -0700166 }
buzbee311ca162013-02-28 15:56:43 -0800167 if (bb == NULL || (Predecessors(bb) != 1)) {
168 return NULL;
169 }
170 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
171 return bb;
172}
173
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700174static MIR* FindPhi(BasicBlock* bb, int ssa_name) {
buzbee311ca162013-02-28 15:56:43 -0800175 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
176 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
177 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
178 if (mir->ssa_rep->uses[i] == ssa_name) {
179 return mir;
180 }
181 }
182 }
183 }
184 return NULL;
185}
186
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700187static SelectInstructionKind SelectKind(MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800188 switch (mir->dalvikInsn.opcode) {
189 case Instruction::MOVE:
190 case Instruction::MOVE_OBJECT:
191 case Instruction::MOVE_16:
192 case Instruction::MOVE_OBJECT_16:
193 case Instruction::MOVE_FROM16:
194 case Instruction::MOVE_OBJECT_FROM16:
195 return kSelectMove;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700196 case Instruction::CONST:
197 case Instruction::CONST_4:
198 case Instruction::CONST_16:
buzbee311ca162013-02-28 15:56:43 -0800199 return kSelectConst;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700200 case Instruction::GOTO:
201 case Instruction::GOTO_16:
202 case Instruction::GOTO_32:
buzbee311ca162013-02-28 15:56:43 -0800203 return kSelectGoto;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700204 default:
205 return kSelectNone;
buzbee311ca162013-02-28 15:56:43 -0800206 }
buzbee311ca162013-02-28 15:56:43 -0800207}
208
Vladimir Markoa1a70742014-03-03 10:28:05 +0000209static constexpr ConditionCode kIfCcZConditionCodes[] = {
210 kCondEq, kCondNe, kCondLt, kCondGe, kCondGt, kCondLe
211};
212
213COMPILE_ASSERT(arraysize(kIfCcZConditionCodes) == Instruction::IF_LEZ - Instruction::IF_EQZ + 1,
214 if_ccz_ccodes_size1);
215
216static constexpr bool IsInstructionIfCcZ(Instruction::Code opcode) {
217 return Instruction::IF_EQZ <= opcode && opcode <= Instruction::IF_LEZ;
218}
219
220static constexpr ConditionCode ConditionCodeForIfCcZ(Instruction::Code opcode) {
221 return kIfCcZConditionCodes[opcode - Instruction::IF_EQZ];
222}
223
224COMPILE_ASSERT(ConditionCodeForIfCcZ(Instruction::IF_EQZ) == kCondEq, check_if_eqz_ccode);
225COMPILE_ASSERT(ConditionCodeForIfCcZ(Instruction::IF_NEZ) == kCondNe, check_if_nez_ccode);
226COMPILE_ASSERT(ConditionCodeForIfCcZ(Instruction::IF_LTZ) == kCondLt, check_if_ltz_ccode);
227COMPILE_ASSERT(ConditionCodeForIfCcZ(Instruction::IF_GEZ) == kCondGe, check_if_gez_ccode);
228COMPILE_ASSERT(ConditionCodeForIfCcZ(Instruction::IF_GTZ) == kCondGt, check_if_gtz_ccode);
229COMPILE_ASSERT(ConditionCodeForIfCcZ(Instruction::IF_LEZ) == kCondLe, check_if_lez_ccode);
230
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700231int MIRGraph::GetSSAUseCount(int s_reg) {
buzbee862a7602013-04-05 10:58:54 -0700232 return raw_use_counts_.Get(s_reg);
buzbee311ca162013-02-28 15:56:43 -0800233}
234
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800235size_t MIRGraph::GetNumAvailableNonSpecialCompilerTemps() {
236 if (num_non_special_compiler_temps_ >= max_available_non_special_compiler_temps_) {
237 return 0;
238 } else {
239 return max_available_non_special_compiler_temps_ - num_non_special_compiler_temps_;
240 }
241}
242
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000243
244// FIXME - will probably need to revisit all uses of this, as type not defined.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800245static const RegLocation temp_loc = {kLocCompilerTemp,
buzbee091cc402014-03-31 10:14:40 -0700246 0, 1 /*defined*/, 0, 0, 0, 0, 0, 1 /*home*/,
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000247 RegStorage(), INVALID_SREG, INVALID_SREG};
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800248
249CompilerTemp* MIRGraph::GetNewCompilerTemp(CompilerTempType ct_type, bool wide) {
250 // There is a limit to the number of non-special temps so check to make sure it wasn't exceeded.
251 if (ct_type == kCompilerTempVR) {
252 size_t available_temps = GetNumAvailableNonSpecialCompilerTemps();
253 if (available_temps <= 0 || (available_temps <= 1 && wide)) {
254 return 0;
255 }
256 }
257
258 CompilerTemp *compiler_temp = static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000259 kArenaAllocRegAlloc));
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800260
261 // Create the type of temp requested. Special temps need special handling because
262 // they have a specific virtual register assignment.
263 if (ct_type == kCompilerTempSpecialMethodPtr) {
264 DCHECK_EQ(wide, false);
265 compiler_temp->v_reg = static_cast<int>(kVRegMethodPtrBaseReg);
266 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
267
268 // The MIR graph keeps track of the sreg for method pointer specially, so record that now.
269 method_sreg_ = compiler_temp->s_reg_low;
270 } else {
271 DCHECK_EQ(ct_type, kCompilerTempVR);
272
273 // The new non-special compiler temp must receive a unique v_reg with a negative value.
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700274 compiler_temp->v_reg = static_cast<int>(kVRegNonSpecialTempBaseReg) -
275 num_non_special_compiler_temps_;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800276 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
277 num_non_special_compiler_temps_++;
278
279 if (wide) {
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700280 // Create a new CompilerTemp for the high part.
281 CompilerTemp *compiler_temp_high =
282 static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp), kArenaAllocRegAlloc));
283 compiler_temp_high->v_reg = compiler_temp->v_reg;
284 compiler_temp_high->s_reg_low = compiler_temp->s_reg_low;
285 compiler_temps_.Insert(compiler_temp_high);
286
287 // Ensure that the two registers are consecutive. Since the virtual registers used for temps
288 // grow in a negative fashion, we need the smaller to refer to the low part. Thus, we
289 // redefine the v_reg and s_reg_low.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800290 compiler_temp->v_reg--;
291 int ssa_reg_high = compiler_temp->s_reg_low;
292 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
293 int ssa_reg_low = compiler_temp->s_reg_low;
294
295 // If needed initialize the register location for the high part.
296 // The low part is handled later in this method on a common path.
297 if (reg_location_ != nullptr) {
298 reg_location_[ssa_reg_high] = temp_loc;
299 reg_location_[ssa_reg_high].high_word = 1;
300 reg_location_[ssa_reg_high].s_reg_low = ssa_reg_low;
301 reg_location_[ssa_reg_high].wide = true;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800302 }
303
304 num_non_special_compiler_temps_++;
305 }
306 }
307
308 // Have we already allocated the register locations?
309 if (reg_location_ != nullptr) {
310 int ssa_reg_low = compiler_temp->s_reg_low;
311 reg_location_[ssa_reg_low] = temp_loc;
312 reg_location_[ssa_reg_low].s_reg_low = ssa_reg_low;
313 reg_location_[ssa_reg_low].wide = wide;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800314 }
315
316 compiler_temps_.Insert(compiler_temp);
317 return compiler_temp;
318}
buzbee311ca162013-02-28 15:56:43 -0800319
320/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700321bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800322 if (bb->block_type == kDead) {
323 return true;
324 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100325 // Don't do a separate LVN if we did the GVN.
Vladimir Marko55fff042014-07-10 12:42:52 +0100326 bool use_lvn = bb->use_lvn && (cu_->disable_opt & (1u << kGlobalValueNumbering)) != 0u;
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100327 std::unique_ptr<ScopedArenaAllocator> allocator;
Vladimir Marko95a05972014-05-30 10:01:32 +0100328 std::unique_ptr<GlobalValueNumbering> global_valnum;
Ian Rogers700a4022014-05-19 16:49:03 -0700329 std::unique_ptr<LocalValueNumbering> local_valnum;
buzbee1da1e2f2013-11-15 13:37:01 -0800330 if (use_lvn) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100331 allocator.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko95a05972014-05-30 10:01:32 +0100332 global_valnum.reset(new (allocator.get()) GlobalValueNumbering(cu_, allocator.get()));
Vladimir Markob19955d2014-07-29 12:04:10 +0100333 local_valnum.reset(new (allocator.get()) LocalValueNumbering(global_valnum.get(), bb->id,
334 allocator.get()));
buzbee1da1e2f2013-11-15 13:37:01 -0800335 }
buzbee311ca162013-02-28 15:56:43 -0800336 while (bb != NULL) {
337 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
338 // TUNING: use the returned value number for CSE.
buzbee1da1e2f2013-11-15 13:37:01 -0800339 if (use_lvn) {
340 local_valnum->GetValueNumber(mir);
341 }
buzbee311ca162013-02-28 15:56:43 -0800342 // Look for interesting opcodes, skip otherwise
343 Instruction::Code opcode = mir->dalvikInsn.opcode;
344 switch (opcode) {
345 case Instruction::CMPL_FLOAT:
346 case Instruction::CMPL_DOUBLE:
347 case Instruction::CMPG_FLOAT:
348 case Instruction::CMPG_DOUBLE:
349 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700350 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800351 // Bitcode doesn't allow this optimization.
352 break;
353 }
354 if (mir->next != NULL) {
355 MIR* mir_next = mir->next;
buzbee311ca162013-02-28 15:56:43 -0800356 // Make sure result of cmp is used by next insn and nowhere else
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700357 if (IsInstructionIfCcZ(mir_next->dalvikInsn.opcode) &&
buzbee311ca162013-02-28 15:56:43 -0800358 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
359 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
Vladimir Markoa1a70742014-03-03 10:28:05 +0000360 mir_next->meta.ccode = ConditionCodeForIfCcZ(mir_next->dalvikInsn.opcode);
Brian Carlstromdf629502013-07-17 22:39:56 -0700361 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800362 case Instruction::CMPL_FLOAT:
363 mir_next->dalvikInsn.opcode =
364 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
365 break;
366 case Instruction::CMPL_DOUBLE:
367 mir_next->dalvikInsn.opcode =
368 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
369 break;
370 case Instruction::CMPG_FLOAT:
371 mir_next->dalvikInsn.opcode =
372 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
373 break;
374 case Instruction::CMPG_DOUBLE:
375 mir_next->dalvikInsn.opcode =
376 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
377 break;
378 case Instruction::CMP_LONG:
379 mir_next->dalvikInsn.opcode =
380 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
381 break;
382 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
383 }
384 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700385 // Copy the SSA information that is relevant.
buzbee311ca162013-02-28 15:56:43 -0800386 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
387 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
388 mir_next->ssa_rep->fp_use = mir->ssa_rep->fp_use;
389 mir_next->ssa_rep->num_defs = 0;
390 mir->ssa_rep->num_uses = 0;
391 mir->ssa_rep->num_defs = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700392 // Copy in the decoded instruction information for potential SSA re-creation.
393 mir_next->dalvikInsn.vA = mir->dalvikInsn.vB;
394 mir_next->dalvikInsn.vB = mir->dalvikInsn.vC;
buzbee311ca162013-02-28 15:56:43 -0800395 }
396 }
397 break;
398 case Instruction::GOTO:
399 case Instruction::GOTO_16:
400 case Instruction::GOTO_32:
401 case Instruction::IF_EQ:
402 case Instruction::IF_NE:
403 case Instruction::IF_LT:
404 case Instruction::IF_GE:
405 case Instruction::IF_GT:
406 case Instruction::IF_LE:
407 case Instruction::IF_EQZ:
408 case Instruction::IF_NEZ:
409 case Instruction::IF_LTZ:
410 case Instruction::IF_GEZ:
411 case Instruction::IF_GTZ:
412 case Instruction::IF_LEZ:
buzbeecbcfaf32013-08-19 07:37:40 -0700413 // If we've got a backwards branch to return, no need to suspend check.
buzbee0d829482013-10-11 15:24:55 -0700414 if ((IsBackedge(bb, bb->taken) && GetBasicBlock(bb->taken)->dominates_return) ||
415 (IsBackedge(bb, bb->fall_through) &&
416 GetBasicBlock(bb->fall_through)->dominates_return)) {
buzbee311ca162013-02-28 15:56:43 -0800417 mir->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
418 if (cu_->verbose) {
buzbee0d829482013-10-11 15:24:55 -0700419 LOG(INFO) << "Suppressed suspend check on branch to return at 0x" << std::hex
420 << mir->offset;
buzbee311ca162013-02-28 15:56:43 -0800421 }
422 }
423 break;
424 default:
425 break;
426 }
427 // Is this the select pattern?
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800428 // TODO: flesh out support for Mips. NOTE: llvm's select op doesn't quite work here.
buzbee311ca162013-02-28 15:56:43 -0800429 // TUNING: expand to support IF_xx compare & branches
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000430 if (!cu_->compiler->IsPortable() &&
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100431 (cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2 ||
432 cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) &&
Vladimir Markoa1a70742014-03-03 10:28:05 +0000433 IsInstructionIfCcZ(mir->dalvikInsn.opcode)) {
buzbee0d829482013-10-11 15:24:55 -0700434 BasicBlock* ft = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800435 DCHECK(ft != NULL);
buzbee0d829482013-10-11 15:24:55 -0700436 BasicBlock* ft_ft = GetBasicBlock(ft->fall_through);
437 BasicBlock* ft_tk = GetBasicBlock(ft->taken);
buzbee311ca162013-02-28 15:56:43 -0800438
buzbee0d829482013-10-11 15:24:55 -0700439 BasicBlock* tk = GetBasicBlock(bb->taken);
buzbee311ca162013-02-28 15:56:43 -0800440 DCHECK(tk != NULL);
buzbee0d829482013-10-11 15:24:55 -0700441 BasicBlock* tk_ft = GetBasicBlock(tk->fall_through);
442 BasicBlock* tk_tk = GetBasicBlock(tk->taken);
buzbee311ca162013-02-28 15:56:43 -0800443
444 /*
445 * In the select pattern, the taken edge goes to a block that unconditionally
446 * transfers to the rejoin block and the fall_though edge goes to a block that
447 * unconditionally falls through to the rejoin block.
448 */
449 if ((tk_ft == NULL) && (ft_tk == NULL) && (tk_tk == ft_ft) &&
450 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
451 /*
452 * Okay - we have the basic diamond shape. At the very least, we can eliminate the
453 * suspend check on the taken-taken branch back to the join point.
454 */
455 if (SelectKind(tk->last_mir_insn) == kSelectGoto) {
456 tk->last_mir_insn->optimization_flags |= (MIR_IGNORE_SUSPEND_CHECK);
457 }
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100458
459 // TODO: Add logic for LONG.
buzbee311ca162013-02-28 15:56:43 -0800460 // Are the block bodies something we can handle?
461 if ((ft->first_mir_insn == ft->last_mir_insn) &&
462 (tk->first_mir_insn != tk->last_mir_insn) &&
463 (tk->first_mir_insn->next == tk->last_mir_insn) &&
464 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
465 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
466 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
467 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
468 // Almost there. Are the instructions targeting the same vreg?
469 MIR* if_true = tk->first_mir_insn;
470 MIR* if_false = ft->first_mir_insn;
471 // It's possible that the target of the select isn't used - skip those (rare) cases.
472 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
473 if ((phi != NULL) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
474 /*
475 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
476 * Phi node in the merge block and delete it (while using the SSA name
477 * of the merge as the target of the SELECT. Delete both taken and
478 * fallthrough blocks, and set fallthrough to merge block.
479 * NOTE: not updating other dataflow info (no longer used at this point).
480 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
481 */
Vladimir Markoa1a70742014-03-03 10:28:05 +0000482 mir->meta.ccode = ConditionCodeForIfCcZ(mir->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800483 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
484 bool const_form = (SelectKind(if_true) == kSelectConst);
485 if ((SelectKind(if_true) == kSelectMove)) {
486 if (IsConst(if_true->ssa_rep->uses[0]) &&
487 IsConst(if_false->ssa_rep->uses[0])) {
488 const_form = true;
489 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
490 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
491 }
492 }
493 if (const_form) {
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800494 /*
495 * TODO: If both constants are the same value, then instead of generating
496 * a select, we should simply generate a const bytecode. This should be
497 * considered after inlining which can lead to CFG of this form.
498 */
buzbee311ca162013-02-28 15:56:43 -0800499 // "true" set val in vB
500 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
501 // "false" set val in vC
502 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
503 } else {
504 DCHECK_EQ(SelectKind(if_true), kSelectMove);
505 DCHECK_EQ(SelectKind(if_false), kSelectMove);
buzbee862a7602013-04-05 10:58:54 -0700506 int* src_ssa =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000507 static_cast<int*>(arena_->Alloc(sizeof(int) * 3, kArenaAllocDFInfo));
buzbee311ca162013-02-28 15:56:43 -0800508 src_ssa[0] = mir->ssa_rep->uses[0];
509 src_ssa[1] = if_true->ssa_rep->uses[0];
510 src_ssa[2] = if_false->ssa_rep->uses[0];
511 mir->ssa_rep->uses = src_ssa;
512 mir->ssa_rep->num_uses = 3;
513 }
514 mir->ssa_rep->num_defs = 1;
buzbee862a7602013-04-05 10:58:54 -0700515 mir->ssa_rep->defs =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000516 static_cast<int*>(arena_->Alloc(sizeof(int) * 1, kArenaAllocDFInfo));
buzbee862a7602013-04-05 10:58:54 -0700517 mir->ssa_rep->fp_def =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000518 static_cast<bool*>(arena_->Alloc(sizeof(bool) * 1, kArenaAllocDFInfo));
buzbee311ca162013-02-28 15:56:43 -0800519 mir->ssa_rep->fp_def[0] = if_true->ssa_rep->fp_def[0];
buzbee817e45a2013-05-30 18:59:12 -0700520 // Match type of uses to def.
521 mir->ssa_rep->fp_use =
Mathieu Chartierf6c4b3b2013-08-24 16:11:37 -0700522 static_cast<bool*>(arena_->Alloc(sizeof(bool) * mir->ssa_rep->num_uses,
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000523 kArenaAllocDFInfo));
buzbee817e45a2013-05-30 18:59:12 -0700524 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
525 mir->ssa_rep->fp_use[i] = mir->ssa_rep->fp_def[0];
526 }
buzbee311ca162013-02-28 15:56:43 -0800527 /*
528 * There is usually a Phi node in the join block for our two cases. If the
529 * Phi node only contains our two cases as input, we will use the result
530 * SSA name of the Phi node as our select result and delete the Phi. If
531 * the Phi node has more than two operands, we will arbitrarily use the SSA
532 * name of the "true" path, delete the SSA name of the "false" path from the
533 * Phi node (and fix up the incoming arc list).
534 */
535 if (phi->ssa_rep->num_uses == 2) {
536 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
537 phi->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
538 } else {
539 int dead_def = if_false->ssa_rep->defs[0];
540 int live_def = if_true->ssa_rep->defs[0];
541 mir->ssa_rep->defs[0] = live_def;
buzbee0d829482013-10-11 15:24:55 -0700542 BasicBlockId* incoming = phi->meta.phi_incoming;
buzbee311ca162013-02-28 15:56:43 -0800543 for (int i = 0; i < phi->ssa_rep->num_uses; i++) {
544 if (phi->ssa_rep->uses[i] == live_def) {
545 incoming[i] = bb->id;
546 }
547 }
548 for (int i = 0; i < phi->ssa_rep->num_uses; i++) {
549 if (phi->ssa_rep->uses[i] == dead_def) {
550 int last_slot = phi->ssa_rep->num_uses - 1;
551 phi->ssa_rep->uses[i] = phi->ssa_rep->uses[last_slot];
552 incoming[i] = incoming[last_slot];
553 }
554 }
555 }
556 phi->ssa_rep->num_uses--;
buzbee0d829482013-10-11 15:24:55 -0700557 bb->taken = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800558 tk->block_type = kDead;
559 for (MIR* tmir = ft->first_mir_insn; tmir != NULL; tmir = tmir->next) {
560 tmir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
561 }
562 }
563 }
564 }
565 }
566 }
buzbee1da1e2f2013-11-15 13:37:01 -0800567 bb = ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) ? NextDominatedBlock(bb) : NULL;
buzbee311ca162013-02-28 15:56:43 -0800568 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100569 if (use_lvn && UNLIKELY(!global_valnum->Good())) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100570 LOG(WARNING) << "LVN overflow in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
571 }
buzbee311ca162013-02-28 15:56:43 -0800572
buzbee311ca162013-02-28 15:56:43 -0800573 return true;
574}
575
buzbee311ca162013-02-28 15:56:43 -0800576/* Collect stats on number of checks removed */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700577void MIRGraph::CountChecks(struct BasicBlock* bb) {
buzbee862a7602013-04-05 10:58:54 -0700578 if (bb->data_flow_info != NULL) {
579 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
580 if (mir->ssa_rep == NULL) {
581 continue;
buzbee311ca162013-02-28 15:56:43 -0800582 }
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700583 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee862a7602013-04-05 10:58:54 -0700584 if (df_attributes & DF_HAS_NULL_CHKS) {
585 checkstats_->null_checks++;
586 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
587 checkstats_->null_checks_eliminated++;
588 }
589 }
590 if (df_attributes & DF_HAS_RANGE_CHKS) {
591 checkstats_->range_checks++;
592 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
593 checkstats_->range_checks_eliminated++;
594 }
buzbee311ca162013-02-28 15:56:43 -0800595 }
596 }
597 }
buzbee311ca162013-02-28 15:56:43 -0800598}
599
600/* Try to make common case the fallthrough path */
buzbee0d829482013-10-11 15:24:55 -0700601bool MIRGraph::LayoutBlocks(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800602 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback
603 if (!bb->explicit_throw) {
604 return false;
605 }
606 BasicBlock* walker = bb;
607 while (true) {
608 // Check termination conditions
609 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
610 break;
611 }
buzbee0d829482013-10-11 15:24:55 -0700612 BasicBlock* prev = GetBasicBlock(walker->predecessors->Get(0));
buzbee311ca162013-02-28 15:56:43 -0800613 if (prev->conditional_branch) {
buzbee0d829482013-10-11 15:24:55 -0700614 if (GetBasicBlock(prev->fall_through) == walker) {
buzbee311ca162013-02-28 15:56:43 -0800615 // Already done - return
616 break;
617 }
buzbee0d829482013-10-11 15:24:55 -0700618 DCHECK_EQ(walker, GetBasicBlock(prev->taken));
buzbee311ca162013-02-28 15:56:43 -0800619 // Got one. Flip it and exit
620 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
621 switch (opcode) {
622 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
623 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
624 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
625 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
626 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
627 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
628 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
629 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
630 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
631 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
632 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
633 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
634 default: LOG(FATAL) << "Unexpected opcode " << opcode;
635 }
636 prev->last_mir_insn->dalvikInsn.opcode = opcode;
buzbee0d829482013-10-11 15:24:55 -0700637 BasicBlockId t_bb = prev->taken;
buzbee311ca162013-02-28 15:56:43 -0800638 prev->taken = prev->fall_through;
639 prev->fall_through = t_bb;
640 break;
641 }
642 walker = prev;
643 }
644 return false;
645}
646
647/* Combine any basic blocks terminated by instructions that we now know can't throw */
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -0800648void MIRGraph::CombineBlocks(struct BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800649 // Loop here to allow combining a sequence of blocks
650 while (true) {
651 // Check termination conditions
652 if ((bb->first_mir_insn == NULL)
653 || (bb->data_flow_info == NULL)
654 || (bb->block_type == kExceptionHandling)
655 || (bb->block_type == kExitBlock)
656 || (bb->block_type == kDead)
buzbee0d829482013-10-11 15:24:55 -0700657 || (bb->taken == NullBasicBlockId)
658 || (GetBasicBlock(bb->taken)->block_type != kExceptionHandling)
659 || (bb->successor_block_list_type != kNotUsed)
buzbee311ca162013-02-28 15:56:43 -0800660 || (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) != kMirOpCheck)) {
661 break;
662 }
663
664 // Test the kMirOpCheck instruction
665 MIR* mir = bb->last_mir_insn;
666 // Grab the attributes from the paired opcode
667 MIR* throw_insn = mir->meta.throw_insn;
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700668 uint64_t df_attributes = GetDataFlowAttributes(throw_insn);
buzbee311ca162013-02-28 15:56:43 -0800669 bool can_combine = true;
670 if (df_attributes & DF_HAS_NULL_CHKS) {
671 can_combine &= ((throw_insn->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0);
672 }
673 if (df_attributes & DF_HAS_RANGE_CHKS) {
674 can_combine &= ((throw_insn->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0);
675 }
676 if (!can_combine) {
677 break;
678 }
679 // OK - got one. Combine
buzbee0d829482013-10-11 15:24:55 -0700680 BasicBlock* bb_next = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800681 DCHECK(!bb_next->catch_entry);
682 DCHECK_EQ(Predecessors(bb_next), 1U);
buzbee311ca162013-02-28 15:56:43 -0800683 // Overwrite the kOpCheck insn with the paired opcode
684 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
685 *bb->last_mir_insn = *throw_insn;
buzbee311ca162013-02-28 15:56:43 -0800686 // Use the successor info from the next block
buzbee0d829482013-10-11 15:24:55 -0700687 bb->successor_block_list_type = bb_next->successor_block_list_type;
688 bb->successor_blocks = bb_next->successor_blocks;
buzbee311ca162013-02-28 15:56:43 -0800689 // Use the ending block linkage from the next block
690 bb->fall_through = bb_next->fall_through;
buzbee0d829482013-10-11 15:24:55 -0700691 GetBasicBlock(bb->taken)->block_type = kDead; // Kill the unused exception block
buzbee311ca162013-02-28 15:56:43 -0800692 bb->taken = bb_next->taken;
693 // Include the rest of the instructions
694 bb->last_mir_insn = bb_next->last_mir_insn;
695 /*
Junmo Parkf1770fd2014-08-12 09:34:54 +0900696 * If lower-half of pair of blocks to combine contained
697 * a return or a conditional branch or an explicit throw,
698 * move the flag to the newly combined block.
buzbee311ca162013-02-28 15:56:43 -0800699 */
700 bb->terminated_by_return = bb_next->terminated_by_return;
Junmo Parkf1770fd2014-08-12 09:34:54 +0900701 bb->conditional_branch = bb_next->conditional_branch;
702 bb->explicit_throw = bb_next->explicit_throw;
buzbee311ca162013-02-28 15:56:43 -0800703
704 /*
705 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
706 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
707 */
708
709 // Kill bb_next and remap now-dead id to parent
710 bb_next->block_type = kDead;
buzbee1fd33462013-03-25 13:40:45 -0700711 block_id_map_.Overwrite(bb_next->id, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800712
713 // Now, loop back and see if we can keep going
714 }
buzbee311ca162013-02-28 15:56:43 -0800715}
716
Vladimir Markobfea9c22014-01-17 17:49:33 +0000717void MIRGraph::EliminateNullChecksAndInferTypesStart() {
718 if ((cu_->disable_opt & (1 << kNullCheckElimination)) == 0) {
719 if (kIsDebugBuild) {
720 AllNodesIterator iter(this);
721 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
722 CHECK(bb->data_flow_info == nullptr || bb->data_flow_info->ending_check_v == nullptr);
723 }
724 }
725
726 DCHECK(temp_scoped_alloc_.get() == nullptr);
727 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
728 temp_bit_vector_size_ = GetNumSSARegs();
729 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
730 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapTempSSARegisterV);
731 }
732}
733
buzbee1da1e2f2013-11-15 13:37:01 -0800734/*
735 * Eliminate unnecessary null checks for a basic block. Also, while we're doing
736 * an iterative walk go ahead and perform type and size inference.
737 */
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -0800738bool MIRGraph::EliminateNullChecksAndInferTypes(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800739 if (bb->data_flow_info == NULL) return false;
buzbee1da1e2f2013-11-15 13:37:01 -0800740 bool infer_changed = false;
741 bool do_nce = ((cu_->disable_opt & (1 << kNullCheckElimination)) == 0);
buzbee311ca162013-02-28 15:56:43 -0800742
Vladimir Markobfea9c22014-01-17 17:49:33 +0000743 ArenaBitVector* ssa_regs_to_check = temp_bit_vector_;
buzbee1da1e2f2013-11-15 13:37:01 -0800744 if (do_nce) {
745 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +0100746 * Set initial state. Catch blocks don't need any special treatment.
buzbee1da1e2f2013-11-15 13:37:01 -0800747 */
Vladimir Marko0a810d22014-07-11 14:44:36 +0100748 if (bb->block_type == kEntryBlock) {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000749 ssa_regs_to_check->ClearAllBits();
buzbee1da1e2f2013-11-15 13:37:01 -0800750 // Assume all ins are objects.
751 for (uint16_t in_reg = cu_->num_dalvik_registers - cu_->num_ins;
752 in_reg < cu_->num_dalvik_registers; in_reg++) {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000753 ssa_regs_to_check->SetBit(in_reg);
buzbee1da1e2f2013-11-15 13:37:01 -0800754 }
755 if ((cu_->access_flags & kAccStatic) == 0) {
756 // If non-static method, mark "this" as non-null
757 int this_reg = cu_->num_dalvik_registers - cu_->num_ins;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000758 ssa_regs_to_check->ClearBit(this_reg);
buzbee1da1e2f2013-11-15 13:37:01 -0800759 }
760 } else if (bb->predecessors->Size() == 1) {
761 BasicBlock* pred_bb = GetBasicBlock(bb->predecessors->Get(0));
Vladimir Markobfea9c22014-01-17 17:49:33 +0000762 // pred_bb must have already been processed at least once.
763 DCHECK(pred_bb->data_flow_info->ending_check_v != nullptr);
764 ssa_regs_to_check->Copy(pred_bb->data_flow_info->ending_check_v);
buzbee1da1e2f2013-11-15 13:37:01 -0800765 if (pred_bb->block_type == kDalvikByteCode) {
766 // Check to see if predecessor had an explicit null-check.
767 MIR* last_insn = pred_bb->last_mir_insn;
Jean Christophe Beylerb5c9b402014-04-30 14:52:00 -0700768 if (last_insn != nullptr) {
769 Instruction::Code last_opcode = last_insn->dalvikInsn.opcode;
770 if (last_opcode == Instruction::IF_EQZ) {
771 if (pred_bb->fall_through == bb->id) {
772 // The fall-through of a block following a IF_EQZ, set the vA of the IF_EQZ to show that
773 // it can't be null.
774 ssa_regs_to_check->ClearBit(last_insn->ssa_rep->uses[0]);
775 }
776 } else if (last_opcode == Instruction::IF_NEZ) {
777 if (pred_bb->taken == bb->id) {
778 // The taken block following a IF_NEZ, set the vA of the IF_NEZ to show that it can't be
779 // null.
780 ssa_regs_to_check->ClearBit(last_insn->ssa_rep->uses[0]);
781 }
buzbee1da1e2f2013-11-15 13:37:01 -0800782 }
Ian Rogers22fd6a02013-06-13 15:06:54 -0700783 }
784 }
buzbee1da1e2f2013-11-15 13:37:01 -0800785 } else {
786 // Starting state is union of all incoming arcs
787 GrowableArray<BasicBlockId>::Iterator iter(bb->predecessors);
788 BasicBlock* pred_bb = GetBasicBlock(iter.Next());
Vladimir Markobfea9c22014-01-17 17:49:33 +0000789 CHECK(pred_bb != NULL);
790 while (pred_bb->data_flow_info->ending_check_v == nullptr) {
791 pred_bb = GetBasicBlock(iter.Next());
792 // At least one predecessor must have been processed before this bb.
793 DCHECK(pred_bb != nullptr);
794 DCHECK(pred_bb->data_flow_info != nullptr);
795 }
796 ssa_regs_to_check->Copy(pred_bb->data_flow_info->ending_check_v);
buzbee1da1e2f2013-11-15 13:37:01 -0800797 while (true) {
798 pred_bb = GetBasicBlock(iter.Next());
799 if (!pred_bb) break;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000800 DCHECK(pred_bb->data_flow_info != nullptr);
801 if (pred_bb->data_flow_info->ending_check_v == nullptr) {
buzbee1da1e2f2013-11-15 13:37:01 -0800802 continue;
803 }
Vladimir Markobfea9c22014-01-17 17:49:33 +0000804 ssa_regs_to_check->Union(pred_bb->data_flow_info->ending_check_v);
buzbee311ca162013-02-28 15:56:43 -0800805 }
buzbee311ca162013-02-28 15:56:43 -0800806 }
Vladimir Markobfea9c22014-01-17 17:49:33 +0000807 // At this point, ssa_regs_to_check shows which sregs have an object definition with
buzbee1da1e2f2013-11-15 13:37:01 -0800808 // no intervening uses.
buzbee311ca162013-02-28 15:56:43 -0800809 }
810
811 // Walk through the instruction in the block, updating as necessary
812 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
813 if (mir->ssa_rep == NULL) {
814 continue;
815 }
buzbee1da1e2f2013-11-15 13:37:01 -0800816
817 // Propagate type info.
818 infer_changed = InferTypeAndSize(bb, mir, infer_changed);
819 if (!do_nce) {
820 continue;
821 }
822
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700823 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -0800824
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000825 // Might need a null check?
826 if (df_attributes & DF_HAS_NULL_CHKS) {
827 int src_idx;
828 if (df_attributes & DF_NULL_CHK_1) {
829 src_idx = 1;
830 } else if (df_attributes & DF_NULL_CHK_2) {
831 src_idx = 2;
832 } else {
833 src_idx = 0;
834 }
835 int src_sreg = mir->ssa_rep->uses[src_idx];
Vladimir Markobfea9c22014-01-17 17:49:33 +0000836 if (!ssa_regs_to_check->IsBitSet(src_sreg)) {
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000837 // Eliminate the null check.
838 mir->optimization_flags |= MIR_IGNORE_NULL_CHECK;
839 } else {
840 // Do the null check.
841 mir->optimization_flags &= ~MIR_IGNORE_NULL_CHECK;
842 // Mark s_reg as null-checked
Vladimir Markobfea9c22014-01-17 17:49:33 +0000843 ssa_regs_to_check->ClearBit(src_sreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000844 }
845 }
846
847 if ((df_attributes & DF_A_WIDE) ||
848 (df_attributes & (DF_REF_A | DF_SETS_CONST | DF_NULL_TRANSFER)) == 0) {
849 continue;
850 }
851
852 /*
853 * First, mark all object definitions as requiring null check.
854 * Note: we can't tell if a CONST definition might be used as an object, so treat
855 * them all as object definitions.
856 */
857 if (((df_attributes & (DF_DA | DF_REF_A)) == (DF_DA | DF_REF_A)) ||
858 (df_attributes & DF_SETS_CONST)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000859 ssa_regs_to_check->SetBit(mir->ssa_rep->defs[0]);
buzbee4db179d2013-10-23 12:16:39 -0700860 }
861
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000862 // Now, remove mark from all object definitions we know are non-null.
863 if (df_attributes & DF_NON_NULL_DST) {
864 // Mark target of NEW* as non-null
Vladimir Markobfea9c22014-01-17 17:49:33 +0000865 ssa_regs_to_check->ClearBit(mir->ssa_rep->defs[0]);
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000866 }
867
buzbee311ca162013-02-28 15:56:43 -0800868 // Mark non-null returns from invoke-style NEW*
869 if (df_attributes & DF_NON_NULL_RET) {
870 MIR* next_mir = mir->next;
871 // Next should be an MOVE_RESULT_OBJECT
872 if (next_mir &&
873 next_mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) {
874 // Mark as null checked
Vladimir Markobfea9c22014-01-17 17:49:33 +0000875 ssa_regs_to_check->ClearBit(next_mir->ssa_rep->defs[0]);
buzbee311ca162013-02-28 15:56:43 -0800876 } else {
877 if (next_mir) {
878 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
buzbee0d829482013-10-11 15:24:55 -0700879 } else if (bb->fall_through != NullBasicBlockId) {
buzbee311ca162013-02-28 15:56:43 -0800880 // Look in next basic block
buzbee0d829482013-10-11 15:24:55 -0700881 struct BasicBlock* next_bb = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800882 for (MIR* tmir = next_bb->first_mir_insn; tmir != NULL;
883 tmir =tmir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700884 if (MIR::DecodedInstruction::IsPseudoMirOp(tmir->dalvikInsn.opcode)) {
buzbee311ca162013-02-28 15:56:43 -0800885 continue;
886 }
887 // First non-pseudo should be MOVE_RESULT_OBJECT
888 if (tmir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) {
889 // Mark as null checked
Vladimir Markobfea9c22014-01-17 17:49:33 +0000890 ssa_regs_to_check->ClearBit(tmir->ssa_rep->defs[0]);
buzbee311ca162013-02-28 15:56:43 -0800891 } else {
892 LOG(WARNING) << "Unexpected op after new: " << tmir->dalvikInsn.opcode;
893 }
894 break;
895 }
896 }
897 }
898 }
899
900 /*
901 * Propagate nullcheck state on register copies (including
902 * Phi pseudo copies. For the latter, nullcheck state is
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000903 * the "or" of all the Phi's operands.
buzbee311ca162013-02-28 15:56:43 -0800904 */
905 if (df_attributes & (DF_NULL_TRANSFER_0 | DF_NULL_TRANSFER_N)) {
906 int tgt_sreg = mir->ssa_rep->defs[0];
907 int operands = (df_attributes & DF_NULL_TRANSFER_0) ? 1 :
908 mir->ssa_rep->num_uses;
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000909 bool needs_null_check = false;
buzbee311ca162013-02-28 15:56:43 -0800910 for (int i = 0; i < operands; i++) {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000911 needs_null_check |= ssa_regs_to_check->IsBitSet(mir->ssa_rep->uses[i]);
buzbee311ca162013-02-28 15:56:43 -0800912 }
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000913 if (needs_null_check) {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000914 ssa_regs_to_check->SetBit(tgt_sreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +0000915 } else {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000916 ssa_regs_to_check->ClearBit(tgt_sreg);
buzbee311ca162013-02-28 15:56:43 -0800917 }
918 }
buzbee311ca162013-02-28 15:56:43 -0800919 }
920
921 // Did anything change?
Vladimir Markobfea9c22014-01-17 17:49:33 +0000922 bool nce_changed = false;
923 if (do_nce) {
924 if (bb->data_flow_info->ending_check_v == nullptr) {
925 DCHECK(temp_scoped_alloc_.get() != nullptr);
926 bb->data_flow_info->ending_check_v = new (temp_scoped_alloc_.get()) ArenaBitVector(
927 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapNullCheck);
928 nce_changed = ssa_regs_to_check->GetHighestBitSet() != -1;
929 bb->data_flow_info->ending_check_v->Copy(ssa_regs_to_check);
Jean Christophe Beylerb5c9b402014-04-30 14:52:00 -0700930 } else if (!ssa_regs_to_check->SameBitsSet(bb->data_flow_info->ending_check_v)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +0000931 nce_changed = true;
932 bb->data_flow_info->ending_check_v->Copy(ssa_regs_to_check);
933 }
buzbee311ca162013-02-28 15:56:43 -0800934 }
buzbee1da1e2f2013-11-15 13:37:01 -0800935 return infer_changed | nce_changed;
buzbee311ca162013-02-28 15:56:43 -0800936}
937
Vladimir Markobfea9c22014-01-17 17:49:33 +0000938void MIRGraph::EliminateNullChecksAndInferTypesEnd() {
939 if ((cu_->disable_opt & (1 << kNullCheckElimination)) == 0) {
940 // Clean up temporaries.
941 temp_bit_vector_size_ = 0u;
942 temp_bit_vector_ = nullptr;
943 AllNodesIterator iter(this);
944 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
945 if (bb->data_flow_info != nullptr) {
946 bb->data_flow_info->ending_check_v = nullptr;
947 }
948 }
949 DCHECK(temp_scoped_alloc_.get() != nullptr);
950 temp_scoped_alloc_.reset();
951 }
952}
953
954bool MIRGraph::EliminateClassInitChecksGate() {
955 if ((cu_->disable_opt & (1 << kClassInitCheckElimination)) != 0 ||
956 !cu_->mir_graph->HasStaticFieldAccess()) {
957 return false;
958 }
959
960 if (kIsDebugBuild) {
961 AllNodesIterator iter(this);
962 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
963 CHECK(bb->data_flow_info == nullptr || bb->data_flow_info->ending_check_v == nullptr);
964 }
965 }
966
967 DCHECK(temp_scoped_alloc_.get() == nullptr);
968 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
969
970 // Each insn we use here has at least 2 code units, offset/2 will be a unique index.
971 const size_t end = (cu_->code_item->insns_size_in_code_units_ + 1u) / 2u;
972 temp_insn_data_ = static_cast<uint16_t*>(
973 temp_scoped_alloc_->Alloc(end * sizeof(*temp_insn_data_), kArenaAllocGrowableArray));
974
975 uint32_t unique_class_count = 0u;
976 {
977 // Get unique_class_count and store indexes in temp_insn_data_ using a map on a nested
978 // ScopedArenaAllocator.
979
980 // Embed the map value in the entry to save space.
981 struct MapEntry {
982 // Map key: the class identified by the declaring dex file and type index.
983 const DexFile* declaring_dex_file;
984 uint16_t declaring_class_idx;
985 // Map value: index into bit vectors of classes requiring initialization checks.
986 uint16_t index;
987 };
988 struct MapEntryComparator {
989 bool operator()(const MapEntry& lhs, const MapEntry& rhs) const {
990 if (lhs.declaring_class_idx != rhs.declaring_class_idx) {
991 return lhs.declaring_class_idx < rhs.declaring_class_idx;
992 }
993 return lhs.declaring_dex_file < rhs.declaring_dex_file;
994 }
995 };
996
Vladimir Markobfea9c22014-01-17 17:49:33 +0000997 ScopedArenaAllocator allocator(&cu_->arena_stack);
Vladimir Marko69f08ba2014-04-11 12:28:11 +0100998 ScopedArenaSet<MapEntry, MapEntryComparator> class_to_index_map(MapEntryComparator(),
999 allocator.Adapter());
Vladimir Markobfea9c22014-01-17 17:49:33 +00001000
1001 // First, find all SGET/SPUTs that may need class initialization checks, record INVOKE_STATICs.
1002 AllNodesIterator iter(this);
1003 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1004 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1005 DCHECK(bb->data_flow_info != nullptr);
1006 if (mir->dalvikInsn.opcode >= Instruction::SGET &&
1007 mir->dalvikInsn.opcode <= Instruction::SPUT_SHORT) {
1008 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
1009 uint16_t index = 0xffffu;
Vladimir Markof418f322014-07-09 14:45:36 +01001010 if (!field_info.IsInitialized()) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001011 DCHECK_LT(class_to_index_map.size(), 0xffffu);
1012 MapEntry entry = {
Vladimir Markof418f322014-07-09 14:45:36 +01001013 // Treat unresolved fields as if each had its own class.
1014 field_info.IsResolved() ? field_info.DeclaringDexFile()
1015 : nullptr,
1016 field_info.IsResolved() ? field_info.DeclaringClassIndex()
1017 : field_info.FieldIndex(),
Vladimir Markobfea9c22014-01-17 17:49:33 +00001018 static_cast<uint16_t>(class_to_index_map.size())
1019 };
1020 index = class_to_index_map.insert(entry).first->index;
1021 }
1022 // Using offset/2 for index into temp_insn_data_.
1023 temp_insn_data_[mir->offset / 2u] = index;
1024 }
1025 }
1026 }
1027 unique_class_count = static_cast<uint32_t>(class_to_index_map.size());
1028 }
1029
1030 if (unique_class_count == 0u) {
1031 // All SGET/SPUTs refer to initialized classes. Nothing to do.
1032 temp_insn_data_ = nullptr;
1033 temp_scoped_alloc_.reset();
1034 return false;
1035 }
1036
1037 temp_bit_vector_size_ = unique_class_count;
1038 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1039 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapClInitCheck);
1040 DCHECK_GT(temp_bit_vector_size_, 0u);
1041 return true;
1042}
1043
1044/*
1045 * Eliminate unnecessary class initialization checks for a basic block.
1046 */
1047bool MIRGraph::EliminateClassInitChecks(BasicBlock* bb) {
1048 DCHECK_EQ((cu_->disable_opt & (1 << kClassInitCheckElimination)), 0u);
1049 if (bb->data_flow_info == NULL) {
1050 return false;
1051 }
1052
1053 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +01001054 * Set initial state. Catch blocks don't need any special treatment.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001055 */
1056 ArenaBitVector* classes_to_check = temp_bit_vector_;
1057 DCHECK(classes_to_check != nullptr);
Vladimir Marko0a810d22014-07-11 14:44:36 +01001058 if (bb->block_type == kEntryBlock) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001059 classes_to_check->SetInitialBits(temp_bit_vector_size_);
1060 } else if (bb->predecessors->Size() == 1) {
1061 BasicBlock* pred_bb = GetBasicBlock(bb->predecessors->Get(0));
1062 // pred_bb must have already been processed at least once.
1063 DCHECK(pred_bb != nullptr);
1064 DCHECK(pred_bb->data_flow_info != nullptr);
1065 DCHECK(pred_bb->data_flow_info->ending_check_v != nullptr);
1066 classes_to_check->Copy(pred_bb->data_flow_info->ending_check_v);
1067 } else {
1068 // Starting state is union of all incoming arcs
1069 GrowableArray<BasicBlockId>::Iterator iter(bb->predecessors);
1070 BasicBlock* pred_bb = GetBasicBlock(iter.Next());
1071 DCHECK(pred_bb != NULL);
1072 DCHECK(pred_bb->data_flow_info != NULL);
1073 while (pred_bb->data_flow_info->ending_check_v == nullptr) {
1074 pred_bb = GetBasicBlock(iter.Next());
1075 // At least one predecessor must have been processed before this bb.
1076 DCHECK(pred_bb != nullptr);
1077 DCHECK(pred_bb->data_flow_info != nullptr);
1078 }
1079 classes_to_check->Copy(pred_bb->data_flow_info->ending_check_v);
1080 while (true) {
1081 pred_bb = GetBasicBlock(iter.Next());
1082 if (!pred_bb) break;
1083 DCHECK(pred_bb->data_flow_info != nullptr);
1084 if (pred_bb->data_flow_info->ending_check_v == nullptr) {
1085 continue;
1086 }
1087 classes_to_check->Union(pred_bb->data_flow_info->ending_check_v);
1088 }
1089 }
1090 // At this point, classes_to_check shows which classes need clinit checks.
1091
1092 // Walk through the instruction in the block, updating as necessary
1093 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1094 if (mir->dalvikInsn.opcode >= Instruction::SGET &&
1095 mir->dalvikInsn.opcode <= Instruction::SPUT_SHORT) {
1096 uint16_t index = temp_insn_data_[mir->offset / 2u];
1097 if (index != 0xffffu) {
1098 if (mir->dalvikInsn.opcode >= Instruction::SGET &&
1099 mir->dalvikInsn.opcode <= Instruction::SPUT_SHORT) {
1100 if (!classes_to_check->IsBitSet(index)) {
1101 // Eliminate the class init check.
1102 mir->optimization_flags |= MIR_IGNORE_CLINIT_CHECK;
1103 } else {
1104 // Do the class init check.
1105 mir->optimization_flags &= ~MIR_IGNORE_CLINIT_CHECK;
1106 }
1107 }
1108 // Mark the class as initialized.
1109 classes_to_check->ClearBit(index);
1110 }
1111 }
1112 }
1113
1114 // Did anything change?
1115 bool changed = false;
1116 if (bb->data_flow_info->ending_check_v == nullptr) {
1117 DCHECK(temp_scoped_alloc_.get() != nullptr);
1118 DCHECK(bb->data_flow_info != nullptr);
1119 bb->data_flow_info->ending_check_v = new (temp_scoped_alloc_.get()) ArenaBitVector(
1120 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapClInitCheck);
1121 changed = classes_to_check->GetHighestBitSet() != -1;
1122 bb->data_flow_info->ending_check_v->Copy(classes_to_check);
1123 } else if (!classes_to_check->Equal(bb->data_flow_info->ending_check_v)) {
1124 changed = true;
1125 bb->data_flow_info->ending_check_v->Copy(classes_to_check);
1126 }
1127 return changed;
1128}
1129
1130void MIRGraph::EliminateClassInitChecksEnd() {
1131 // Clean up temporaries.
1132 temp_bit_vector_size_ = 0u;
1133 temp_bit_vector_ = nullptr;
1134 AllNodesIterator iter(this);
1135 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1136 if (bb->data_flow_info != nullptr) {
1137 bb->data_flow_info->ending_check_v = nullptr;
1138 }
1139 }
1140
1141 DCHECK(temp_insn_data_ != nullptr);
1142 temp_insn_data_ = nullptr;
1143 DCHECK(temp_scoped_alloc_.get() != nullptr);
1144 temp_scoped_alloc_.reset();
1145}
1146
Vladimir Marko95a05972014-05-30 10:01:32 +01001147bool MIRGraph::ApplyGlobalValueNumberingGate() {
Vladimir Marko55fff042014-07-10 12:42:52 +01001148 if ((cu_->disable_opt & (1u << kGlobalValueNumbering)) != 0u) {
Vladimir Marko95a05972014-05-30 10:01:32 +01001149 return false;
1150 }
1151
1152 DCHECK(temp_scoped_alloc_ == nullptr);
1153 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1154 DCHECK(temp_gvn_ == nullptr);
1155 temp_gvn_.reset(
1156 new (temp_scoped_alloc_.get()) GlobalValueNumbering(cu_, temp_scoped_alloc_.get()));
1157 return true;
1158}
1159
1160bool MIRGraph::ApplyGlobalValueNumbering(BasicBlock* bb) {
1161 DCHECK(temp_gvn_ != nullptr);
1162 LocalValueNumbering* lvn = temp_gvn_->PrepareBasicBlock(bb);
1163 if (lvn != nullptr) {
1164 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1165 lvn->GetValueNumber(mir);
1166 }
1167 }
1168 bool change = (lvn != nullptr) && temp_gvn_->FinishBasicBlock(bb);
1169 return change;
1170}
1171
1172void MIRGraph::ApplyGlobalValueNumberingEnd() {
1173 // Perform modifications.
1174 if (temp_gvn_->Good()) {
1175 temp_gvn_->AllowModifications();
1176 PreOrderDfsIterator iter(this);
1177 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Vladimir Markob19955d2014-07-29 12:04:10 +01001178 ScopedArenaAllocator allocator(&cu_->arena_stack); // Reclaim memory after each LVN.
1179 LocalValueNumbering* lvn = temp_gvn_->PrepareBasicBlock(bb, &allocator);
Vladimir Marko95a05972014-05-30 10:01:32 +01001180 if (lvn != nullptr) {
1181 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1182 lvn->GetValueNumber(mir);
1183 }
1184 bool change = temp_gvn_->FinishBasicBlock(bb);
Vladimir Marko55fff042014-07-10 12:42:52 +01001185 DCHECK(!change) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko95a05972014-05-30 10:01:32 +01001186 }
1187 }
1188 } else {
1189 LOG(WARNING) << "GVN failed for " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
1190 }
1191
1192 DCHECK(temp_gvn_ != nullptr);
1193 temp_gvn_.reset();
1194 DCHECK(temp_scoped_alloc_ != nullptr);
1195 temp_scoped_alloc_.reset();
1196}
1197
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001198void MIRGraph::ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput) {
1199 uint32_t method_index = invoke->meta.method_lowering_info;
1200 if (temp_bit_vector_->IsBitSet(method_index)) {
1201 iget_or_iput->meta.ifield_lowering_info = temp_insn_data_[method_index];
1202 DCHECK_EQ(field_idx, GetIFieldLoweringInfo(iget_or_iput).FieldIndex());
1203 return;
1204 }
1205
1206 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(invoke);
1207 MethodReference target = method_info.GetTargetMethod();
1208 DexCompilationUnit inlined_unit(
1209 cu_, cu_->class_loader, cu_->class_linker, *target.dex_file,
1210 nullptr /* code_item not used */, 0u /* class_def_idx not used */, target.dex_method_index,
1211 0u /* access_flags not used */, nullptr /* verified_method not used */);
1212 MirIFieldLoweringInfo inlined_field_info(field_idx);
1213 MirIFieldLoweringInfo::Resolve(cu_->compiler_driver, &inlined_unit, &inlined_field_info, 1u);
1214 DCHECK(inlined_field_info.IsResolved());
1215
1216 uint32_t field_info_index = ifield_lowering_infos_.Size();
1217 ifield_lowering_infos_.Insert(inlined_field_info);
1218 temp_bit_vector_->SetBit(method_index);
1219 temp_insn_data_[method_index] = field_info_index;
1220 iget_or_iput->meta.ifield_lowering_info = field_info_index;
1221}
1222
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001223bool MIRGraph::InlineSpecialMethodsGate() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001224 if ((cu_->disable_opt & (1 << kSuppressMethodInlining)) != 0 ||
1225 method_lowering_infos_.Size() == 0u) {
1226 return false;
1227 }
1228 if (cu_->compiler_driver->GetMethodInlinerMap() == nullptr) {
1229 // This isn't the Quick compiler.
1230 return false;
1231 }
1232 return true;
1233}
1234
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001235void MIRGraph::InlineSpecialMethodsStart() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001236 // Prepare for inlining getters/setters. Since we're inlining at most 1 IGET/IPUT from
1237 // each INVOKE, we can index the data by the MIR::meta::method_lowering_info index.
1238
1239 DCHECK(temp_scoped_alloc_.get() == nullptr);
1240 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1241 temp_bit_vector_size_ = method_lowering_infos_.Size();
1242 temp_bit_vector_ = new (temp_scoped_alloc_.get()) ArenaBitVector(
1243 temp_scoped_alloc_.get(), temp_bit_vector_size_, false, kBitMapMisc);
1244 temp_bit_vector_->ClearAllBits();
1245 temp_insn_data_ = static_cast<uint16_t*>(temp_scoped_alloc_->Alloc(
1246 temp_bit_vector_size_ * sizeof(*temp_insn_data_), kArenaAllocGrowableArray));
1247}
1248
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001249void MIRGraph::InlineSpecialMethods(BasicBlock* bb) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001250 if (bb->block_type != kDalvikByteCode) {
1251 return;
1252 }
1253 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001254 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee35ba7f32014-05-31 08:59:01 -07001255 continue;
1256 }
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001257 if (!(Instruction::FlagsOf(mir->dalvikInsn.opcode) & Instruction::kInvoke)) {
1258 continue;
1259 }
1260 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
1261 if (!method_info.FastPath()) {
1262 continue;
1263 }
1264 InvokeType sharp_type = method_info.GetSharpType();
1265 if ((sharp_type != kDirect) &&
1266 (sharp_type != kStatic || method_info.NeedsClassInitialization())) {
1267 continue;
1268 }
1269 DCHECK(cu_->compiler_driver->GetMethodInlinerMap() != nullptr);
1270 MethodReference target = method_info.GetTargetMethod();
1271 if (cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(target.dex_file)
1272 ->GenInline(this, bb, mir, target.dex_method_index)) {
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001273 if (cu_->verbose || cu_->print_pass) {
1274 LOG(INFO) << "SpecialMethodInliner: Inlined " << method_info.GetInvokeType() << " ("
1275 << sharp_type << ") call to \"" << PrettyMethod(target.dex_method_index, *target.dex_file)
1276 << "\" from \"" << PrettyMethod(cu_->method_idx, *cu_->dex_file)
1277 << "\" @0x" << std::hex << mir->offset;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001278 }
1279 }
1280 }
1281}
1282
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001283void MIRGraph::InlineSpecialMethodsEnd() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001284 DCHECK(temp_insn_data_ != nullptr);
1285 temp_insn_data_ = nullptr;
1286 DCHECK(temp_bit_vector_ != nullptr);
1287 temp_bit_vector_ = nullptr;
1288 DCHECK(temp_scoped_alloc_.get() != nullptr);
1289 temp_scoped_alloc_.reset();
1290}
1291
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001292void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -08001293 Checkstats* stats =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001294 static_cast<Checkstats*>(arena_->Alloc(sizeof(Checkstats), kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001295 checkstats_ = stats;
buzbee56c71782013-09-05 17:13:19 -07001296 AllNodesIterator iter(this);
buzbee311ca162013-02-28 15:56:43 -08001297 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
1298 CountChecks(bb);
1299 }
1300 if (stats->null_checks > 0) {
1301 float eliminated = static_cast<float>(stats->null_checks_eliminated);
1302 float checks = static_cast<float>(stats->null_checks);
1303 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1304 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
1305 << (eliminated/checks) * 100.0 << "%";
1306 }
1307 if (stats->range_checks > 0) {
1308 float eliminated = static_cast<float>(stats->range_checks_eliminated);
1309 float checks = static_cast<float>(stats->range_checks);
1310 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1311 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
1312 << (eliminated/checks) * 100.0 << "%";
1313 }
1314}
1315
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001316bool MIRGraph::BuildExtendedBBList(struct BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -08001317 if (bb->visited) return false;
1318 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
1319 || (bb->block_type == kExitBlock))) {
1320 // Ignore special blocks
1321 bb->visited = true;
1322 return false;
1323 }
1324 // Must be head of extended basic block.
1325 BasicBlock* start_bb = bb;
buzbee0d829482013-10-11 15:24:55 -07001326 extended_basic_blocks_.push_back(bb->id);
buzbee311ca162013-02-28 15:56:43 -08001327 bool terminated_by_return = false;
buzbee1da1e2f2013-11-15 13:37:01 -08001328 bool do_local_value_numbering = false;
buzbee311ca162013-02-28 15:56:43 -08001329 // Visit blocks strictly dominated by this head.
1330 while (bb != NULL) {
1331 bb->visited = true;
1332 terminated_by_return |= bb->terminated_by_return;
buzbee1da1e2f2013-11-15 13:37:01 -08001333 do_local_value_numbering |= bb->use_lvn;
buzbee311ca162013-02-28 15:56:43 -08001334 bb = NextDominatedBlock(bb);
1335 }
buzbee1da1e2f2013-11-15 13:37:01 -08001336 if (terminated_by_return || do_local_value_numbering) {
1337 // Do lvn for all blocks in this extended set.
buzbee311ca162013-02-28 15:56:43 -08001338 bb = start_bb;
1339 while (bb != NULL) {
buzbee1da1e2f2013-11-15 13:37:01 -08001340 bb->use_lvn = do_local_value_numbering;
1341 bb->dominates_return = terminated_by_return;
buzbee311ca162013-02-28 15:56:43 -08001342 bb = NextDominatedBlock(bb);
1343 }
1344 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001345 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -08001346}
1347
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001348void MIRGraph::BasicBlockOptimization() {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001349 if ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) {
1350 ClearAllVisitedFlags();
1351 PreOrderDfsIterator iter2(this);
1352 for (BasicBlock* bb = iter2.Next(); bb != NULL; bb = iter2.Next()) {
1353 BuildExtendedBBList(bb);
buzbee311ca162013-02-28 15:56:43 -08001354 }
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001355 // Perform extended basic block optimizations.
1356 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
1357 BasicBlockOpt(GetBasicBlock(extended_basic_blocks_[i]));
1358 }
1359 } else {
1360 PreOrderDfsIterator iter(this);
1361 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
1362 BasicBlockOpt(bb);
1363 }
buzbee311ca162013-02-28 15:56:43 -08001364 }
1365}
1366
1367} // namespace art