blob: 546e67a6262908b3acb8c934280c15b003ce1198 [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"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080018#include "base/logging.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080019#include "base/scoped_arena_containers.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070020#include "dataflow_iterator-inl.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080021#include "dex_flags.h"
22#include "driver/compiler_driver.h"
23#include "driver/dex_compilation_unit.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010024#include "global_value_numbering.h"
Vladimir Marko7a01dc22015-01-02 17:00:44 +000025#include "gvn_dead_code_elimination.h"
buzbee311ca162013-02-28 15:56:43 -080026#include "local_value_numbering.h"
Vladimir Markoaf6925b2014-10-31 16:37:32 +000027#include "mir_field_info.h"
Vladimir Markoe490b012015-02-24 11:32:46 +000028#include "type_inference.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070029#include "quick/dex_file_method_inliner.h"
30#include "quick/dex_file_to_method_inliner_map.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070031#include "stack.h"
buzbee311ca162013-02-28 15:56:43 -080032
33namespace art {
34
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070035static unsigned int Predecessors(BasicBlock* bb) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +010036 return bb->predecessors.size();
buzbee311ca162013-02-28 15:56:43 -080037}
38
39/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070040void MIRGraph::SetConstant(int32_t ssa_reg, int32_t value) {
buzbee862a7602013-04-05 10:58:54 -070041 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080042 constant_values_[ssa_reg] = value;
Vladimir Marko066f9e42015-01-16 16:04:43 +000043 reg_location_[ssa_reg].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080044}
45
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070046void MIRGraph::SetConstantWide(int32_t ssa_reg, int64_t value) {
buzbee862a7602013-04-05 10:58:54 -070047 is_constant_v_->SetBit(ssa_reg);
Serguei Katkov597da1f2014-07-15 17:25:46 +070048 is_constant_v_->SetBit(ssa_reg + 1);
buzbee311ca162013-02-28 15:56:43 -080049 constant_values_[ssa_reg] = Low32Bits(value);
50 constant_values_[ssa_reg + 1] = High32Bits(value);
Vladimir Marko066f9e42015-01-16 16:04:43 +000051 reg_location_[ssa_reg].is_const = true;
52 reg_location_[ssa_reg + 1].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080053}
54
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -080055void MIRGraph::DoConstantPropagation(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -080056 MIR* mir;
buzbee311ca162013-02-28 15:56:43 -080057
58 for (mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070059 // Skip pass if BB has MIR without SSA representation.
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070060 if (mir->ssa_rep == nullptr) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070061 return;
62 }
63
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070064 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -080065
Ian Rogers29a26482014-05-02 15:27:29 -070066 MIR::DecodedInstruction* d_insn = &mir->dalvikInsn;
buzbee311ca162013-02-28 15:56:43 -080067
68 if (!(df_attributes & DF_HAS_DEFS)) continue;
69
70 /* Handle instructions that set up constants directly */
71 if (df_attributes & DF_SETS_CONST) {
72 if (df_attributes & DF_DA) {
73 int32_t vB = static_cast<int32_t>(d_insn->vB);
74 switch (d_insn->opcode) {
75 case Instruction::CONST_4:
76 case Instruction::CONST_16:
77 case Instruction::CONST:
78 SetConstant(mir->ssa_rep->defs[0], vB);
79 break;
80 case Instruction::CONST_HIGH16:
81 SetConstant(mir->ssa_rep->defs[0], vB << 16);
82 break;
83 case Instruction::CONST_WIDE_16:
84 case Instruction::CONST_WIDE_32:
85 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
86 break;
87 case Instruction::CONST_WIDE:
Brian Carlstromb1eba212013-07-17 18:07:19 -070088 SetConstantWide(mir->ssa_rep->defs[0], d_insn->vB_wide);
buzbee311ca162013-02-28 15:56:43 -080089 break;
90 case Instruction::CONST_WIDE_HIGH16:
91 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
92 break;
93 default:
94 break;
95 }
96 }
97 /* Handle instructions that set up constants directly */
98 } else if (df_attributes & DF_IS_MOVE) {
99 int i;
100
101 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
buzbee862a7602013-04-05 10:58:54 -0700102 if (!is_constant_v_->IsBitSet(mir->ssa_rep->uses[i])) break;
buzbee311ca162013-02-28 15:56:43 -0800103 }
104 /* Move a register holding a constant to another register */
105 if (i == mir->ssa_rep->num_uses) {
106 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
107 if (df_attributes & DF_A_WIDE) {
108 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
109 }
110 }
111 }
112 }
113 /* TODO: implement code to handle arithmetic operations */
buzbee311ca162013-02-28 15:56:43 -0800114}
115
buzbee311ca162013-02-28 15:56:43 -0800116/* Advance to next strictly dominated MIR node in an extended basic block */
buzbee0d829482013-10-11 15:24:55 -0700117MIR* MIRGraph::AdvanceMIR(BasicBlock** p_bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800118 BasicBlock* bb = *p_bb;
119 if (mir != NULL) {
120 mir = mir->next;
Serguei Katkovea392162015-01-29 17:08:05 +0600121 while (mir == NULL) {
buzbee0d829482013-10-11 15:24:55 -0700122 bb = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800123 if ((bb == NULL) || Predecessors(bb) != 1) {
Serguei Katkovea392162015-01-29 17:08:05 +0600124 // mir is null and we cannot proceed further.
125 break;
buzbee311ca162013-02-28 15:56:43 -0800126 } else {
Serguei Katkovea392162015-01-29 17:08:05 +0600127 *p_bb = bb;
128 mir = bb->first_mir_insn;
buzbee311ca162013-02-28 15:56:43 -0800129 }
130 }
131 }
132 return mir;
133}
134
135/*
136 * To be used at an invoke mir. If the logically next mir node represents
137 * a move-result, return it. Else, return NULL. If a move-result exists,
138 * it is required to immediately follow the invoke with no intervening
139 * opcodes or incoming arcs. However, if the result of the invoke is not
140 * used, a move-result may not be present.
141 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700142MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800143 BasicBlock* tbb = bb;
144 mir = AdvanceMIR(&tbb, mir);
145 while (mir != NULL) {
buzbee311ca162013-02-28 15:56:43 -0800146 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
147 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
148 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
149 break;
150 }
151 // Keep going if pseudo op, otherwise terminate
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700152 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee311ca162013-02-28 15:56:43 -0800153 mir = AdvanceMIR(&tbb, mir);
buzbee35ba7f32014-05-31 08:59:01 -0700154 } else {
155 mir = NULL;
buzbee311ca162013-02-28 15:56:43 -0800156 }
157 }
158 return mir;
159}
160
buzbee0d829482013-10-11 15:24:55 -0700161BasicBlock* MIRGraph::NextDominatedBlock(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800162 if (bb->block_type == kDead) {
163 return NULL;
164 }
165 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
166 || (bb->block_type == kExitBlock));
buzbee0d829482013-10-11 15:24:55 -0700167 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
168 BasicBlock* bb_fall_through = GetBasicBlock(bb->fall_through);
buzbee1da1e2f2013-11-15 13:37:01 -0800169 if (((bb_fall_through == NULL) && (bb_taken != NULL)) &&
buzbee0d829482013-10-11 15:24:55 -0700170 ((bb_taken->block_type == kDalvikByteCode) || (bb_taken->block_type == kExitBlock))) {
buzbeecbcfaf32013-08-19 07:37:40 -0700171 // Follow simple unconditional branches.
buzbee0d829482013-10-11 15:24:55 -0700172 bb = bb_taken;
buzbeecbcfaf32013-08-19 07:37:40 -0700173 } else {
174 // Follow simple fallthrough
buzbee0d829482013-10-11 15:24:55 -0700175 bb = (bb_taken != NULL) ? NULL : bb_fall_through;
buzbeecbcfaf32013-08-19 07:37:40 -0700176 }
buzbee311ca162013-02-28 15:56:43 -0800177 if (bb == NULL || (Predecessors(bb) != 1)) {
178 return NULL;
179 }
180 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
181 return bb;
182}
183
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700184static MIR* FindPhi(BasicBlock* bb, int ssa_name) {
buzbee311ca162013-02-28 15:56:43 -0800185 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
186 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
187 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
188 if (mir->ssa_rep->uses[i] == ssa_name) {
189 return mir;
190 }
191 }
192 }
193 }
194 return NULL;
195}
196
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700197static SelectInstructionKind SelectKind(MIR* mir) {
Chao-ying Fu8ac41af2014-10-01 16:53:04 -0700198 // Work with the case when mir is nullptr.
199 if (mir == nullptr) {
200 return kSelectNone;
201 }
buzbee311ca162013-02-28 15:56:43 -0800202 switch (mir->dalvikInsn.opcode) {
203 case Instruction::MOVE:
204 case Instruction::MOVE_OBJECT:
205 case Instruction::MOVE_16:
206 case Instruction::MOVE_OBJECT_16:
207 case Instruction::MOVE_FROM16:
208 case Instruction::MOVE_OBJECT_FROM16:
209 return kSelectMove;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700210 case Instruction::CONST:
211 case Instruction::CONST_4:
212 case Instruction::CONST_16:
buzbee311ca162013-02-28 15:56:43 -0800213 return kSelectConst;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700214 case Instruction::GOTO:
215 case Instruction::GOTO_16:
216 case Instruction::GOTO_32:
buzbee311ca162013-02-28 15:56:43 -0800217 return kSelectGoto;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700218 default:
219 return kSelectNone;
buzbee311ca162013-02-28 15:56:43 -0800220 }
buzbee311ca162013-02-28 15:56:43 -0800221}
222
Vladimir Markoa1a70742014-03-03 10:28:05 +0000223static constexpr ConditionCode kIfCcZConditionCodes[] = {
224 kCondEq, kCondNe, kCondLt, kCondGe, kCondGt, kCondLe
225};
226
Andreas Gampe785d2f22014-11-03 22:57:30 -0800227static_assert(arraysize(kIfCcZConditionCodes) == Instruction::IF_LEZ - Instruction::IF_EQZ + 1,
228 "if_ccz_ccodes_size1");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000229
Vladimir Markoa1a70742014-03-03 10:28:05 +0000230static constexpr ConditionCode ConditionCodeForIfCcZ(Instruction::Code opcode) {
231 return kIfCcZConditionCodes[opcode - Instruction::IF_EQZ];
232}
233
Andreas Gampe785d2f22014-11-03 22:57:30 -0800234static_assert(ConditionCodeForIfCcZ(Instruction::IF_EQZ) == kCondEq, "if_eqz ccode");
235static_assert(ConditionCodeForIfCcZ(Instruction::IF_NEZ) == kCondNe, "if_nez ccode");
236static_assert(ConditionCodeForIfCcZ(Instruction::IF_LTZ) == kCondLt, "if_ltz ccode");
237static_assert(ConditionCodeForIfCcZ(Instruction::IF_GEZ) == kCondGe, "if_gez ccode");
238static_assert(ConditionCodeForIfCcZ(Instruction::IF_GTZ) == kCondGt, "if_gtz ccode");
239static_assert(ConditionCodeForIfCcZ(Instruction::IF_LEZ) == kCondLe, "if_lez ccode");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000240
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700241int MIRGraph::GetSSAUseCount(int s_reg) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100242 DCHECK_LT(static_cast<size_t>(s_reg), ssa_subscripts_.size());
243 return raw_use_counts_[s_reg];
buzbee311ca162013-02-28 15:56:43 -0800244}
245
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700246size_t MIRGraph::GetNumBytesForSpecialTemps() const {
247 // This logic is written with assumption that Method* is only special temp.
248 DCHECK_EQ(max_available_special_compiler_temps_, 1u);
249 return sizeof(StackReference<mirror::ArtMethod>);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800250}
251
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700252size_t MIRGraph::GetNumAvailableVRTemps() {
253 // First take into account all temps reserved for backend.
254 if (max_available_non_special_compiler_temps_ < reserved_temps_for_backend_) {
255 return 0;
256 }
257
258 // Calculate remaining ME temps available.
259 size_t remaining_me_temps = max_available_non_special_compiler_temps_ - reserved_temps_for_backend_;
260
261 if (num_non_special_compiler_temps_ >= remaining_me_temps) {
262 return 0;
263 } else {
264 return remaining_me_temps - num_non_special_compiler_temps_;
265 }
266}
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000267
268// FIXME - will probably need to revisit all uses of this, as type not defined.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800269static const RegLocation temp_loc = {kLocCompilerTemp,
buzbee091cc402014-03-31 10:14:40 -0700270 0, 1 /*defined*/, 0, 0, 0, 0, 0, 1 /*home*/,
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000271 RegStorage(), INVALID_SREG, INVALID_SREG};
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800272
273CompilerTemp* MIRGraph::GetNewCompilerTemp(CompilerTempType ct_type, bool wide) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700274 // Once the compiler temps have been committed, new ones cannot be requested anymore.
275 DCHECK_EQ(compiler_temps_committed_, false);
276 // Make sure that reserved for BE set is sane.
277 DCHECK_LE(reserved_temps_for_backend_, max_available_non_special_compiler_temps_);
278
279 bool verbose = cu_->verbose;
280 const char* ct_type_str = nullptr;
281
282 if (verbose) {
283 switch (ct_type) {
284 case kCompilerTempBackend:
285 ct_type_str = "backend";
286 break;
287 case kCompilerTempSpecialMethodPtr:
288 ct_type_str = "method*";
289 break;
290 case kCompilerTempVR:
291 ct_type_str = "VR";
292 break;
293 default:
294 ct_type_str = "unknown";
295 break;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800296 }
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700297 LOG(INFO) << "CompilerTemps: A compiler temp of type " << ct_type_str << " that is "
298 << (wide ? "wide is being requested." : "not wide is being requested.");
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800299 }
300
301 CompilerTemp *compiler_temp = static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000302 kArenaAllocRegAlloc));
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800303
304 // Create the type of temp requested. Special temps need special handling because
305 // they have a specific virtual register assignment.
306 if (ct_type == kCompilerTempSpecialMethodPtr) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700307 // This has a special location on stack which is 32-bit or 64-bit depending
308 // on mode. However, we don't want to overlap with non-special section
309 // and thus even for 64-bit, we allow only a non-wide temp to be requested.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800310 DCHECK_EQ(wide, false);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800311
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700312 // The vreg is always the first special temp for method ptr.
313 compiler_temp->v_reg = GetFirstSpecialTempVR();
314
315 } else if (ct_type == kCompilerTempBackend) {
316 requested_backend_temp_ = true;
317
318 // Make sure that we are not exceeding temps reserved for BE.
319 // Since VR temps cannot be requested once the BE temps are requested, we
320 // allow reservation of VR temps as well for BE. We
321 size_t available_temps = reserved_temps_for_backend_ + GetNumAvailableVRTemps();
Vladimir Markocc234812015-04-07 09:36:09 +0100322 size_t needed_temps = wide ? 2u : 1u;
323 if (available_temps < needed_temps) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700324 if (verbose) {
Vladimir Markocc234812015-04-07 09:36:09 +0100325 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
326 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700327 }
328 return nullptr;
329 }
330
331 // Update the remaining reserved temps since we have now used them.
332 // Note that the code below is actually subtracting to remove them from reserve
333 // once they have been claimed. It is careful to not go below zero.
Vladimir Markocc234812015-04-07 09:36:09 +0100334 reserved_temps_for_backend_ =
335 std::max(reserved_temps_for_backend_, needed_temps) - needed_temps;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700336
337 // The new non-special compiler temp must receive a unique v_reg.
338 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
339 num_non_special_compiler_temps_++;
340 } else if (ct_type == kCompilerTempVR) {
341 // Once we start giving out BE temps, we don't allow anymore ME temps to be requested.
342 // This is done in order to prevent problems with ssa since these structures are allocated
343 // and managed by the ME.
344 DCHECK_EQ(requested_backend_temp_, false);
345
346 // There is a limit to the number of non-special temps so check to make sure it wasn't exceeded.
347 size_t available_temps = GetNumAvailableVRTemps();
348 if (available_temps <= 0 || (available_temps <= 1 && wide)) {
349 if (verbose) {
350 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str << " are available.";
351 }
352 return nullptr;
353 }
354
355 // The new non-special compiler temp must receive a unique v_reg.
356 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
357 num_non_special_compiler_temps_++;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800358 } else {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700359 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << ct_type_str << ".";
360 }
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800361
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700362 // We allocate an sreg as well to make developer life easier.
363 // However, if this is requested from an ME pass that will recalculate ssa afterwards,
364 // this sreg is no longer valid. The caller should be aware of this.
365 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
366
367 if (verbose) {
368 LOG(INFO) << "CompilerTemps: New temp of type " << ct_type_str << " with v" << compiler_temp->v_reg
369 << " and s" << compiler_temp->s_reg_low << " has been created.";
370 }
371
372 if (wide) {
373 // Only non-special temps are handled as wide for now.
374 // Note that the number of non special temps is incremented below.
375 DCHECK(ct_type == kCompilerTempBackend || ct_type == kCompilerTempVR);
376
377 // Ensure that the two registers are consecutive.
378 int ssa_reg_low = compiler_temp->s_reg_low;
379 int ssa_reg_high = AddNewSReg(compiler_temp->v_reg + 1);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800380 num_non_special_compiler_temps_++;
381
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700382 if (verbose) {
383 LOG(INFO) << "CompilerTemps: The wide part of temp of type " << ct_type_str << " is v"
384 << compiler_temp->v_reg + 1 << " and s" << ssa_reg_high << ".";
385 }
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700386
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700387 if (reg_location_ != nullptr) {
388 reg_location_[ssa_reg_high] = temp_loc;
389 reg_location_[ssa_reg_high].high_word = true;
390 reg_location_[ssa_reg_high].s_reg_low = ssa_reg_low;
391 reg_location_[ssa_reg_high].wide = true;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800392 }
393 }
394
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700395 // If the register locations have already been allocated, add the information
396 // about the temp. We will not overflow because they have been initialized
397 // to support the maximum number of temps. For ME temps that have multiple
398 // ssa versions, the structures below will be expanded on the post pass cleanup.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800399 if (reg_location_ != nullptr) {
400 int ssa_reg_low = compiler_temp->s_reg_low;
401 reg_location_[ssa_reg_low] = temp_loc;
402 reg_location_[ssa_reg_low].s_reg_low = ssa_reg_low;
403 reg_location_[ssa_reg_low].wide = wide;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800404 }
405
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800406 return compiler_temp;
407}
buzbee311ca162013-02-28 15:56:43 -0800408
Vladimir Markocc234812015-04-07 09:36:09 +0100409void MIRGraph::RemoveLastCompilerTemp(CompilerTempType ct_type, bool wide, CompilerTemp* temp) {
410 // Once the compiler temps have been committed, it's too late for any modifications.
411 DCHECK_EQ(compiler_temps_committed_, false);
412
413 size_t used_temps = wide ? 2u : 1u;
414
415 if (ct_type == kCompilerTempBackend) {
416 DCHECK(requested_backend_temp_);
417
418 // Make the temps available to backend again.
419 reserved_temps_for_backend_ += used_temps;
420 } else if (ct_type == kCompilerTempVR) {
421 DCHECK(!requested_backend_temp_);
422 } else {
423 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << static_cast<int>(ct_type);
424 }
425
426 // Reduce the number of non-special compiler temps.
427 DCHECK_LE(used_temps, num_non_special_compiler_temps_);
428 num_non_special_compiler_temps_ -= used_temps;
429
430 // Check that this was really the last temp.
431 DCHECK_EQ(static_cast<size_t>(temp->v_reg),
432 GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_);
433
434 if (cu_->verbose) {
435 LOG(INFO) << "Last temporary has been removed.";
436 }
437}
438
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000439static bool EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
440 bool is_taken;
441 switch (opcode) {
442 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
443 case Instruction::IF_NE: is_taken = (src1 != src2); break;
444 case Instruction::IF_LT: is_taken = (src1 < src2); break;
445 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
446 case Instruction::IF_GT: is_taken = (src1 > src2); break;
447 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
448 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
449 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
450 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
451 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
452 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
453 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
454 default:
455 LOG(FATAL) << "Unexpected opcode " << opcode;
456 UNREACHABLE();
457 }
458 return is_taken;
459}
460
buzbee311ca162013-02-28 15:56:43 -0800461/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700462bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800463 if (bb->block_type == kDead) {
464 return true;
465 }
Ningsheng Jiana262f772014-11-25 16:48:07 +0800466 // Currently multiply-accumulate backend supports are only available on arm32 and arm64.
467 if (cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2) {
468 MultiplyAddOpt(bb);
469 }
Vladimir Marko415ac882014-09-30 18:09:14 +0100470 bool use_lvn = bb->use_lvn && (cu_->disable_opt & (1u << kLocalValueNumbering)) == 0u;
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100471 std::unique_ptr<ScopedArenaAllocator> allocator;
Vladimir Marko95a05972014-05-30 10:01:32 +0100472 std::unique_ptr<GlobalValueNumbering> global_valnum;
Ian Rogers700a4022014-05-19 16:49:03 -0700473 std::unique_ptr<LocalValueNumbering> local_valnum;
buzbee1da1e2f2013-11-15 13:37:01 -0800474 if (use_lvn) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100475 allocator.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko415ac882014-09-30 18:09:14 +0100476 global_valnum.reset(new (allocator.get()) GlobalValueNumbering(cu_, allocator.get(),
477 GlobalValueNumbering::kModeLvn));
Vladimir Markob19955d2014-07-29 12:04:10 +0100478 local_valnum.reset(new (allocator.get()) LocalValueNumbering(global_valnum.get(), bb->id,
479 allocator.get()));
buzbee1da1e2f2013-11-15 13:37:01 -0800480 }
buzbee311ca162013-02-28 15:56:43 -0800481 while (bb != NULL) {
482 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
483 // TUNING: use the returned value number for CSE.
buzbee1da1e2f2013-11-15 13:37:01 -0800484 if (use_lvn) {
485 local_valnum->GetValueNumber(mir);
486 }
buzbee311ca162013-02-28 15:56:43 -0800487 // Look for interesting opcodes, skip otherwise
488 Instruction::Code opcode = mir->dalvikInsn.opcode;
489 switch (opcode) {
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000490 case Instruction::IF_EQ:
491 case Instruction::IF_NE:
492 case Instruction::IF_LT:
493 case Instruction::IF_GE:
494 case Instruction::IF_GT:
495 case Instruction::IF_LE:
496 if (!IsConst(mir->ssa_rep->uses[1])) {
497 break;
498 }
499 FALLTHROUGH_INTENDED;
500 case Instruction::IF_EQZ:
501 case Instruction::IF_NEZ:
502 case Instruction::IF_LTZ:
503 case Instruction::IF_GEZ:
504 case Instruction::IF_GTZ:
505 case Instruction::IF_LEZ:
506 // Result known at compile time?
507 if (IsConst(mir->ssa_rep->uses[0])) {
508 int32_t rhs = (mir->ssa_rep->num_uses == 2) ? ConstantValue(mir->ssa_rep->uses[1]) : 0;
509 bool is_taken = EvaluateBranch(opcode, ConstantValue(mir->ssa_rep->uses[0]), rhs);
510 BasicBlockId edge_to_kill = is_taken ? bb->fall_through : bb->taken;
511 if (is_taken) {
512 // Replace with GOTO.
513 bb->fall_through = NullBasicBlockId;
514 mir->dalvikInsn.opcode = Instruction::GOTO;
515 mir->dalvikInsn.vA =
516 IsInstructionIfCc(opcode) ? mir->dalvikInsn.vC : mir->dalvikInsn.vB;
517 } else {
518 // Make NOP.
519 bb->taken = NullBasicBlockId;
520 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
521 }
522 mir->ssa_rep->num_uses = 0;
523 BasicBlock* successor_to_unlink = GetBasicBlock(edge_to_kill);
524 successor_to_unlink->ErasePredecessor(bb->id);
Vladimir Marko341e4252014-12-19 10:29:51 +0000525 // We have changed the graph structure.
526 dfs_orders_up_to_date_ = false;
527 domination_up_to_date_ = false;
528 topological_order_up_to_date_ = false;
529 // Keep MIR SSA rep, the worst that can happen is a Phi with just 1 input.
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000530 }
531 break;
buzbee311ca162013-02-28 15:56:43 -0800532 case Instruction::CMPL_FLOAT:
533 case Instruction::CMPL_DOUBLE:
534 case Instruction::CMPG_FLOAT:
535 case Instruction::CMPG_DOUBLE:
536 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700537 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800538 // Bitcode doesn't allow this optimization.
539 break;
540 }
541 if (mir->next != NULL) {
542 MIR* mir_next = mir->next;
buzbee311ca162013-02-28 15:56:43 -0800543 // Make sure result of cmp is used by next insn and nowhere else
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700544 if (IsInstructionIfCcZ(mir_next->dalvikInsn.opcode) &&
buzbee311ca162013-02-28 15:56:43 -0800545 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
546 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
Vladimir Markoa1a70742014-03-03 10:28:05 +0000547 mir_next->meta.ccode = ConditionCodeForIfCcZ(mir_next->dalvikInsn.opcode);
Brian Carlstromdf629502013-07-17 22:39:56 -0700548 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800549 case Instruction::CMPL_FLOAT:
550 mir_next->dalvikInsn.opcode =
551 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
552 break;
553 case Instruction::CMPL_DOUBLE:
554 mir_next->dalvikInsn.opcode =
555 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
556 break;
557 case Instruction::CMPG_FLOAT:
558 mir_next->dalvikInsn.opcode =
559 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
560 break;
561 case Instruction::CMPG_DOUBLE:
562 mir_next->dalvikInsn.opcode =
563 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
564 break;
565 case Instruction::CMP_LONG:
566 mir_next->dalvikInsn.opcode =
567 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
568 break;
569 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
570 }
571 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
Zheng Xub218c852014-12-08 18:18:01 +0800572 // Clear use count of temp VR.
573 use_counts_[mir->ssa_rep->defs[0]] = 0;
574 raw_use_counts_[mir->ssa_rep->defs[0]] = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700575 // Copy the SSA information that is relevant.
buzbee311ca162013-02-28 15:56:43 -0800576 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
577 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
buzbee311ca162013-02-28 15:56:43 -0800578 mir_next->ssa_rep->num_defs = 0;
579 mir->ssa_rep->num_uses = 0;
580 mir->ssa_rep->num_defs = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700581 // Copy in the decoded instruction information for potential SSA re-creation.
582 mir_next->dalvikInsn.vA = mir->dalvikInsn.vB;
583 mir_next->dalvikInsn.vB = mir->dalvikInsn.vC;
buzbee311ca162013-02-28 15:56:43 -0800584 }
585 }
586 break;
buzbee311ca162013-02-28 15:56:43 -0800587 default:
588 break;
589 }
590 // Is this the select pattern?
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800591 // TODO: flesh out support for Mips. NOTE: llvm's select op doesn't quite work here.
buzbee311ca162013-02-28 15:56:43 -0800592 // TUNING: expand to support IF_xx compare & branches
Elliott Hughes956af0f2014-12-11 14:34:28 -0800593 if ((cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2 ||
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100594 cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) &&
Vladimir Markoa1a70742014-03-03 10:28:05 +0000595 IsInstructionIfCcZ(mir->dalvikInsn.opcode)) {
buzbee0d829482013-10-11 15:24:55 -0700596 BasicBlock* ft = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800597 DCHECK(ft != NULL);
buzbee0d829482013-10-11 15:24:55 -0700598 BasicBlock* ft_ft = GetBasicBlock(ft->fall_through);
599 BasicBlock* ft_tk = GetBasicBlock(ft->taken);
buzbee311ca162013-02-28 15:56:43 -0800600
buzbee0d829482013-10-11 15:24:55 -0700601 BasicBlock* tk = GetBasicBlock(bb->taken);
buzbee311ca162013-02-28 15:56:43 -0800602 DCHECK(tk != NULL);
buzbee0d829482013-10-11 15:24:55 -0700603 BasicBlock* tk_ft = GetBasicBlock(tk->fall_through);
604 BasicBlock* tk_tk = GetBasicBlock(tk->taken);
buzbee311ca162013-02-28 15:56:43 -0800605
606 /*
607 * In the select pattern, the taken edge goes to a block that unconditionally
608 * transfers to the rejoin block and the fall_though edge goes to a block that
609 * unconditionally falls through to the rejoin block.
610 */
611 if ((tk_ft == NULL) && (ft_tk == NULL) && (tk_tk == ft_ft) &&
612 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
613 /*
Vladimir Marko8b858e12014-11-27 14:52:37 +0000614 * Okay - we have the basic diamond shape.
buzbee311ca162013-02-28 15:56:43 -0800615 */
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100616
617 // TODO: Add logic for LONG.
buzbee311ca162013-02-28 15:56:43 -0800618 // Are the block bodies something we can handle?
619 if ((ft->first_mir_insn == ft->last_mir_insn) &&
620 (tk->first_mir_insn != tk->last_mir_insn) &&
621 (tk->first_mir_insn->next == tk->last_mir_insn) &&
622 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
623 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
624 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
625 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
626 // Almost there. Are the instructions targeting the same vreg?
627 MIR* if_true = tk->first_mir_insn;
628 MIR* if_false = ft->first_mir_insn;
629 // It's possible that the target of the select isn't used - skip those (rare) cases.
630 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
631 if ((phi != NULL) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
632 /*
633 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
634 * Phi node in the merge block and delete it (while using the SSA name
635 * of the merge as the target of the SELECT. Delete both taken and
636 * fallthrough blocks, and set fallthrough to merge block.
637 * NOTE: not updating other dataflow info (no longer used at this point).
638 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
639 */
Vladimir Markoa1a70742014-03-03 10:28:05 +0000640 mir->meta.ccode = ConditionCodeForIfCcZ(mir->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800641 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
642 bool const_form = (SelectKind(if_true) == kSelectConst);
643 if ((SelectKind(if_true) == kSelectMove)) {
644 if (IsConst(if_true->ssa_rep->uses[0]) &&
645 IsConst(if_false->ssa_rep->uses[0])) {
646 const_form = true;
647 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
648 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
649 }
650 }
651 if (const_form) {
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800652 /*
653 * TODO: If both constants are the same value, then instead of generating
654 * a select, we should simply generate a const bytecode. This should be
655 * considered after inlining which can lead to CFG of this form.
656 */
buzbee311ca162013-02-28 15:56:43 -0800657 // "true" set val in vB
658 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
659 // "false" set val in vC
660 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
661 } else {
662 DCHECK_EQ(SelectKind(if_true), kSelectMove);
663 DCHECK_EQ(SelectKind(if_false), kSelectMove);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000664 int32_t* src_ssa = arena_->AllocArray<int32_t>(3, kArenaAllocDFInfo);
buzbee311ca162013-02-28 15:56:43 -0800665 src_ssa[0] = mir->ssa_rep->uses[0];
666 src_ssa[1] = if_true->ssa_rep->uses[0];
667 src_ssa[2] = if_false->ssa_rep->uses[0];
668 mir->ssa_rep->uses = src_ssa;
669 mir->ssa_rep->num_uses = 3;
670 }
Vladimir Markoe490b012015-02-24 11:32:46 +0000671 AllocateSSADefData(mir, 1);
buzbee311ca162013-02-28 15:56:43 -0800672 /*
673 * There is usually a Phi node in the join block for our two cases. If the
674 * Phi node only contains our two cases as input, we will use the result
675 * SSA name of the Phi node as our select result and delete the Phi. If
676 * the Phi node has more than two operands, we will arbitrarily use the SSA
Vladimir Marko341e4252014-12-19 10:29:51 +0000677 * name of the "false" path, delete the SSA name of the "true" path from the
buzbee311ca162013-02-28 15:56:43 -0800678 * Phi node (and fix up the incoming arc list).
679 */
680 if (phi->ssa_rep->num_uses == 2) {
681 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000682 // Rather than changing the Phi to kMirOpNop, remove it completely.
683 // This avoids leaving other Phis after kMirOpNop (i.e. a non-Phi) insn.
684 tk_tk->RemoveMIR(phi);
685 int dead_false_def = if_false->ssa_rep->defs[0];
686 raw_use_counts_[dead_false_def] = use_counts_[dead_false_def] = 0;
buzbee311ca162013-02-28 15:56:43 -0800687 } else {
Vladimir Marko341e4252014-12-19 10:29:51 +0000688 int live_def = if_false->ssa_rep->defs[0];
buzbee311ca162013-02-28 15:56:43 -0800689 mir->ssa_rep->defs[0] = live_def;
buzbee311ca162013-02-28 15:56:43 -0800690 }
Vladimir Marko341e4252014-12-19 10:29:51 +0000691 int dead_true_def = if_true->ssa_rep->defs[0];
692 raw_use_counts_[dead_true_def] = use_counts_[dead_true_def] = 0;
Vladimir Marko6e071832015-03-25 11:13:39 +0000693 // Update ending vreg->sreg map for GC maps generation.
694 int def_vreg = SRegToVReg(mir->ssa_rep->defs[0]);
695 bb->data_flow_info->vreg_to_ssa_map_exit[def_vreg] = mir->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000696 // We want to remove ft and tk and link bb directly to ft_ft. First, we need
697 // to update all Phi inputs correctly with UpdatePredecessor(ft->id, bb->id)
698 // since the live_def above comes from ft->first_mir_insn (if_false).
699 DCHECK(if_false == ft->first_mir_insn);
700 ft_ft->UpdatePredecessor(ft->id, bb->id);
701 // Correct the rest of the links between bb, ft and ft_ft.
702 ft->ErasePredecessor(bb->id);
703 ft->fall_through = NullBasicBlockId;
704 bb->fall_through = ft_ft->id;
705 // Now we can kill tk and ft.
706 tk->Kill(this);
707 ft->Kill(this);
708 // NOTE: DFS order, domination info and topological order are still usable
709 // despite the newly dead blocks.
buzbee311ca162013-02-28 15:56:43 -0800710 }
711 }
712 }
713 }
714 }
buzbee1da1e2f2013-11-15 13:37:01 -0800715 bb = ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) ? NextDominatedBlock(bb) : NULL;
buzbee311ca162013-02-28 15:56:43 -0800716 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100717 if (use_lvn && UNLIKELY(!global_valnum->Good())) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100718 LOG(WARNING) << "LVN overflow in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
719 }
buzbee311ca162013-02-28 15:56:43 -0800720
buzbee311ca162013-02-28 15:56:43 -0800721 return true;
722}
723
buzbee311ca162013-02-28 15:56:43 -0800724/* Collect stats on number of checks removed */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700725void MIRGraph::CountChecks(class BasicBlock* bb) {
buzbee862a7602013-04-05 10:58:54 -0700726 if (bb->data_flow_info != NULL) {
727 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
728 if (mir->ssa_rep == NULL) {
729 continue;
buzbee311ca162013-02-28 15:56:43 -0800730 }
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700731 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee862a7602013-04-05 10:58:54 -0700732 if (df_attributes & DF_HAS_NULL_CHKS) {
733 checkstats_->null_checks++;
734 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
735 checkstats_->null_checks_eliminated++;
736 }
737 }
738 if (df_attributes & DF_HAS_RANGE_CHKS) {
739 checkstats_->range_checks++;
740 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
741 checkstats_->range_checks_eliminated++;
742 }
buzbee311ca162013-02-28 15:56:43 -0800743 }
744 }
745 }
buzbee311ca162013-02-28 15:56:43 -0800746}
747
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700748/* Try to make common case the fallthrough path. */
buzbee0d829482013-10-11 15:24:55 -0700749bool MIRGraph::LayoutBlocks(BasicBlock* bb) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700750 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback.
buzbee311ca162013-02-28 15:56:43 -0800751 if (!bb->explicit_throw) {
752 return false;
753 }
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700754
755 // If we visited it, we are done.
756 if (bb->visited) {
757 return false;
758 }
759 bb->visited = true;
760
buzbee311ca162013-02-28 15:56:43 -0800761 BasicBlock* walker = bb;
762 while (true) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700763 // Check termination conditions.
buzbee311ca162013-02-28 15:56:43 -0800764 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
765 break;
766 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100767 DCHECK(!walker->predecessors.empty());
768 BasicBlock* prev = GetBasicBlock(walker->predecessors[0]);
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700769
770 // If we visited the predecessor, we are done.
771 if (prev->visited) {
772 return false;
773 }
774 prev->visited = true;
775
buzbee311ca162013-02-28 15:56:43 -0800776 if (prev->conditional_branch) {
buzbee0d829482013-10-11 15:24:55 -0700777 if (GetBasicBlock(prev->fall_through) == walker) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700778 // Already done - return.
buzbee311ca162013-02-28 15:56:43 -0800779 break;
780 }
buzbee0d829482013-10-11 15:24:55 -0700781 DCHECK_EQ(walker, GetBasicBlock(prev->taken));
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700782 // Got one. Flip it and exit.
buzbee311ca162013-02-28 15:56:43 -0800783 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
784 switch (opcode) {
785 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
786 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
787 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
788 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
789 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
790 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
791 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
792 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
793 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
794 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
795 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
796 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
797 default: LOG(FATAL) << "Unexpected opcode " << opcode;
798 }
799 prev->last_mir_insn->dalvikInsn.opcode = opcode;
buzbee0d829482013-10-11 15:24:55 -0700800 BasicBlockId t_bb = prev->taken;
buzbee311ca162013-02-28 15:56:43 -0800801 prev->taken = prev->fall_through;
802 prev->fall_through = t_bb;
803 break;
804 }
805 walker = prev;
806 }
807 return false;
808}
809
810/* Combine any basic blocks terminated by instructions that we now know can't throw */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700811void MIRGraph::CombineBlocks(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800812 // Loop here to allow combining a sequence of blocks
Vladimir Marko312eb252014-10-07 15:01:57 +0100813 while ((bb->block_type == kDalvikByteCode) &&
814 (bb->last_mir_insn != nullptr) &&
815 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) == kMirOpCheck)) {
816 MIR* mir = bb->last_mir_insn;
817 DCHECK(bb->first_mir_insn != nullptr);
818
Vladimir Marko315cc202014-12-18 17:01:02 +0000819 // Get the paired insn and check if it can still throw.
Vladimir Marko312eb252014-10-07 15:01:57 +0100820 MIR* throw_insn = mir->meta.throw_insn;
Vladimir Marko315cc202014-12-18 17:01:02 +0000821 if (CanThrow(throw_insn)) {
buzbee311ca162013-02-28 15:56:43 -0800822 break;
823 }
824
buzbee311ca162013-02-28 15:56:43 -0800825 // OK - got one. Combine
buzbee0d829482013-10-11 15:24:55 -0700826 BasicBlock* bb_next = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800827 DCHECK(!bb_next->catch_entry);
Vladimir Marko312eb252014-10-07 15:01:57 +0100828 DCHECK_EQ(bb_next->predecessors.size(), 1u);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700829
830 // Now move instructions from bb_next to bb. Start off with doing a sanity check
831 // that kMirOpCheck's throw instruction is first one in the bb_next.
buzbee311ca162013-02-28 15:56:43 -0800832 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700833 // Now move all instructions (throw instruction to last one) from bb_next to bb.
834 MIR* last_to_move = bb_next->last_mir_insn;
835 bb_next->RemoveMIRList(throw_insn, last_to_move);
836 bb->InsertMIRListAfter(bb->last_mir_insn, throw_insn, last_to_move);
837 // The kMirOpCheck instruction is not needed anymore.
838 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
839 bb->RemoveMIR(mir);
840
Vladimir Marko312eb252014-10-07 15:01:57 +0100841 // Before we overwrite successors, remove their predecessor links to bb.
842 bb_next->ErasePredecessor(bb->id);
843 if (bb->taken != NullBasicBlockId) {
844 DCHECK_EQ(bb->successor_block_list_type, kNotUsed);
845 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
846 // bb->taken will be overwritten below.
847 DCHECK_EQ(bb_taken->block_type, kExceptionHandling);
848 DCHECK_EQ(bb_taken->predecessors.size(), 1u);
849 DCHECK_EQ(bb_taken->predecessors[0], bb->id);
850 bb_taken->predecessors.clear();
851 bb_taken->block_type = kDead;
852 DCHECK(bb_taken->data_flow_info == nullptr);
853 } else {
854 DCHECK_EQ(bb->successor_block_list_type, kCatch);
855 for (SuccessorBlockInfo* succ_info : bb->successor_blocks) {
856 if (succ_info->block != NullBasicBlockId) {
857 BasicBlock* succ_bb = GetBasicBlock(succ_info->block);
858 DCHECK(succ_bb->catch_entry);
859 succ_bb->ErasePredecessor(bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100860 }
861 }
862 }
buzbee311ca162013-02-28 15:56:43 -0800863 // Use the successor info from the next block
buzbee0d829482013-10-11 15:24:55 -0700864 bb->successor_block_list_type = bb_next->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100865 bb->successor_blocks.swap(bb_next->successor_blocks); // Swap instead of copying.
Vladimir Marko312eb252014-10-07 15:01:57 +0100866 bb_next->successor_block_list_type = kNotUsed;
buzbee311ca162013-02-28 15:56:43 -0800867 // Use the ending block linkage from the next block
868 bb->fall_through = bb_next->fall_through;
Vladimir Marko312eb252014-10-07 15:01:57 +0100869 bb_next->fall_through = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800870 bb->taken = bb_next->taken;
Vladimir Marko312eb252014-10-07 15:01:57 +0100871 bb_next->taken = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800872 /*
Junmo Parkf1770fd2014-08-12 09:34:54 +0900873 * If lower-half of pair of blocks to combine contained
874 * a return or a conditional branch or an explicit throw,
875 * move the flag to the newly combined block.
buzbee311ca162013-02-28 15:56:43 -0800876 */
877 bb->terminated_by_return = bb_next->terminated_by_return;
Junmo Parkf1770fd2014-08-12 09:34:54 +0900878 bb->conditional_branch = bb_next->conditional_branch;
879 bb->explicit_throw = bb_next->explicit_throw;
Vladimir Marko312eb252014-10-07 15:01:57 +0100880 // Merge the use_lvn flag.
881 bb->use_lvn |= bb_next->use_lvn;
882
883 // Kill the unused block.
884 bb_next->data_flow_info = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800885
886 /*
887 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
888 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
Vladimir Marko312eb252014-10-07 15:01:57 +0100889 * NOTE: GVN uses bb->data_flow_info->live_in_v which is unaffected by the block merge.
buzbee311ca162013-02-28 15:56:43 -0800890 */
891
Vladimir Marko312eb252014-10-07 15:01:57 +0100892 // Kill bb_next and remap now-dead id to parent.
buzbee311ca162013-02-28 15:56:43 -0800893 bb_next->block_type = kDead;
Vladimir Marko312eb252014-10-07 15:01:57 +0100894 bb_next->data_flow_info = nullptr; // Must be null for dead blocks. (Relied on by the GVN.)
buzbee1fd33462013-03-25 13:40:45 -0700895 block_id_map_.Overwrite(bb_next->id, bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100896 // Update predecessors in children.
897 ChildBlockIterator iter(bb, this);
898 for (BasicBlock* child = iter.Next(); child != nullptr; child = iter.Next()) {
899 child->UpdatePredecessor(bb_next->id, bb->id);
900 }
901
Vladimir Markoffda4992014-12-18 17:05:58 +0000902 // DFS orders, domination and topological order are not up to date anymore.
Vladimir Marko312eb252014-10-07 15:01:57 +0100903 dfs_orders_up_to_date_ = false;
Vladimir Markoffda4992014-12-18 17:05:58 +0000904 domination_up_to_date_ = false;
905 topological_order_up_to_date_ = false;
buzbee311ca162013-02-28 15:56:43 -0800906
907 // Now, loop back and see if we can keep going
908 }
buzbee311ca162013-02-28 15:56:43 -0800909}
910
Vladimir Marko67c72b82014-10-09 12:26:10 +0100911bool MIRGraph::EliminateNullChecksGate() {
912 if ((cu_->disable_opt & (1 << kNullCheckElimination)) != 0 ||
913 (merged_df_flags_ & DF_HAS_NULL_CHKS) == 0) {
914 return false;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000915 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100916
Vladimir Marko67c72b82014-10-09 12:26:10 +0100917 DCHECK(temp_scoped_alloc_.get() == nullptr);
918 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700919 temp_.nce.num_vregs = GetNumOfCodeAndTempVRs();
Vladimir Markof585e542014-11-21 13:41:32 +0000920 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
921 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000922 temp_.nce.ending_vregs_to_check_matrix =
923 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +0000924 std::fill_n(temp_.nce.ending_vregs_to_check_matrix, GetNumBlocks(), nullptr);
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700925
926 // reset MIR_MARK
927 AllNodesIterator iter(this);
928 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
929 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
930 mir->optimization_flags &= ~MIR_MARK;
931 }
932 }
933
Vladimir Marko67c72b82014-10-09 12:26:10 +0100934 return true;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000935}
936
buzbee1da1e2f2013-11-15 13:37:01 -0800937/*
Vladimir Marko67c72b82014-10-09 12:26:10 +0100938 * Eliminate unnecessary null checks for a basic block.
buzbee1da1e2f2013-11-15 13:37:01 -0800939 */
Vladimir Marko67c72b82014-10-09 12:26:10 +0100940bool MIRGraph::EliminateNullChecks(BasicBlock* bb) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100941 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
942 // Ignore the kExitBlock as well.
943 DCHECK(bb->first_mir_insn == nullptr);
944 return false;
945 }
buzbee311ca162013-02-28 15:56:43 -0800946
Vladimir Markof585e542014-11-21 13:41:32 +0000947 ArenaBitVector* vregs_to_check = temp_.nce.work_vregs_to_check;
Vladimir Marko67c72b82014-10-09 12:26:10 +0100948 /*
949 * Set initial state. Catch blocks don't need any special treatment.
950 */
951 if (bb->block_type == kEntryBlock) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100952 vregs_to_check->ClearAllBits();
Vladimir Marko67c72b82014-10-09 12:26:10 +0100953 // Assume all ins are objects.
954 for (uint16_t in_reg = GetFirstInVR();
955 in_reg < GetNumOfCodeVRs(); in_reg++) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100956 vregs_to_check->SetBit(in_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100957 }
958 if ((cu_->access_flags & kAccStatic) == 0) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100959 // If non-static method, mark "this" as non-null.
Vladimir Marko67c72b82014-10-09 12:26:10 +0100960 int this_reg = GetFirstInVR();
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100961 vregs_to_check->ClearBit(this_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100962 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100963 } else {
964 DCHECK_EQ(bb->block_type, kDalvikByteCode);
965 // Starting state is union of all incoming arcs.
966 bool copied_first = false;
967 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +0000968 if (temp_.nce.ending_vregs_to_check_matrix[pred_id] == nullptr) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100969 continue;
970 }
971 BasicBlock* pred_bb = GetBasicBlock(pred_id);
972 DCHECK(pred_bb != nullptr);
973 MIR* null_check_insn = nullptr;
974 if (pred_bb->block_type == kDalvikByteCode) {
975 // Check to see if predecessor had an explicit null-check.
976 MIR* last_insn = pred_bb->last_mir_insn;
977 if (last_insn != nullptr) {
978 Instruction::Code last_opcode = last_insn->dalvikInsn.opcode;
979 if ((last_opcode == Instruction::IF_EQZ && pred_bb->fall_through == bb->id) ||
980 (last_opcode == Instruction::IF_NEZ && pred_bb->taken == bb->id)) {
981 // Remember the null check insn if there's no other predecessor requiring null check.
982 if (!copied_first || !vregs_to_check->IsBitSet(last_insn->dalvikInsn.vA)) {
983 null_check_insn = last_insn;
984 }
buzbee1da1e2f2013-11-15 13:37:01 -0800985 }
Ian Rogers22fd6a02013-06-13 15:06:54 -0700986 }
987 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100988 if (!copied_first) {
989 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +0000990 vregs_to_check->Copy(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100991 } else {
Vladimir Markof585e542014-11-21 13:41:32 +0000992 vregs_to_check->Union(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100993 }
994 if (null_check_insn != nullptr) {
995 vregs_to_check->ClearBit(null_check_insn->dalvikInsn.vA);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100996 }
997 }
998 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
buzbee311ca162013-02-28 15:56:43 -0800999 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001000 // At this point, vregs_to_check shows which sregs have an object definition with
Vladimir Marko67c72b82014-10-09 12:26:10 +01001001 // no intervening uses.
buzbee311ca162013-02-28 15:56:43 -08001002
1003 // Walk through the instruction in the block, updating as necessary
1004 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
Jean Christophe Beylercc794c32014-05-02 09:34:13 -07001005 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -08001006
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -07001007 if ((df_attributes & DF_NULL_TRANSFER_N) != 0u) {
1008 // The algorithm was written in a phi agnostic way.
1009 continue;
1010 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001011
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001012 // Might need a null check?
1013 if (df_attributes & DF_HAS_NULL_CHKS) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001014 int src_vreg;
1015 if (df_attributes & DF_NULL_CHK_OUT0) {
1016 DCHECK_NE(df_attributes & DF_IS_INVOKE, 0u);
1017 src_vreg = mir->dalvikInsn.vC;
1018 } else if (df_attributes & DF_NULL_CHK_B) {
1019 DCHECK_NE(df_attributes & DF_REF_B, 0u);
1020 src_vreg = mir->dalvikInsn.vB;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001021 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001022 DCHECK_NE(df_attributes & DF_NULL_CHK_A, 0u);
1023 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1024 src_vreg = mir->dalvikInsn.vA;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001025 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001026 if (!vregs_to_check->IsBitSet(src_vreg)) {
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001027 // Eliminate the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001028 mir->optimization_flags |= MIR_MARK;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001029 } else {
1030 // Do the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001031 mir->optimization_flags &= ~MIR_MARK;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001032 // Mark src_vreg as null-checked.
1033 vregs_to_check->ClearBit(src_vreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001034 }
1035 }
1036
1037 if ((df_attributes & DF_A_WIDE) ||
1038 (df_attributes & (DF_REF_A | DF_SETS_CONST | DF_NULL_TRANSFER)) == 0) {
1039 continue;
1040 }
1041
1042 /*
1043 * First, mark all object definitions as requiring null check.
1044 * Note: we can't tell if a CONST definition might be used as an object, so treat
1045 * them all as object definitions.
1046 */
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001047 if ((df_attributes & (DF_DA | DF_REF_A)) == (DF_DA | DF_REF_A) ||
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001048 (df_attributes & DF_SETS_CONST)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001049 vregs_to_check->SetBit(mir->dalvikInsn.vA);
buzbee4db179d2013-10-23 12:16:39 -07001050 }
1051
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001052 // Then, remove mark from all object definitions we know are non-null.
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001053 if (df_attributes & DF_NON_NULL_DST) {
1054 // Mark target of NEW* as non-null
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001055 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1056 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001057 }
1058
buzbee311ca162013-02-28 15:56:43 -08001059 // Mark non-null returns from invoke-style NEW*
1060 if (df_attributes & DF_NON_NULL_RET) {
1061 MIR* next_mir = mir->next;
1062 // Next should be an MOVE_RESULT_OBJECT
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001063 if (UNLIKELY(next_mir == nullptr)) {
1064 // The MethodVerifier makes sure there's no MOVE_RESULT at the catch entry or branch
1065 // target, so the MOVE_RESULT cannot be broken away into another block.
1066 LOG(WARNING) << "Unexpected end of block following new";
1067 } else if (UNLIKELY(next_mir->dalvikInsn.opcode != Instruction::MOVE_RESULT_OBJECT)) {
1068 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
buzbee311ca162013-02-28 15:56:43 -08001069 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001070 // Mark as null checked.
1071 vregs_to_check->ClearBit(next_mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001072 }
1073 }
1074
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001075 // Propagate null check state on register copies.
1076 if (df_attributes & DF_NULL_TRANSFER_0) {
1077 DCHECK_EQ(df_attributes | ~(DF_DA | DF_REF_A | DF_UB | DF_REF_B), static_cast<uint64_t>(-1));
1078 if (vregs_to_check->IsBitSet(mir->dalvikInsn.vB)) {
1079 vregs_to_check->SetBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001080 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001081 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001082 }
1083 }
buzbee311ca162013-02-28 15:56:43 -08001084 }
1085
1086 // Did anything change?
Vladimir Markobfea9c22014-01-17 17:49:33 +00001087 bool nce_changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001088 ArenaBitVector* old_ending_ssa_regs_to_check = temp_.nce.ending_vregs_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001089 if (old_ending_ssa_regs_to_check == nullptr) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001090 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001091 nce_changed = vregs_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001092 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001093 // Create a new vregs_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001094 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1095 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001096 } else if (!vregs_to_check->SameBitsSet(old_ending_ssa_regs_to_check)) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001097 nce_changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001098 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
1099 temp_.nce.work_vregs_to_check = old_ending_ssa_regs_to_check; // Reuse for next BB.
buzbee311ca162013-02-28 15:56:43 -08001100 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001101 return nce_changed;
buzbee311ca162013-02-28 15:56:43 -08001102}
1103
Vladimir Marko67c72b82014-10-09 12:26:10 +01001104void MIRGraph::EliminateNullChecksEnd() {
1105 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001106 temp_.nce.num_vregs = 0u;
1107 temp_.nce.work_vregs_to_check = nullptr;
1108 temp_.nce.ending_vregs_to_check_matrix = nullptr;
Vladimir Marko67c72b82014-10-09 12:26:10 +01001109 DCHECK(temp_scoped_alloc_.get() != nullptr);
1110 temp_scoped_alloc_.reset();
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001111
1112 // converge MIR_MARK with MIR_IGNORE_NULL_CHECK
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001113 AllNodesIterator iter(this);
1114 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1115 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001116 constexpr int kMarkToIgnoreNullCheckShift = kMIRMark - kMIRIgnoreNullCheck;
Andreas Gampe785d2f22014-11-03 22:57:30 -08001117 static_assert(kMarkToIgnoreNullCheckShift > 0, "Not a valid right-shift");
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001118 uint16_t mirMarkAdjustedToIgnoreNullCheck =
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001119 (mir->optimization_flags & MIR_MARK) >> kMarkToIgnoreNullCheckShift;
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001120 mir->optimization_flags |= mirMarkAdjustedToIgnoreNullCheck;
1121 }
1122 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001123}
1124
Vladimir Markoe490b012015-02-24 11:32:46 +00001125void MIRGraph::InferTypesStart() {
1126 DCHECK(temp_scoped_alloc_ != nullptr);
1127 temp_.ssa.ti = new (temp_scoped_alloc_.get()) TypeInference(this, temp_scoped_alloc_.get());
1128}
1129
Vladimir Marko67c72b82014-10-09 12:26:10 +01001130/*
1131 * Perform type and size inference for a basic block.
1132 */
1133bool MIRGraph::InferTypes(BasicBlock* bb) {
1134 if (bb->data_flow_info == nullptr) return false;
1135
Vladimir Markoe490b012015-02-24 11:32:46 +00001136 DCHECK(temp_.ssa.ti != nullptr);
1137 return temp_.ssa.ti->Apply(bb);
1138}
Vladimir Marko67c72b82014-10-09 12:26:10 +01001139
Vladimir Markoe490b012015-02-24 11:32:46 +00001140void MIRGraph::InferTypesEnd() {
1141 DCHECK(temp_.ssa.ti != nullptr);
1142 temp_.ssa.ti->Finish();
1143 delete temp_.ssa.ti;
1144 temp_.ssa.ti = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001145}
1146
1147bool MIRGraph::EliminateClassInitChecksGate() {
1148 if ((cu_->disable_opt & (1 << kClassInitCheckElimination)) != 0 ||
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001149 (merged_df_flags_ & DF_CLINIT) == 0) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001150 return false;
1151 }
1152
Vladimir Markobfea9c22014-01-17 17:49:33 +00001153 DCHECK(temp_scoped_alloc_.get() == nullptr);
1154 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1155
1156 // Each insn we use here has at least 2 code units, offset/2 will be a unique index.
Razvan A Lupusoru75035972014-09-11 15:24:59 -07001157 const size_t end = (GetNumDalvikInsns() + 1u) / 2u;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001158 temp_.cice.indexes = temp_scoped_alloc_->AllocArray<uint16_t>(end, kArenaAllocGrowableArray);
Vladimir Markof585e542014-11-21 13:41:32 +00001159 std::fill_n(temp_.cice.indexes, end, 0xffffu);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001160
1161 uint32_t unique_class_count = 0u;
1162 {
1163 // Get unique_class_count and store indexes in temp_insn_data_ using a map on a nested
1164 // ScopedArenaAllocator.
1165
1166 // Embed the map value in the entry to save space.
1167 struct MapEntry {
1168 // Map key: the class identified by the declaring dex file and type index.
1169 const DexFile* declaring_dex_file;
1170 uint16_t declaring_class_idx;
1171 // Map value: index into bit vectors of classes requiring initialization checks.
1172 uint16_t index;
1173 };
1174 struct MapEntryComparator {
1175 bool operator()(const MapEntry& lhs, const MapEntry& rhs) const {
1176 if (lhs.declaring_class_idx != rhs.declaring_class_idx) {
1177 return lhs.declaring_class_idx < rhs.declaring_class_idx;
1178 }
1179 return lhs.declaring_dex_file < rhs.declaring_dex_file;
1180 }
1181 };
1182
Vladimir Markobfea9c22014-01-17 17:49:33 +00001183 ScopedArenaAllocator allocator(&cu_->arena_stack);
Vladimir Marko69f08ba2014-04-11 12:28:11 +01001184 ScopedArenaSet<MapEntry, MapEntryComparator> class_to_index_map(MapEntryComparator(),
1185 allocator.Adapter());
Vladimir Markobfea9c22014-01-17 17:49:33 +00001186
1187 // First, find all SGET/SPUTs that may need class initialization checks, record INVOKE_STATICs.
1188 AllNodesIterator iter(this);
1189 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001190 if (bb->block_type == kDalvikByteCode) {
1191 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001192 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001193 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001194 if (!field_info.IsReferrersClass()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001195 DCHECK_LT(class_to_index_map.size(), 0xffffu);
1196 MapEntry entry = {
1197 // Treat unresolved fields as if each had its own class.
1198 field_info.IsResolved() ? field_info.DeclaringDexFile()
1199 : nullptr,
1200 field_info.IsResolved() ? field_info.DeclaringClassIndex()
1201 : field_info.FieldIndex(),
1202 static_cast<uint16_t>(class_to_index_map.size())
1203 };
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001204 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001205 // Using offset/2 for index into temp_.cice.indexes.
1206 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001207 }
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001208 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001209 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
1210 DCHECK(method_info.IsStatic());
1211 if (method_info.FastPath() && !method_info.IsReferrersClass()) {
1212 MapEntry entry = {
1213 method_info.DeclaringDexFile(),
1214 method_info.DeclaringClassIndex(),
1215 static_cast<uint16_t>(class_to_index_map.size())
1216 };
1217 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001218 // Using offset/2 for index into temp_.cice.indexes.
1219 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001220 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001221 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001222 }
1223 }
1224 }
1225 unique_class_count = static_cast<uint32_t>(class_to_index_map.size());
1226 }
1227
1228 if (unique_class_count == 0u) {
1229 // All SGET/SPUTs refer to initialized classes. Nothing to do.
Vladimir Markof585e542014-11-21 13:41:32 +00001230 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001231 temp_scoped_alloc_.reset();
1232 return false;
1233 }
1234
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001235 // 2 bits for each class: is class initialized, is class in dex cache.
Vladimir Markof585e542014-11-21 13:41:32 +00001236 temp_.cice.num_class_bits = 2u * unique_class_count;
1237 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1238 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001239 temp_.cice.ending_classes_to_check_matrix =
1240 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +00001241 std::fill_n(temp_.cice.ending_classes_to_check_matrix, GetNumBlocks(), nullptr);
1242 DCHECK_GT(temp_.cice.num_class_bits, 0u);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001243 return true;
1244}
1245
1246/*
1247 * Eliminate unnecessary class initialization checks for a basic block.
1248 */
1249bool MIRGraph::EliminateClassInitChecks(BasicBlock* bb) {
1250 DCHECK_EQ((cu_->disable_opt & (1 << kClassInitCheckElimination)), 0u);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001251 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
1252 // Ignore the kExitBlock as well.
1253 DCHECK(bb->first_mir_insn == nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001254 return false;
1255 }
1256
1257 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +01001258 * Set initial state. Catch blocks don't need any special treatment.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001259 */
Vladimir Markof585e542014-11-21 13:41:32 +00001260 ArenaBitVector* classes_to_check = temp_.cice.work_classes_to_check;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001261 DCHECK(classes_to_check != nullptr);
Vladimir Marko0a810d22014-07-11 14:44:36 +01001262 if (bb->block_type == kEntryBlock) {
Vladimir Markof585e542014-11-21 13:41:32 +00001263 classes_to_check->SetInitialBits(temp_.cice.num_class_bits);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001264 } else {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001265 // Starting state is union of all incoming arcs.
1266 bool copied_first = false;
1267 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +00001268 if (temp_.cice.ending_classes_to_check_matrix[pred_id] == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001269 continue;
1270 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001271 if (!copied_first) {
1272 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001273 classes_to_check->Copy(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001274 } else {
Vladimir Markof585e542014-11-21 13:41:32 +00001275 classes_to_check->Union(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001276 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001277 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001278 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001279 }
1280 // At this point, classes_to_check shows which classes need clinit checks.
1281
1282 // Walk through the instruction in the block, updating as necessary
1283 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markof585e542014-11-21 13:41:32 +00001284 uint16_t index = temp_.cice.indexes[mir->offset / 2u];
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001285 if (index != 0xffffu) {
1286 bool check_initialization = false;
1287 bool check_dex_cache = false;
1288
1289 // NOTE: index != 0xffff does not guarantee that this is an SGET/SPUT/INVOKE_STATIC.
1290 // Dex instructions with width 1 can have the same offset/2.
1291
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001292 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001293 check_initialization = true;
1294 check_dex_cache = true;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001295 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001296 check_initialization = true;
1297 // NOTE: INVOKE_STATIC doesn't guarantee that the type will be in the dex cache.
1298 }
1299
1300 if (check_dex_cache) {
1301 uint32_t check_dex_cache_index = 2u * index + 1u;
1302 if (!classes_to_check->IsBitSet(check_dex_cache_index)) {
1303 // Eliminate the class init check.
1304 mir->optimization_flags |= MIR_CLASS_IS_IN_DEX_CACHE;
1305 } else {
1306 // Do the class init check.
1307 mir->optimization_flags &= ~MIR_CLASS_IS_IN_DEX_CACHE;
1308 }
1309 classes_to_check->ClearBit(check_dex_cache_index);
1310 }
1311 if (check_initialization) {
1312 uint32_t check_clinit_index = 2u * index;
1313 if (!classes_to_check->IsBitSet(check_clinit_index)) {
1314 // Eliminate the class init check.
1315 mir->optimization_flags |= MIR_CLASS_IS_INITIALIZED;
1316 } else {
1317 // Do the class init check.
1318 mir->optimization_flags &= ~MIR_CLASS_IS_INITIALIZED;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001319 }
1320 // Mark the class as initialized.
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001321 classes_to_check->ClearBit(check_clinit_index);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001322 }
1323 }
1324 }
1325
1326 // Did anything change?
1327 bool changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001328 ArenaBitVector* old_ending_classes_to_check = temp_.cice.ending_classes_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001329 if (old_ending_classes_to_check == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001330 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001331 changed = classes_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001332 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001333 // Create a new classes_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001334 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1335 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Marko5229cf12014-10-09 14:57:59 +01001336 } else if (!classes_to_check->Equal(old_ending_classes_to_check)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001337 changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001338 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
1339 temp_.cice.work_classes_to_check = old_ending_classes_to_check; // Reuse for next BB.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001340 }
1341 return changed;
1342}
1343
1344void MIRGraph::EliminateClassInitChecksEnd() {
1345 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001346 temp_.cice.num_class_bits = 0u;
1347 temp_.cice.work_classes_to_check = nullptr;
1348 temp_.cice.ending_classes_to_check_matrix = nullptr;
1349 DCHECK(temp_.cice.indexes != nullptr);
1350 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001351 DCHECK(temp_scoped_alloc_.get() != nullptr);
1352 temp_scoped_alloc_.reset();
1353}
1354
Vladimir Marko95a05972014-05-30 10:01:32 +01001355bool MIRGraph::ApplyGlobalValueNumberingGate() {
Vladimir Marko415ac882014-09-30 18:09:14 +01001356 if (GlobalValueNumbering::Skip(cu_)) {
Vladimir Marko95a05972014-05-30 10:01:32 +01001357 return false;
1358 }
1359
1360 DCHECK(temp_scoped_alloc_ == nullptr);
1361 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001362 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001363 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001364 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001365 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
Vladimir Markof585e542014-11-21 13:41:32 +00001366 DCHECK(temp_.gvn.gvn == nullptr);
1367 temp_.gvn.gvn = new (temp_scoped_alloc_.get()) GlobalValueNumbering(
1368 cu_, temp_scoped_alloc_.get(), GlobalValueNumbering::kModeGvn);
Vladimir Marko95a05972014-05-30 10:01:32 +01001369 return true;
1370}
1371
1372bool MIRGraph::ApplyGlobalValueNumbering(BasicBlock* bb) {
Vladimir Markof585e542014-11-21 13:41:32 +00001373 DCHECK(temp_.gvn.gvn != nullptr);
1374 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001375 if (lvn != nullptr) {
1376 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1377 lvn->GetValueNumber(mir);
1378 }
1379 }
Vladimir Markof585e542014-11-21 13:41:32 +00001380 bool change = (lvn != nullptr) && temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001381 return change;
1382}
1383
1384void MIRGraph::ApplyGlobalValueNumberingEnd() {
1385 // Perform modifications.
Vladimir Markof585e542014-11-21 13:41:32 +00001386 DCHECK(temp_.gvn.gvn != nullptr);
1387 if (temp_.gvn.gvn->Good()) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001388 temp_.gvn.gvn->StartPostProcessing();
Vladimir Marko415ac882014-09-30 18:09:14 +01001389 if (max_nested_loops_ != 0u) {
Vladimir Marko415ac882014-09-30 18:09:14 +01001390 TopologicalSortIterator iter(this);
1391 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1392 ScopedArenaAllocator allocator(&cu_->arena_stack); // Reclaim memory after each LVN.
Vladimir Markof585e542014-11-21 13:41:32 +00001393 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb, &allocator);
Vladimir Marko415ac882014-09-30 18:09:14 +01001394 if (lvn != nullptr) {
1395 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1396 lvn->GetValueNumber(mir);
1397 }
Vladimir Markof585e542014-11-21 13:41:32 +00001398 bool change = temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko415ac882014-09-30 18:09:14 +01001399 DCHECK(!change) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko95a05972014-05-30 10:01:32 +01001400 }
Vladimir Marko95a05972014-05-30 10:01:32 +01001401 }
1402 }
Vladimir Marko415ac882014-09-30 18:09:14 +01001403 // GVN was successful, running the LVN would be useless.
1404 cu_->disable_opt |= (1u << kLocalValueNumbering);
Vladimir Marko95a05972014-05-30 10:01:32 +01001405 } else {
1406 LOG(WARNING) << "GVN failed for " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001407 cu_->disable_opt |= (1u << kGvnDeadCodeElimination);
Vladimir Marko95a05972014-05-30 10:01:32 +01001408 }
1409
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001410 if ((cu_->disable_opt & (1 << kGvnDeadCodeElimination)) != 0) {
1411 EliminateDeadCodeEnd();
1412 } // else preserve GVN data for CSE.
1413}
1414
1415bool MIRGraph::EliminateDeadCodeGate() {
1416 if ((cu_->disable_opt & (1 << kGvnDeadCodeElimination)) != 0) {
1417 return false;
1418 }
1419 DCHECK(temp_scoped_alloc_ != nullptr);
1420 temp_.gvn.dce = new (temp_scoped_alloc_.get()) GvnDeadCodeElimination(temp_.gvn.gvn,
1421 temp_scoped_alloc_.get());
1422 return true;
1423}
1424
1425bool MIRGraph::EliminateDeadCode(BasicBlock* bb) {
1426 DCHECK(temp_scoped_alloc_ != nullptr);
1427 DCHECK(temp_.gvn.gvn != nullptr);
1428 if (bb->block_type != kDalvikByteCode) {
1429 return false;
1430 }
1431 DCHECK(temp_.gvn.dce != nullptr);
1432 temp_.gvn.dce->Apply(bb);
1433 return false; // No need to repeat.
1434}
1435
1436void MIRGraph::EliminateDeadCodeEnd() {
1437 DCHECK_EQ(temp_.gvn.dce != nullptr, (cu_->disable_opt & (1 << kGvnDeadCodeElimination)) == 0);
1438 if (temp_.gvn.dce != nullptr) {
1439 delete temp_.gvn.dce;
1440 temp_.gvn.dce = nullptr;
1441 }
Vladimir Markof585e542014-11-21 13:41:32 +00001442 delete temp_.gvn.gvn;
1443 temp_.gvn.gvn = nullptr;
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001444 temp_.gvn.ifield_ids = nullptr;
1445 temp_.gvn.sfield_ids = nullptr;
Vladimir Marko95a05972014-05-30 10:01:32 +01001446 DCHECK(temp_scoped_alloc_ != nullptr);
1447 temp_scoped_alloc_.reset();
1448}
1449
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001450void MIRGraph::ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput) {
1451 uint32_t method_index = invoke->meta.method_lowering_info;
Vladimir Markof585e542014-11-21 13:41:32 +00001452 if (temp_.smi.processed_indexes->IsBitSet(method_index)) {
1453 iget_or_iput->meta.ifield_lowering_info = temp_.smi.lowering_infos[method_index];
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001454 DCHECK_EQ(field_idx, GetIFieldLoweringInfo(iget_or_iput).FieldIndex());
1455 return;
1456 }
1457
1458 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(invoke);
1459 MethodReference target = method_info.GetTargetMethod();
1460 DexCompilationUnit inlined_unit(
1461 cu_, cu_->class_loader, cu_->class_linker, *target.dex_file,
1462 nullptr /* code_item not used */, 0u /* class_def_idx not used */, target.dex_method_index,
1463 0u /* access_flags not used */, nullptr /* verified_method not used */);
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001464 DexMemAccessType type = IGetOrIPutMemAccessType(iget_or_iput->dalvikInsn.opcode);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001465 MirIFieldLoweringInfo inlined_field_info(field_idx, type, false);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001466 MirIFieldLoweringInfo::Resolve(cu_->compiler_driver, &inlined_unit, &inlined_field_info, 1u);
1467 DCHECK(inlined_field_info.IsResolved());
1468
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001469 uint32_t field_info_index = ifield_lowering_infos_.size();
1470 ifield_lowering_infos_.push_back(inlined_field_info);
Vladimir Markof585e542014-11-21 13:41:32 +00001471 temp_.smi.processed_indexes->SetBit(method_index);
1472 temp_.smi.lowering_infos[method_index] = field_info_index;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001473 iget_or_iput->meta.ifield_lowering_info = field_info_index;
1474}
1475
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001476bool MIRGraph::InlineSpecialMethodsGate() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001477 if ((cu_->disable_opt & (1 << kSuppressMethodInlining)) != 0 ||
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001478 method_lowering_infos_.size() == 0u) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001479 return false;
1480 }
1481 if (cu_->compiler_driver->GetMethodInlinerMap() == nullptr) {
1482 // This isn't the Quick compiler.
1483 return false;
1484 }
1485 return true;
1486}
1487
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001488void MIRGraph::InlineSpecialMethodsStart() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001489 // Prepare for inlining getters/setters. Since we're inlining at most 1 IGET/IPUT from
1490 // each INVOKE, we can index the data by the MIR::meta::method_lowering_info index.
1491
1492 DCHECK(temp_scoped_alloc_.get() == nullptr);
1493 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001494 temp_.smi.num_indexes = method_lowering_infos_.size();
1495 temp_.smi.processed_indexes = new (temp_scoped_alloc_.get()) ArenaBitVector(
1496 temp_scoped_alloc_.get(), temp_.smi.num_indexes, false, kBitMapMisc);
1497 temp_.smi.processed_indexes->ClearAllBits();
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001498 temp_.smi.lowering_infos =
1499 temp_scoped_alloc_->AllocArray<uint16_t>(temp_.smi.num_indexes, kArenaAllocGrowableArray);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001500}
1501
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001502void MIRGraph::InlineSpecialMethods(BasicBlock* bb) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001503 if (bb->block_type != kDalvikByteCode) {
1504 return;
1505 }
1506 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001507 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee35ba7f32014-05-31 08:59:01 -07001508 continue;
1509 }
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001510 if (!(mir->dalvikInsn.FlagsOf() & Instruction::kInvoke)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001511 continue;
1512 }
1513 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
Vladimir Marko87b7c522015-04-08 10:01:01 +01001514 if (!method_info.FastPath() || !method_info.IsSpecial()) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001515 continue;
1516 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001517
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001518 InvokeType sharp_type = method_info.GetSharpType();
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001519 if ((sharp_type != kDirect) && (sharp_type != kStatic)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001520 continue;
1521 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001522
1523 if (sharp_type == kStatic) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001524 bool needs_clinit = !method_info.IsClassInitialized() &&
1525 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) == 0);
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001526 if (needs_clinit) {
1527 continue;
1528 }
1529 }
1530
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001531 DCHECK(cu_->compiler_driver->GetMethodInlinerMap() != nullptr);
1532 MethodReference target = method_info.GetTargetMethod();
1533 if (cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(target.dex_file)
1534 ->GenInline(this, bb, mir, target.dex_method_index)) {
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001535 if (cu_->verbose || cu_->print_pass) {
1536 LOG(INFO) << "SpecialMethodInliner: Inlined " << method_info.GetInvokeType() << " ("
1537 << sharp_type << ") call to \"" << PrettyMethod(target.dex_method_index, *target.dex_file)
1538 << "\" from \"" << PrettyMethod(cu_->method_idx, *cu_->dex_file)
1539 << "\" @0x" << std::hex << mir->offset;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001540 }
1541 }
1542 }
1543}
1544
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001545void MIRGraph::InlineSpecialMethodsEnd() {
Vladimir Markof585e542014-11-21 13:41:32 +00001546 // Clean up temporaries.
1547 DCHECK(temp_.smi.lowering_infos != nullptr);
1548 temp_.smi.lowering_infos = nullptr;
1549 temp_.smi.num_indexes = 0u;
1550 DCHECK(temp_.smi.processed_indexes != nullptr);
1551 temp_.smi.processed_indexes = nullptr;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001552 DCHECK(temp_scoped_alloc_.get() != nullptr);
1553 temp_scoped_alloc_.reset();
1554}
1555
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001556void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -08001557 Checkstats* stats =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001558 static_cast<Checkstats*>(arena_->Alloc(sizeof(Checkstats), kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001559 checkstats_ = stats;
buzbee56c71782013-09-05 17:13:19 -07001560 AllNodesIterator iter(this);
buzbee311ca162013-02-28 15:56:43 -08001561 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
1562 CountChecks(bb);
1563 }
1564 if (stats->null_checks > 0) {
1565 float eliminated = static_cast<float>(stats->null_checks_eliminated);
1566 float checks = static_cast<float>(stats->null_checks);
1567 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1568 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
1569 << (eliminated/checks) * 100.0 << "%";
1570 }
1571 if (stats->range_checks > 0) {
1572 float eliminated = static_cast<float>(stats->range_checks_eliminated);
1573 float checks = static_cast<float>(stats->range_checks);
1574 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1575 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
1576 << (eliminated/checks) * 100.0 << "%";
1577 }
1578}
1579
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001580bool MIRGraph::BuildExtendedBBList(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -08001581 if (bb->visited) return false;
1582 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
1583 || (bb->block_type == kExitBlock))) {
1584 // Ignore special blocks
1585 bb->visited = true;
1586 return false;
1587 }
1588 // Must be head of extended basic block.
1589 BasicBlock* start_bb = bb;
buzbee0d829482013-10-11 15:24:55 -07001590 extended_basic_blocks_.push_back(bb->id);
buzbee311ca162013-02-28 15:56:43 -08001591 bool terminated_by_return = false;
buzbee1da1e2f2013-11-15 13:37:01 -08001592 bool do_local_value_numbering = false;
buzbee311ca162013-02-28 15:56:43 -08001593 // Visit blocks strictly dominated by this head.
1594 while (bb != NULL) {
1595 bb->visited = true;
1596 terminated_by_return |= bb->terminated_by_return;
buzbee1da1e2f2013-11-15 13:37:01 -08001597 do_local_value_numbering |= bb->use_lvn;
buzbee311ca162013-02-28 15:56:43 -08001598 bb = NextDominatedBlock(bb);
1599 }
buzbee1da1e2f2013-11-15 13:37:01 -08001600 if (terminated_by_return || do_local_value_numbering) {
1601 // Do lvn for all blocks in this extended set.
buzbee311ca162013-02-28 15:56:43 -08001602 bb = start_bb;
1603 while (bb != NULL) {
buzbee1da1e2f2013-11-15 13:37:01 -08001604 bb->use_lvn = do_local_value_numbering;
1605 bb->dominates_return = terminated_by_return;
buzbee311ca162013-02-28 15:56:43 -08001606 bb = NextDominatedBlock(bb);
1607 }
1608 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001609 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -08001610}
1611
Vladimir Markoffda4992014-12-18 17:05:58 +00001612void MIRGraph::BasicBlockOptimizationStart() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001613 if ((cu_->disable_opt & (1 << kLocalValueNumbering)) == 0) {
1614 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001615 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001616 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001617 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001618 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
1619 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001620}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001621
Vladimir Markoffda4992014-12-18 17:05:58 +00001622void MIRGraph::BasicBlockOptimization() {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001623 if ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) {
1624 ClearAllVisitedFlags();
1625 PreOrderDfsIterator iter2(this);
1626 for (BasicBlock* bb = iter2.Next(); bb != NULL; bb = iter2.Next()) {
1627 BuildExtendedBBList(bb);
buzbee311ca162013-02-28 15:56:43 -08001628 }
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001629 // Perform extended basic block optimizations.
1630 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
1631 BasicBlockOpt(GetBasicBlock(extended_basic_blocks_[i]));
1632 }
1633 } else {
1634 PreOrderDfsIterator iter(this);
1635 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
1636 BasicBlockOpt(bb);
1637 }
buzbee311ca162013-02-28 15:56:43 -08001638 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001639}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001640
Vladimir Markoffda4992014-12-18 17:05:58 +00001641void MIRGraph::BasicBlockOptimizationEnd() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001642 // Clean up after LVN.
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001643 temp_.gvn.ifield_ids = nullptr;
1644 temp_.gvn.sfield_ids = nullptr;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001645 temp_scoped_alloc_.reset();
buzbee311ca162013-02-28 15:56:43 -08001646}
1647
Vladimir Marko8b858e12014-11-27 14:52:37 +00001648bool MIRGraph::EliminateSuspendChecksGate() {
1649 if ((cu_->disable_opt & (1 << kSuspendCheckElimination)) != 0 || // Disabled.
1650 GetMaxNestedLoops() == 0u || // Nothing to do.
1651 GetMaxNestedLoops() >= 32u || // Only 32 bits in suspend_checks_in_loops_[.].
1652 // Exclude 32 as well to keep bit shifts well-defined.
1653 !HasInvokes()) { // No invokes to actually eliminate any suspend checks.
1654 return false;
1655 }
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001656 suspend_checks_in_loops_ = arena_->AllocArray<uint32_t>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Marko8b858e12014-11-27 14:52:37 +00001657 return true;
1658}
1659
1660bool MIRGraph::EliminateSuspendChecks(BasicBlock* bb) {
1661 if (bb->block_type != kDalvikByteCode) {
1662 return false;
1663 }
1664 DCHECK_EQ(GetTopologicalSortOrderLoopHeadStack()->size(), bb->nesting_depth);
1665 if (bb->nesting_depth == 0u) {
1666 // Out of loops.
1667 DCHECK_EQ(suspend_checks_in_loops_[bb->id], 0u); // The array was zero-initialized.
1668 return false;
1669 }
1670 uint32_t suspend_checks_in_loops = (1u << bb->nesting_depth) - 1u; // Start with all loop heads.
1671 bool found_invoke = false;
1672 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko87b7c522015-04-08 10:01:01 +01001673 if ((IsInstructionInvoke(mir->dalvikInsn.opcode) ||
1674 IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) &&
1675 !GetMethodLoweringInfo(mir).IsIntrinsic()) {
Vladimir Marko8b858e12014-11-27 14:52:37 +00001676 // Non-intrinsic invoke, rely on a suspend point in the invoked method.
1677 found_invoke = true;
1678 break;
1679 }
1680 }
1681 if (!found_invoke) {
1682 // Intersect suspend checks from predecessors.
1683 uint16_t bb_topo_idx = topological_order_indexes_[bb->id];
1684 uint32_t pred_mask_union = 0u;
1685 for (BasicBlockId pred_id : bb->predecessors) {
1686 uint16_t pred_topo_idx = topological_order_indexes_[pred_id];
1687 if (pred_topo_idx < bb_topo_idx) {
1688 // Determine the loop depth of the predecessors relative to this block.
1689 size_t pred_loop_depth = topological_order_loop_head_stack_.size();
1690 while (pred_loop_depth != 0u &&
1691 pred_topo_idx < topological_order_loop_head_stack_[pred_loop_depth - 1].first) {
1692 --pred_loop_depth;
1693 }
1694 DCHECK_LE(pred_loop_depth, GetBasicBlock(pred_id)->nesting_depth);
1695 uint32_t pred_mask = (1u << pred_loop_depth) - 1u;
1696 // Intersect pred_mask bits in suspend_checks_in_loops with
1697 // suspend_checks_in_loops_[pred_id].
1698 uint32_t pred_loops_without_checks = pred_mask & ~suspend_checks_in_loops_[pred_id];
1699 suspend_checks_in_loops = suspend_checks_in_loops & ~pred_loops_without_checks;
1700 pred_mask_union |= pred_mask;
1701 }
1702 }
1703 DCHECK_EQ(((1u << (IsLoopHead(bb->id) ? bb->nesting_depth - 1u: bb->nesting_depth)) - 1u),
1704 pred_mask_union);
1705 suspend_checks_in_loops &= pred_mask_union;
1706 }
1707 suspend_checks_in_loops_[bb->id] = suspend_checks_in_loops;
1708 if (suspend_checks_in_loops == 0u) {
1709 return false;
1710 }
1711 // Apply MIR_IGNORE_SUSPEND_CHECK if appropriate.
1712 if (bb->taken != NullBasicBlockId) {
1713 DCHECK(bb->last_mir_insn != nullptr);
1714 DCHECK(IsInstructionIfCc(bb->last_mir_insn->dalvikInsn.opcode) ||
1715 IsInstructionIfCcZ(bb->last_mir_insn->dalvikInsn.opcode) ||
1716 IsInstructionGoto(bb->last_mir_insn->dalvikInsn.opcode) ||
1717 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) >= kMirOpFusedCmplFloat &&
1718 static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) <= kMirOpFusedCmpLong));
1719 if (!IsSuspendCheckEdge(bb, bb->taken) &&
1720 (bb->fall_through == NullBasicBlockId || !IsSuspendCheckEdge(bb, bb->fall_through))) {
1721 bb->last_mir_insn->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
1722 }
1723 } else if (bb->fall_through != NullBasicBlockId && IsSuspendCheckEdge(bb, bb->fall_through)) {
1724 // We've got a fall-through suspend edge. Add an artificial GOTO to force suspend check.
1725 MIR* mir = NewMIR();
1726 mir->dalvikInsn.opcode = Instruction::GOTO;
1727 mir->dalvikInsn.vA = 0; // Branch offset.
1728 mir->offset = GetBasicBlock(bb->fall_through)->start_offset;
1729 mir->m_unit_index = current_method_;
1730 mir->ssa_rep = reinterpret_cast<SSARepresentation*>(
1731 arena_->Alloc(sizeof(SSARepresentation), kArenaAllocDFInfo)); // Zero-initialized.
1732 bb->AppendMIR(mir);
1733 std::swap(bb->fall_through, bb->taken); // The fall-through has become taken.
1734 }
1735 return true;
1736}
1737
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001738bool MIRGraph::CanThrow(MIR* mir) const {
Ningsheng Jiana262f772014-11-25 16:48:07 +08001739 if ((mir->dalvikInsn.FlagsOf() & Instruction::kThrow) == 0) {
1740 return false;
1741 }
1742 const int opt_flags = mir->optimization_flags;
1743 uint64_t df_attributes = GetDataFlowAttributes(mir);
1744
Vladimir Marko315cc202014-12-18 17:01:02 +00001745 // First, check if the insn can still throw NPE.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001746 if (((df_attributes & DF_HAS_NULL_CHKS) != 0) && ((opt_flags & MIR_IGNORE_NULL_CHECK) == 0)) {
1747 return true;
1748 }
Vladimir Marko315cc202014-12-18 17:01:02 +00001749
1750 // Now process specific instructions.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001751 if ((df_attributes & DF_IFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001752 // The IGET/IPUT family. We have processed the IGET/IPUT null check above.
1753 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1754 // If not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001755 const MirIFieldLoweringInfo& field_info = GetIFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001756 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
1757 return !fast;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001758 } else if ((df_attributes & DF_SFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001759 // The SGET/SPUT family. Check for potentially throwing class initialization.
1760 // Also, if not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001761 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001762 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
Ningsheng Jiana262f772014-11-25 16:48:07 +08001763 bool is_class_initialized = field_info.IsClassInitialized() ||
1764 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0);
Vladimir Marko315cc202014-12-18 17:01:02 +00001765 return !(fast && is_class_initialized);
1766 } else if ((df_attributes & DF_HAS_RANGE_CHKS) != 0) {
1767 // Only AGET/APUT have range checks. We have processed the AGET/APUT null check above.
1768 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1769 // Non-throwing only if range check has been eliminated.
1770 return ((opt_flags & MIR_IGNORE_RANGE_CHECK) == 0);
Vladimir Marko22fe45d2015-03-18 11:33:58 +00001771 } else if (mir->dalvikInsn.opcode == Instruction::CHECK_CAST &&
1772 (opt_flags & MIR_IGNORE_CHECK_CAST) != 0) {
1773 return false;
Vladimir Marko315cc202014-12-18 17:01:02 +00001774 } else if (mir->dalvikInsn.opcode == Instruction::ARRAY_LENGTH ||
Vladimir Marko315cc202014-12-18 17:01:02 +00001775 static_cast<int>(mir->dalvikInsn.opcode) == kMirOpNullCheck) {
1776 // No more checks for these (null check was processed above).
1777 return false;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001778 }
1779 return true;
1780}
1781
1782bool MIRGraph::HasAntiDependency(MIR* first, MIR* second) {
1783 DCHECK(first->ssa_rep != nullptr);
1784 DCHECK(second->ssa_rep != nullptr);
1785 if ((second->ssa_rep->num_defs > 0) && (first->ssa_rep->num_uses > 0)) {
1786 int vreg0 = SRegToVReg(second->ssa_rep->defs[0]);
1787 int vreg1 = (second->ssa_rep->num_defs == 2) ?
1788 SRegToVReg(second->ssa_rep->defs[1]) : INVALID_VREG;
1789 for (int i = 0; i < first->ssa_rep->num_uses; i++) {
1790 int32_t use = SRegToVReg(first->ssa_rep->uses[i]);
1791 if (use == vreg0 || use == vreg1) {
1792 return true;
1793 }
1794 }
1795 }
1796 return false;
1797}
1798
1799void MIRGraph::CombineMultiplyAdd(MIR* mul_mir, MIR* add_mir, bool mul_is_first_addend,
1800 bool is_wide, bool is_sub) {
1801 if (is_wide) {
1802 if (is_sub) {
1803 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubLong);
1804 } else {
1805 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddLong);
1806 }
1807 } else {
1808 if (is_sub) {
1809 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubInt);
1810 } else {
1811 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddInt);
1812 }
1813 }
1814 add_mir->ssa_rep->num_uses = is_wide ? 6 : 3;
1815 int32_t addend0 = INVALID_SREG;
1816 int32_t addend1 = INVALID_SREG;
1817 if (is_wide) {
1818 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[2] : add_mir->ssa_rep->uses[0];
1819 addend1 = mul_is_first_addend ? add_mir->ssa_rep->uses[3] : add_mir->ssa_rep->uses[1];
1820 } else {
1821 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[1] : add_mir->ssa_rep->uses[0];
1822 }
1823
1824 AllocateSSAUseData(add_mir, add_mir->ssa_rep->num_uses);
1825 add_mir->ssa_rep->uses[0] = mul_mir->ssa_rep->uses[0];
1826 add_mir->ssa_rep->uses[1] = mul_mir->ssa_rep->uses[1];
1827 // Clear the original multiply product ssa use count, as it is not used anymore.
1828 raw_use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1829 use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1830 if (is_wide) {
1831 DCHECK_EQ(add_mir->ssa_rep->num_uses, 6);
1832 add_mir->ssa_rep->uses[2] = mul_mir->ssa_rep->uses[2];
1833 add_mir->ssa_rep->uses[3] = mul_mir->ssa_rep->uses[3];
1834 add_mir->ssa_rep->uses[4] = addend0;
1835 add_mir->ssa_rep->uses[5] = addend1;
1836 raw_use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1837 use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1838 } else {
1839 DCHECK_EQ(add_mir->ssa_rep->num_uses, 3);
1840 add_mir->ssa_rep->uses[2] = addend0;
1841 }
1842 // Copy in the decoded instruction information.
1843 add_mir->dalvikInsn.vB = SRegToVReg(add_mir->ssa_rep->uses[0]);
1844 if (is_wide) {
1845 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[2]);
1846 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[4]);
1847 } else {
1848 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[1]);
1849 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[2]);
1850 }
1851 // Original multiply MIR is set to Nop.
1852 mul_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1853}
1854
1855void MIRGraph::MultiplyAddOpt(BasicBlock* bb) {
1856 if (bb->block_type == kDead) {
1857 return;
1858 }
1859 ScopedArenaAllocator allocator(&cu_->arena_stack);
1860 ScopedArenaSafeMap<uint32_t, MIR*> ssa_mul_map(std::less<uint32_t>(), allocator.Adapter());
1861 ScopedArenaSafeMap<uint32_t, MIR*>::iterator map_it;
1862 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1863 Instruction::Code opcode = mir->dalvikInsn.opcode;
1864 bool is_sub = true;
1865 bool is_candidate_multiply = false;
1866 switch (opcode) {
1867 case Instruction::MUL_INT:
1868 case Instruction::MUL_INT_2ADDR:
1869 is_candidate_multiply = true;
1870 break;
1871 case Instruction::MUL_LONG:
1872 case Instruction::MUL_LONG_2ADDR:
1873 if (cu_->target64) {
1874 is_candidate_multiply = true;
1875 }
1876 break;
1877 case Instruction::ADD_INT:
1878 case Instruction::ADD_INT_2ADDR:
1879 is_sub = false;
1880 FALLTHROUGH_INTENDED;
1881 case Instruction::SUB_INT:
1882 case Instruction::SUB_INT_2ADDR:
1883 if (((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end()) && !is_sub) {
1884 // a*b+c
1885 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1886 false /* is_wide */, false /* is_sub */);
1887 ssa_mul_map.erase(mir->ssa_rep->uses[0]);
1888 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[1])) != ssa_mul_map.end()) {
1889 // c+a*b or c-a*b
1890 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1891 false /* is_wide */, is_sub);
1892 ssa_mul_map.erase(map_it);
1893 }
1894 break;
1895 case Instruction::ADD_LONG:
1896 case Instruction::ADD_LONG_2ADDR:
1897 is_sub = false;
1898 FALLTHROUGH_INTENDED;
1899 case Instruction::SUB_LONG:
1900 case Instruction::SUB_LONG_2ADDR:
1901 if (!cu_->target64) {
1902 break;
1903 }
1904 if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end() && !is_sub) {
1905 // a*b+c
1906 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1907 true /* is_wide */, false /* is_sub */);
1908 ssa_mul_map.erase(map_it);
1909 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[2])) != ssa_mul_map.end()) {
1910 // c+a*b or c-a*b
1911 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1912 true /* is_wide */, is_sub);
1913 ssa_mul_map.erase(map_it);
1914 }
1915 break;
1916 default:
1917 if (!ssa_mul_map.empty() && CanThrow(mir)) {
1918 // Should not combine multiply and add MIRs across potential exception.
1919 ssa_mul_map.clear();
1920 }
1921 break;
1922 }
1923
1924 // Exclude the case when an MIR writes a vreg which is previous candidate multiply MIR's uses.
1925 // It is because that current RA may allocate the same physical register to them. For this
1926 // kind of cases, the multiplier has been updated, we should not use updated value to the
1927 // multiply-add insn.
1928 if (ssa_mul_map.size() > 0) {
1929 for (auto it = ssa_mul_map.begin(); it != ssa_mul_map.end();) {
1930 MIR* mul = it->second;
1931 if (HasAntiDependency(mul, mir)) {
1932 it = ssa_mul_map.erase(it);
1933 } else {
1934 ++it;
1935 }
1936 }
1937 }
1938
1939 if (is_candidate_multiply &&
1940 (GetRawUseCount(mir->ssa_rep->defs[0]) == 1) && (mir->next != nullptr)) {
1941 ssa_mul_map.Put(mir->ssa_rep->defs[0], mir);
1942 }
1943 }
1944}
1945
buzbee311ca162013-02-28 15:56:43 -08001946} // namespace art