blob: 348260270499f3e99f68f65da99780fd04a54f13 [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 Markoc91df2d2015-04-23 09:29:21 +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
Mathieu Chartier2cebb242015-04-21 16:50:40 -070058 for (mir = bb->first_mir_insn; mir != nullptr; 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;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700119 if (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800120 mir = mir->next;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700121 while (mir == nullptr) {
buzbee0d829482013-10-11 15:24:55 -0700122 bb = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700123 if ((bb == nullptr) || 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
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700137 * a move-result, return it. Else, return nullptr. If a move-result exists,
buzbee311ca162013-02-28 15:56:43 -0800138 * 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);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700145 while (mir != nullptr) {
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 {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700155 mir = nullptr;
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) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700163 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800164 }
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);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700169 if (((bb_fall_through == nullptr) && (bb_taken != nullptr)) &&
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
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700175 bb = (bb_taken != nullptr) ? nullptr : bb_fall_through;
buzbeecbcfaf32013-08-19 07:37:40 -0700176 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700177 if (bb == nullptr || (Predecessors(bb) != 1)) {
178 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800179 }
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) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700185 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800186 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 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700194 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800195}
196
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700197static SelectInstructionKind SelectKind(MIR* mir) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700198 // Work with the case when mir is null.
Chao-ying Fu8ac41af2014-10-01 16:53:04 -0700199 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.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700259 size_t remaining_me_temps = max_available_non_special_compiler_temps_ -
260 reserved_temps_for_backend_;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700261
262 if (num_non_special_compiler_temps_ >= remaining_me_temps) {
263 return 0;
264 } else {
265 return remaining_me_temps - num_non_special_compiler_temps_;
266 }
267}
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000268
269// FIXME - will probably need to revisit all uses of this, as type not defined.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800270static const RegLocation temp_loc = {kLocCompilerTemp,
buzbee091cc402014-03-31 10:14:40 -0700271 0, 1 /*defined*/, 0, 0, 0, 0, 0, 1 /*home*/,
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000272 RegStorage(), INVALID_SREG, INVALID_SREG};
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800273
274CompilerTemp* MIRGraph::GetNewCompilerTemp(CompilerTempType ct_type, bool wide) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700275 // Once the compiler temps have been committed, new ones cannot be requested anymore.
276 DCHECK_EQ(compiler_temps_committed_, false);
277 // Make sure that reserved for BE set is sane.
278 DCHECK_LE(reserved_temps_for_backend_, max_available_non_special_compiler_temps_);
279
280 bool verbose = cu_->verbose;
281 const char* ct_type_str = nullptr;
282
283 if (verbose) {
284 switch (ct_type) {
285 case kCompilerTempBackend:
286 ct_type_str = "backend";
287 break;
288 case kCompilerTempSpecialMethodPtr:
289 ct_type_str = "method*";
290 break;
291 case kCompilerTempVR:
292 ct_type_str = "VR";
293 break;
294 default:
295 ct_type_str = "unknown";
296 break;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800297 }
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700298 LOG(INFO) << "CompilerTemps: A compiler temp of type " << ct_type_str << " that is "
299 << (wide ? "wide is being requested." : "not wide is being requested.");
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800300 }
301
302 CompilerTemp *compiler_temp = static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000303 kArenaAllocRegAlloc));
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800304
305 // Create the type of temp requested. Special temps need special handling because
306 // they have a specific virtual register assignment.
307 if (ct_type == kCompilerTempSpecialMethodPtr) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700308 // This has a special location on stack which is 32-bit or 64-bit depending
309 // on mode. However, we don't want to overlap with non-special section
310 // and thus even for 64-bit, we allow only a non-wide temp to be requested.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800311 DCHECK_EQ(wide, false);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800312
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700313 // The vreg is always the first special temp for method ptr.
314 compiler_temp->v_reg = GetFirstSpecialTempVR();
315
316 } else if (ct_type == kCompilerTempBackend) {
317 requested_backend_temp_ = true;
318
319 // Make sure that we are not exceeding temps reserved for BE.
320 // Since VR temps cannot be requested once the BE temps are requested, we
321 // allow reservation of VR temps as well for BE. We
322 size_t available_temps = reserved_temps_for_backend_ + GetNumAvailableVRTemps();
Vladimir Markocc234812015-04-07 09:36:09 +0100323 size_t needed_temps = wide ? 2u : 1u;
324 if (available_temps < needed_temps) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700325 if (verbose) {
Vladimir Markocc234812015-04-07 09:36:09 +0100326 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
327 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700328 }
329 return nullptr;
330 }
331
332 // Update the remaining reserved temps since we have now used them.
333 // Note that the code below is actually subtracting to remove them from reserve
334 // once they have been claimed. It is careful to not go below zero.
Vladimir Markocc234812015-04-07 09:36:09 +0100335 reserved_temps_for_backend_ =
336 std::max(reserved_temps_for_backend_, needed_temps) - needed_temps;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700337
338 // The new non-special compiler temp must receive a unique v_reg.
339 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
340 num_non_special_compiler_temps_++;
341 } else if (ct_type == kCompilerTempVR) {
342 // Once we start giving out BE temps, we don't allow anymore ME temps to be requested.
343 // This is done in order to prevent problems with ssa since these structures are allocated
344 // and managed by the ME.
345 DCHECK_EQ(requested_backend_temp_, false);
346
347 // There is a limit to the number of non-special temps so check to make sure it wasn't exceeded.
348 size_t available_temps = GetNumAvailableVRTemps();
349 if (available_temps <= 0 || (available_temps <= 1 && wide)) {
350 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700351 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
352 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700353 }
354 return nullptr;
355 }
356
357 // The new non-special compiler temp must receive a unique v_reg.
358 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
359 num_non_special_compiler_temps_++;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800360 } else {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700361 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << ct_type_str << ".";
362 }
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800363
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700364 // We allocate an sreg as well to make developer life easier.
365 // However, if this is requested from an ME pass that will recalculate ssa afterwards,
366 // this sreg is no longer valid. The caller should be aware of this.
367 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
368
369 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700370 LOG(INFO) << "CompilerTemps: New temp of type " << ct_type_str << " with v"
371 << compiler_temp->v_reg << " and s" << compiler_temp->s_reg_low << " has been created.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700372 }
373
374 if (wide) {
375 // Only non-special temps are handled as wide for now.
376 // Note that the number of non special temps is incremented below.
377 DCHECK(ct_type == kCompilerTempBackend || ct_type == kCompilerTempVR);
378
379 // Ensure that the two registers are consecutive.
380 int ssa_reg_low = compiler_temp->s_reg_low;
381 int ssa_reg_high = AddNewSReg(compiler_temp->v_reg + 1);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800382 num_non_special_compiler_temps_++;
383
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700384 if (verbose) {
385 LOG(INFO) << "CompilerTemps: The wide part of temp of type " << ct_type_str << " is v"
386 << compiler_temp->v_reg + 1 << " and s" << ssa_reg_high << ".";
387 }
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700388
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700389 if (reg_location_ != nullptr) {
390 reg_location_[ssa_reg_high] = temp_loc;
391 reg_location_[ssa_reg_high].high_word = true;
392 reg_location_[ssa_reg_high].s_reg_low = ssa_reg_low;
393 reg_location_[ssa_reg_high].wide = true;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800394 }
395 }
396
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700397 // If the register locations have already been allocated, add the information
398 // about the temp. We will not overflow because they have been initialized
399 // to support the maximum number of temps. For ME temps that have multiple
400 // ssa versions, the structures below will be expanded on the post pass cleanup.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800401 if (reg_location_ != nullptr) {
402 int ssa_reg_low = compiler_temp->s_reg_low;
403 reg_location_[ssa_reg_low] = temp_loc;
404 reg_location_[ssa_reg_low].s_reg_low = ssa_reg_low;
405 reg_location_[ssa_reg_low].wide = wide;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800406 }
407
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800408 return compiler_temp;
409}
buzbee311ca162013-02-28 15:56:43 -0800410
Vladimir Markocc234812015-04-07 09:36:09 +0100411void MIRGraph::RemoveLastCompilerTemp(CompilerTempType ct_type, bool wide, CompilerTemp* temp) {
412 // Once the compiler temps have been committed, it's too late for any modifications.
413 DCHECK_EQ(compiler_temps_committed_, false);
414
415 size_t used_temps = wide ? 2u : 1u;
416
417 if (ct_type == kCompilerTempBackend) {
418 DCHECK(requested_backend_temp_);
419
420 // Make the temps available to backend again.
421 reserved_temps_for_backend_ += used_temps;
422 } else if (ct_type == kCompilerTempVR) {
423 DCHECK(!requested_backend_temp_);
424 } else {
425 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << static_cast<int>(ct_type);
426 }
427
428 // Reduce the number of non-special compiler temps.
429 DCHECK_LE(used_temps, num_non_special_compiler_temps_);
430 num_non_special_compiler_temps_ -= used_temps;
431
432 // Check that this was really the last temp.
433 DCHECK_EQ(static_cast<size_t>(temp->v_reg),
434 GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_);
435
436 if (cu_->verbose) {
437 LOG(INFO) << "Last temporary has been removed.";
438 }
439}
440
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000441static bool EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
442 bool is_taken;
443 switch (opcode) {
444 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
445 case Instruction::IF_NE: is_taken = (src1 != src2); break;
446 case Instruction::IF_LT: is_taken = (src1 < src2); break;
447 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
448 case Instruction::IF_GT: is_taken = (src1 > src2); break;
449 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
450 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
451 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
452 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
453 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
454 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
455 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
456 default:
457 LOG(FATAL) << "Unexpected opcode " << opcode;
458 UNREACHABLE();
459 }
460 return is_taken;
461}
462
buzbee311ca162013-02-28 15:56:43 -0800463/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700464bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800465 if (bb->block_type == kDead) {
466 return true;
467 }
Ningsheng Jiana262f772014-11-25 16:48:07 +0800468 // Currently multiply-accumulate backend supports are only available on arm32 and arm64.
469 if (cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2) {
470 MultiplyAddOpt(bb);
471 }
Vladimir Marko415ac882014-09-30 18:09:14 +0100472 bool use_lvn = bb->use_lvn && (cu_->disable_opt & (1u << kLocalValueNumbering)) == 0u;
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100473 std::unique_ptr<ScopedArenaAllocator> allocator;
Vladimir Marko95a05972014-05-30 10:01:32 +0100474 std::unique_ptr<GlobalValueNumbering> global_valnum;
Ian Rogers700a4022014-05-19 16:49:03 -0700475 std::unique_ptr<LocalValueNumbering> local_valnum;
buzbee1da1e2f2013-11-15 13:37:01 -0800476 if (use_lvn) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100477 allocator.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko415ac882014-09-30 18:09:14 +0100478 global_valnum.reset(new (allocator.get()) GlobalValueNumbering(cu_, allocator.get(),
479 GlobalValueNumbering::kModeLvn));
Vladimir Markob19955d2014-07-29 12:04:10 +0100480 local_valnum.reset(new (allocator.get()) LocalValueNumbering(global_valnum.get(), bb->id,
481 allocator.get()));
buzbee1da1e2f2013-11-15 13:37:01 -0800482 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700483 while (bb != nullptr) {
484 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800485 // TUNING: use the returned value number for CSE.
buzbee1da1e2f2013-11-15 13:37:01 -0800486 if (use_lvn) {
487 local_valnum->GetValueNumber(mir);
488 }
buzbee311ca162013-02-28 15:56:43 -0800489 // Look for interesting opcodes, skip otherwise
490 Instruction::Code opcode = mir->dalvikInsn.opcode;
491 switch (opcode) {
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000492 case Instruction::IF_EQ:
493 case Instruction::IF_NE:
494 case Instruction::IF_LT:
495 case Instruction::IF_GE:
496 case Instruction::IF_GT:
497 case Instruction::IF_LE:
498 if (!IsConst(mir->ssa_rep->uses[1])) {
499 break;
500 }
501 FALLTHROUGH_INTENDED;
502 case Instruction::IF_EQZ:
503 case Instruction::IF_NEZ:
504 case Instruction::IF_LTZ:
505 case Instruction::IF_GEZ:
506 case Instruction::IF_GTZ:
507 case Instruction::IF_LEZ:
508 // Result known at compile time?
509 if (IsConst(mir->ssa_rep->uses[0])) {
510 int32_t rhs = (mir->ssa_rep->num_uses == 2) ? ConstantValue(mir->ssa_rep->uses[1]) : 0;
511 bool is_taken = EvaluateBranch(opcode, ConstantValue(mir->ssa_rep->uses[0]), rhs);
512 BasicBlockId edge_to_kill = is_taken ? bb->fall_through : bb->taken;
513 if (is_taken) {
514 // Replace with GOTO.
515 bb->fall_through = NullBasicBlockId;
516 mir->dalvikInsn.opcode = Instruction::GOTO;
517 mir->dalvikInsn.vA =
518 IsInstructionIfCc(opcode) ? mir->dalvikInsn.vC : mir->dalvikInsn.vB;
519 } else {
520 // Make NOP.
521 bb->taken = NullBasicBlockId;
522 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
523 }
524 mir->ssa_rep->num_uses = 0;
525 BasicBlock* successor_to_unlink = GetBasicBlock(edge_to_kill);
526 successor_to_unlink->ErasePredecessor(bb->id);
Vladimir Marko341e4252014-12-19 10:29:51 +0000527 // We have changed the graph structure.
528 dfs_orders_up_to_date_ = false;
529 domination_up_to_date_ = false;
530 topological_order_up_to_date_ = false;
531 // Keep MIR SSA rep, the worst that can happen is a Phi with just 1 input.
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000532 }
533 break;
buzbee311ca162013-02-28 15:56:43 -0800534 case Instruction::CMPL_FLOAT:
535 case Instruction::CMPL_DOUBLE:
536 case Instruction::CMPG_FLOAT:
537 case Instruction::CMPG_DOUBLE:
538 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700539 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800540 // Bitcode doesn't allow this optimization.
541 break;
542 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700543 if (mir->next != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800544 MIR* mir_next = mir->next;
buzbee311ca162013-02-28 15:56:43 -0800545 // Make sure result of cmp is used by next insn and nowhere else
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700546 if (IsInstructionIfCcZ(mir_next->dalvikInsn.opcode) &&
buzbee311ca162013-02-28 15:56:43 -0800547 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
548 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
Vladimir Markoa1a70742014-03-03 10:28:05 +0000549 mir_next->meta.ccode = ConditionCodeForIfCcZ(mir_next->dalvikInsn.opcode);
Brian Carlstromdf629502013-07-17 22:39:56 -0700550 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800551 case Instruction::CMPL_FLOAT:
552 mir_next->dalvikInsn.opcode =
553 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
554 break;
555 case Instruction::CMPL_DOUBLE:
556 mir_next->dalvikInsn.opcode =
557 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
558 break;
559 case Instruction::CMPG_FLOAT:
560 mir_next->dalvikInsn.opcode =
561 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
562 break;
563 case Instruction::CMPG_DOUBLE:
564 mir_next->dalvikInsn.opcode =
565 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
566 break;
567 case Instruction::CMP_LONG:
568 mir_next->dalvikInsn.opcode =
569 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
570 break;
571 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
572 }
573 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
Zheng Xub218c852014-12-08 18:18:01 +0800574 // Clear use count of temp VR.
575 use_counts_[mir->ssa_rep->defs[0]] = 0;
576 raw_use_counts_[mir->ssa_rep->defs[0]] = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700577 // Copy the SSA information that is relevant.
buzbee311ca162013-02-28 15:56:43 -0800578 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
579 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
buzbee311ca162013-02-28 15:56:43 -0800580 mir_next->ssa_rep->num_defs = 0;
581 mir->ssa_rep->num_uses = 0;
582 mir->ssa_rep->num_defs = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700583 // Copy in the decoded instruction information for potential SSA re-creation.
584 mir_next->dalvikInsn.vA = mir->dalvikInsn.vB;
585 mir_next->dalvikInsn.vB = mir->dalvikInsn.vC;
buzbee311ca162013-02-28 15:56:43 -0800586 }
587 }
588 break;
buzbee311ca162013-02-28 15:56:43 -0800589 default:
590 break;
591 }
592 // Is this the select pattern?
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800593 // TODO: flesh out support for Mips. NOTE: llvm's select op doesn't quite work here.
buzbee311ca162013-02-28 15:56:43 -0800594 // TUNING: expand to support IF_xx compare & branches
Elliott Hughes956af0f2014-12-11 14:34:28 -0800595 if ((cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2 ||
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100596 cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) &&
Vladimir Markoa1a70742014-03-03 10:28:05 +0000597 IsInstructionIfCcZ(mir->dalvikInsn.opcode)) {
buzbee0d829482013-10-11 15:24:55 -0700598 BasicBlock* ft = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700599 DCHECK(ft != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700600 BasicBlock* ft_ft = GetBasicBlock(ft->fall_through);
601 BasicBlock* ft_tk = GetBasicBlock(ft->taken);
buzbee311ca162013-02-28 15:56:43 -0800602
buzbee0d829482013-10-11 15:24:55 -0700603 BasicBlock* tk = GetBasicBlock(bb->taken);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700604 DCHECK(tk != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700605 BasicBlock* tk_ft = GetBasicBlock(tk->fall_through);
606 BasicBlock* tk_tk = GetBasicBlock(tk->taken);
buzbee311ca162013-02-28 15:56:43 -0800607
608 /*
609 * In the select pattern, the taken edge goes to a block that unconditionally
610 * transfers to the rejoin block and the fall_though edge goes to a block that
611 * unconditionally falls through to the rejoin block.
612 */
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700613 if ((tk_ft == nullptr) && (ft_tk == nullptr) && (tk_tk == ft_ft) &&
buzbee311ca162013-02-28 15:56:43 -0800614 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
615 /*
Vladimir Marko8b858e12014-11-27 14:52:37 +0000616 * Okay - we have the basic diamond shape.
buzbee311ca162013-02-28 15:56:43 -0800617 */
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100618
619 // TODO: Add logic for LONG.
buzbee311ca162013-02-28 15:56:43 -0800620 // Are the block bodies something we can handle?
621 if ((ft->first_mir_insn == ft->last_mir_insn) &&
622 (tk->first_mir_insn != tk->last_mir_insn) &&
623 (tk->first_mir_insn->next == tk->last_mir_insn) &&
624 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
625 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
626 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
627 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
628 // Almost there. Are the instructions targeting the same vreg?
629 MIR* if_true = tk->first_mir_insn;
630 MIR* if_false = ft->first_mir_insn;
631 // It's possible that the target of the select isn't used - skip those (rare) cases.
632 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700633 if ((phi != nullptr) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
buzbee311ca162013-02-28 15:56:43 -0800634 /*
635 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
636 * Phi node in the merge block and delete it (while using the SSA name
637 * of the merge as the target of the SELECT. Delete both taken and
638 * fallthrough blocks, and set fallthrough to merge block.
639 * NOTE: not updating other dataflow info (no longer used at this point).
640 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
641 */
Vladimir Markoa1a70742014-03-03 10:28:05 +0000642 mir->meta.ccode = ConditionCodeForIfCcZ(mir->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800643 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
644 bool const_form = (SelectKind(if_true) == kSelectConst);
645 if ((SelectKind(if_true) == kSelectMove)) {
646 if (IsConst(if_true->ssa_rep->uses[0]) &&
647 IsConst(if_false->ssa_rep->uses[0])) {
648 const_form = true;
649 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
650 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
651 }
652 }
653 if (const_form) {
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800654 /*
655 * TODO: If both constants are the same value, then instead of generating
656 * a select, we should simply generate a const bytecode. This should be
657 * considered after inlining which can lead to CFG of this form.
658 */
buzbee311ca162013-02-28 15:56:43 -0800659 // "true" set val in vB
660 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
661 // "false" set val in vC
662 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
663 } else {
664 DCHECK_EQ(SelectKind(if_true), kSelectMove);
665 DCHECK_EQ(SelectKind(if_false), kSelectMove);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000666 int32_t* src_ssa = arena_->AllocArray<int32_t>(3, kArenaAllocDFInfo);
buzbee311ca162013-02-28 15:56:43 -0800667 src_ssa[0] = mir->ssa_rep->uses[0];
668 src_ssa[1] = if_true->ssa_rep->uses[0];
669 src_ssa[2] = if_false->ssa_rep->uses[0];
670 mir->ssa_rep->uses = src_ssa;
671 mir->ssa_rep->num_uses = 3;
672 }
Vladimir Markoc91df2d2015-04-23 09:29:21 +0000673 AllocateSSADefData(mir, 1);
buzbee311ca162013-02-28 15:56:43 -0800674 /*
675 * There is usually a Phi node in the join block for our two cases. If the
676 * Phi node only contains our two cases as input, we will use the result
677 * SSA name of the Phi node as our select result and delete the Phi. If
678 * the Phi node has more than two operands, we will arbitrarily use the SSA
Vladimir Marko341e4252014-12-19 10:29:51 +0000679 * name of the "false" path, delete the SSA name of the "true" path from the
buzbee311ca162013-02-28 15:56:43 -0800680 * Phi node (and fix up the incoming arc list).
681 */
682 if (phi->ssa_rep->num_uses == 2) {
683 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000684 // Rather than changing the Phi to kMirOpNop, remove it completely.
685 // This avoids leaving other Phis after kMirOpNop (i.e. a non-Phi) insn.
686 tk_tk->RemoveMIR(phi);
687 int dead_false_def = if_false->ssa_rep->defs[0];
688 raw_use_counts_[dead_false_def] = use_counts_[dead_false_def] = 0;
buzbee311ca162013-02-28 15:56:43 -0800689 } else {
Vladimir Marko341e4252014-12-19 10:29:51 +0000690 int live_def = if_false->ssa_rep->defs[0];
buzbee311ca162013-02-28 15:56:43 -0800691 mir->ssa_rep->defs[0] = live_def;
buzbee311ca162013-02-28 15:56:43 -0800692 }
Vladimir Marko341e4252014-12-19 10:29:51 +0000693 int dead_true_def = if_true->ssa_rep->defs[0];
694 raw_use_counts_[dead_true_def] = use_counts_[dead_true_def] = 0;
Vladimir Marko6e071832015-03-25 11:13:39 +0000695 // Update ending vreg->sreg map for GC maps generation.
696 int def_vreg = SRegToVReg(mir->ssa_rep->defs[0]);
697 bb->data_flow_info->vreg_to_ssa_map_exit[def_vreg] = mir->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000698 // We want to remove ft and tk and link bb directly to ft_ft. First, we need
699 // to update all Phi inputs correctly with UpdatePredecessor(ft->id, bb->id)
700 // since the live_def above comes from ft->first_mir_insn (if_false).
701 DCHECK(if_false == ft->first_mir_insn);
702 ft_ft->UpdatePredecessor(ft->id, bb->id);
703 // Correct the rest of the links between bb, ft and ft_ft.
704 ft->ErasePredecessor(bb->id);
705 ft->fall_through = NullBasicBlockId;
706 bb->fall_through = ft_ft->id;
707 // Now we can kill tk and ft.
708 tk->Kill(this);
709 ft->Kill(this);
710 // NOTE: DFS order, domination info and topological order are still usable
711 // despite the newly dead blocks.
buzbee311ca162013-02-28 15:56:43 -0800712 }
713 }
714 }
715 }
716 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700717 bb = ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) ? NextDominatedBlock(bb) :
718 nullptr;
buzbee311ca162013-02-28 15:56:43 -0800719 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100720 if (use_lvn && UNLIKELY(!global_valnum->Good())) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100721 LOG(WARNING) << "LVN overflow in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
722 }
buzbee311ca162013-02-28 15:56:43 -0800723
buzbee311ca162013-02-28 15:56:43 -0800724 return true;
725}
726
buzbee311ca162013-02-28 15:56:43 -0800727/* Collect stats on number of checks removed */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700728void MIRGraph::CountChecks(class BasicBlock* bb) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 if (bb->data_flow_info != nullptr) {
730 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
731 if (mir->ssa_rep == nullptr) {
buzbee862a7602013-04-05 10:58:54 -0700732 continue;
buzbee311ca162013-02-28 15:56:43 -0800733 }
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700734 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee862a7602013-04-05 10:58:54 -0700735 if (df_attributes & DF_HAS_NULL_CHKS) {
736 checkstats_->null_checks++;
737 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
738 checkstats_->null_checks_eliminated++;
739 }
740 }
741 if (df_attributes & DF_HAS_RANGE_CHKS) {
742 checkstats_->range_checks++;
743 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
744 checkstats_->range_checks_eliminated++;
745 }
buzbee311ca162013-02-28 15:56:43 -0800746 }
747 }
748 }
buzbee311ca162013-02-28 15:56:43 -0800749}
750
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700751/* Try to make common case the fallthrough path. */
buzbee0d829482013-10-11 15:24:55 -0700752bool MIRGraph::LayoutBlocks(BasicBlock* bb) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700753 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback.
buzbee311ca162013-02-28 15:56:43 -0800754 if (!bb->explicit_throw) {
755 return false;
756 }
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700757
758 // If we visited it, we are done.
759 if (bb->visited) {
760 return false;
761 }
762 bb->visited = true;
763
buzbee311ca162013-02-28 15:56:43 -0800764 BasicBlock* walker = bb;
765 while (true) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700766 // Check termination conditions.
buzbee311ca162013-02-28 15:56:43 -0800767 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
768 break;
769 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100770 DCHECK(!walker->predecessors.empty());
771 BasicBlock* prev = GetBasicBlock(walker->predecessors[0]);
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700772
773 // If we visited the predecessor, we are done.
774 if (prev->visited) {
775 return false;
776 }
777 prev->visited = true;
778
buzbee311ca162013-02-28 15:56:43 -0800779 if (prev->conditional_branch) {
buzbee0d829482013-10-11 15:24:55 -0700780 if (GetBasicBlock(prev->fall_through) == walker) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700781 // Already done - return.
buzbee311ca162013-02-28 15:56:43 -0800782 break;
783 }
buzbee0d829482013-10-11 15:24:55 -0700784 DCHECK_EQ(walker, GetBasicBlock(prev->taken));
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700785 // Got one. Flip it and exit.
buzbee311ca162013-02-28 15:56:43 -0800786 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
787 switch (opcode) {
788 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
789 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
790 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
791 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
792 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
793 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
794 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
795 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
796 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
797 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
798 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
799 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
800 default: LOG(FATAL) << "Unexpected opcode " << opcode;
801 }
802 prev->last_mir_insn->dalvikInsn.opcode = opcode;
buzbee0d829482013-10-11 15:24:55 -0700803 BasicBlockId t_bb = prev->taken;
buzbee311ca162013-02-28 15:56:43 -0800804 prev->taken = prev->fall_through;
805 prev->fall_through = t_bb;
806 break;
807 }
808 walker = prev;
809 }
810 return false;
811}
812
813/* Combine any basic blocks terminated by instructions that we now know can't throw */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700814void MIRGraph::CombineBlocks(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800815 // Loop here to allow combining a sequence of blocks
Vladimir Marko312eb252014-10-07 15:01:57 +0100816 while ((bb->block_type == kDalvikByteCode) &&
817 (bb->last_mir_insn != nullptr) &&
818 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) == kMirOpCheck)) {
819 MIR* mir = bb->last_mir_insn;
820 DCHECK(bb->first_mir_insn != nullptr);
821
Vladimir Marko315cc202014-12-18 17:01:02 +0000822 // Get the paired insn and check if it can still throw.
Vladimir Marko312eb252014-10-07 15:01:57 +0100823 MIR* throw_insn = mir->meta.throw_insn;
Vladimir Marko315cc202014-12-18 17:01:02 +0000824 if (CanThrow(throw_insn)) {
buzbee311ca162013-02-28 15:56:43 -0800825 break;
826 }
827
buzbee311ca162013-02-28 15:56:43 -0800828 // OK - got one. Combine
buzbee0d829482013-10-11 15:24:55 -0700829 BasicBlock* bb_next = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800830 DCHECK(!bb_next->catch_entry);
Vladimir Marko312eb252014-10-07 15:01:57 +0100831 DCHECK_EQ(bb_next->predecessors.size(), 1u);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700832
833 // Now move instructions from bb_next to bb. Start off with doing a sanity check
834 // that kMirOpCheck's throw instruction is first one in the bb_next.
buzbee311ca162013-02-28 15:56:43 -0800835 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700836 // Now move all instructions (throw instruction to last one) from bb_next to bb.
837 MIR* last_to_move = bb_next->last_mir_insn;
838 bb_next->RemoveMIRList(throw_insn, last_to_move);
839 bb->InsertMIRListAfter(bb->last_mir_insn, throw_insn, last_to_move);
840 // The kMirOpCheck instruction is not needed anymore.
841 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
842 bb->RemoveMIR(mir);
843
Vladimir Marko312eb252014-10-07 15:01:57 +0100844 // Before we overwrite successors, remove their predecessor links to bb.
845 bb_next->ErasePredecessor(bb->id);
846 if (bb->taken != NullBasicBlockId) {
847 DCHECK_EQ(bb->successor_block_list_type, kNotUsed);
848 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
849 // bb->taken will be overwritten below.
850 DCHECK_EQ(bb_taken->block_type, kExceptionHandling);
851 DCHECK_EQ(bb_taken->predecessors.size(), 1u);
852 DCHECK_EQ(bb_taken->predecessors[0], bb->id);
853 bb_taken->predecessors.clear();
854 bb_taken->block_type = kDead;
855 DCHECK(bb_taken->data_flow_info == nullptr);
856 } else {
857 DCHECK_EQ(bb->successor_block_list_type, kCatch);
858 for (SuccessorBlockInfo* succ_info : bb->successor_blocks) {
859 if (succ_info->block != NullBasicBlockId) {
860 BasicBlock* succ_bb = GetBasicBlock(succ_info->block);
861 DCHECK(succ_bb->catch_entry);
862 succ_bb->ErasePredecessor(bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100863 }
864 }
865 }
buzbee311ca162013-02-28 15:56:43 -0800866 // Use the successor info from the next block
buzbee0d829482013-10-11 15:24:55 -0700867 bb->successor_block_list_type = bb_next->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100868 bb->successor_blocks.swap(bb_next->successor_blocks); // Swap instead of copying.
Vladimir Marko312eb252014-10-07 15:01:57 +0100869 bb_next->successor_block_list_type = kNotUsed;
buzbee311ca162013-02-28 15:56:43 -0800870 // Use the ending block linkage from the next block
871 bb->fall_through = bb_next->fall_through;
Vladimir Marko312eb252014-10-07 15:01:57 +0100872 bb_next->fall_through = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800873 bb->taken = bb_next->taken;
Vladimir Marko312eb252014-10-07 15:01:57 +0100874 bb_next->taken = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800875 /*
Junmo Parkf1770fd2014-08-12 09:34:54 +0900876 * If lower-half of pair of blocks to combine contained
877 * a return or a conditional branch or an explicit throw,
878 * move the flag to the newly combined block.
buzbee311ca162013-02-28 15:56:43 -0800879 */
880 bb->terminated_by_return = bb_next->terminated_by_return;
Junmo Parkf1770fd2014-08-12 09:34:54 +0900881 bb->conditional_branch = bb_next->conditional_branch;
882 bb->explicit_throw = bb_next->explicit_throw;
Vladimir Marko312eb252014-10-07 15:01:57 +0100883 // Merge the use_lvn flag.
884 bb->use_lvn |= bb_next->use_lvn;
885
886 // Kill the unused block.
887 bb_next->data_flow_info = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800888
889 /*
890 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
891 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
Vladimir Marko312eb252014-10-07 15:01:57 +0100892 * NOTE: GVN uses bb->data_flow_info->live_in_v which is unaffected by the block merge.
buzbee311ca162013-02-28 15:56:43 -0800893 */
894
Vladimir Marko312eb252014-10-07 15:01:57 +0100895 // Kill bb_next and remap now-dead id to parent.
buzbee311ca162013-02-28 15:56:43 -0800896 bb_next->block_type = kDead;
Vladimir Marko312eb252014-10-07 15:01:57 +0100897 bb_next->data_flow_info = nullptr; // Must be null for dead blocks. (Relied on by the GVN.)
buzbee1fd33462013-03-25 13:40:45 -0700898 block_id_map_.Overwrite(bb_next->id, bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100899 // Update predecessors in children.
900 ChildBlockIterator iter(bb, this);
901 for (BasicBlock* child = iter.Next(); child != nullptr; child = iter.Next()) {
902 child->UpdatePredecessor(bb_next->id, bb->id);
903 }
904
Vladimir Markoffda4992014-12-18 17:05:58 +0000905 // DFS orders, domination and topological order are not up to date anymore.
Vladimir Marko312eb252014-10-07 15:01:57 +0100906 dfs_orders_up_to_date_ = false;
Vladimir Markoffda4992014-12-18 17:05:58 +0000907 domination_up_to_date_ = false;
908 topological_order_up_to_date_ = false;
buzbee311ca162013-02-28 15:56:43 -0800909
910 // Now, loop back and see if we can keep going
911 }
buzbee311ca162013-02-28 15:56:43 -0800912}
913
Vladimir Marko67c72b82014-10-09 12:26:10 +0100914bool MIRGraph::EliminateNullChecksGate() {
915 if ((cu_->disable_opt & (1 << kNullCheckElimination)) != 0 ||
916 (merged_df_flags_ & DF_HAS_NULL_CHKS) == 0) {
917 return false;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000918 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100919
Vladimir Marko67c72b82014-10-09 12:26:10 +0100920 DCHECK(temp_scoped_alloc_.get() == nullptr);
921 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700922 temp_.nce.num_vregs = GetNumOfCodeAndTempVRs();
Vladimir Markof585e542014-11-21 13:41:32 +0000923 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
924 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000925 temp_.nce.ending_vregs_to_check_matrix =
926 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +0000927 std::fill_n(temp_.nce.ending_vregs_to_check_matrix, GetNumBlocks(), nullptr);
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700928
929 // reset MIR_MARK
930 AllNodesIterator iter(this);
931 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700932 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700933 mir->optimization_flags &= ~MIR_MARK;
934 }
935 }
936
Vladimir Marko67c72b82014-10-09 12:26:10 +0100937 return true;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000938}
939
buzbee1da1e2f2013-11-15 13:37:01 -0800940/*
Vladimir Marko67c72b82014-10-09 12:26:10 +0100941 * Eliminate unnecessary null checks for a basic block.
buzbee1da1e2f2013-11-15 13:37:01 -0800942 */
Vladimir Marko67c72b82014-10-09 12:26:10 +0100943bool MIRGraph::EliminateNullChecks(BasicBlock* bb) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100944 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
945 // Ignore the kExitBlock as well.
946 DCHECK(bb->first_mir_insn == nullptr);
947 return false;
948 }
buzbee311ca162013-02-28 15:56:43 -0800949
Vladimir Markof585e542014-11-21 13:41:32 +0000950 ArenaBitVector* vregs_to_check = temp_.nce.work_vregs_to_check;
Vladimir Marko67c72b82014-10-09 12:26:10 +0100951 /*
952 * Set initial state. Catch blocks don't need any special treatment.
953 */
954 if (bb->block_type == kEntryBlock) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100955 vregs_to_check->ClearAllBits();
Vladimir Marko67c72b82014-10-09 12:26:10 +0100956 // Assume all ins are objects.
957 for (uint16_t in_reg = GetFirstInVR();
958 in_reg < GetNumOfCodeVRs(); in_reg++) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100959 vregs_to_check->SetBit(in_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100960 }
961 if ((cu_->access_flags & kAccStatic) == 0) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100962 // If non-static method, mark "this" as non-null.
Vladimir Marko67c72b82014-10-09 12:26:10 +0100963 int this_reg = GetFirstInVR();
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100964 vregs_to_check->ClearBit(this_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100965 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100966 } else {
967 DCHECK_EQ(bb->block_type, kDalvikByteCode);
968 // Starting state is union of all incoming arcs.
969 bool copied_first = false;
970 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +0000971 if (temp_.nce.ending_vregs_to_check_matrix[pred_id] == nullptr) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100972 continue;
973 }
974 BasicBlock* pred_bb = GetBasicBlock(pred_id);
975 DCHECK(pred_bb != nullptr);
976 MIR* null_check_insn = nullptr;
977 if (pred_bb->block_type == kDalvikByteCode) {
978 // Check to see if predecessor had an explicit null-check.
979 MIR* last_insn = pred_bb->last_mir_insn;
980 if (last_insn != nullptr) {
981 Instruction::Code last_opcode = last_insn->dalvikInsn.opcode;
982 if ((last_opcode == Instruction::IF_EQZ && pred_bb->fall_through == bb->id) ||
983 (last_opcode == Instruction::IF_NEZ && pred_bb->taken == bb->id)) {
984 // Remember the null check insn if there's no other predecessor requiring null check.
985 if (!copied_first || !vregs_to_check->IsBitSet(last_insn->dalvikInsn.vA)) {
986 null_check_insn = last_insn;
987 }
buzbee1da1e2f2013-11-15 13:37:01 -0800988 }
Ian Rogers22fd6a02013-06-13 15:06:54 -0700989 }
990 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100991 if (!copied_first) {
992 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +0000993 vregs_to_check->Copy(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100994 } else {
Vladimir Markof585e542014-11-21 13:41:32 +0000995 vregs_to_check->Union(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100996 }
997 if (null_check_insn != nullptr) {
998 vregs_to_check->ClearBit(null_check_insn->dalvikInsn.vA);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100999 }
1000 }
1001 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
buzbee311ca162013-02-28 15:56:43 -08001002 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001003 // At this point, vregs_to_check shows which sregs have an object definition with
Vladimir Marko67c72b82014-10-09 12:26:10 +01001004 // no intervening uses.
buzbee311ca162013-02-28 15:56:43 -08001005
1006 // Walk through the instruction in the block, updating as necessary
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001007 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beylercc794c32014-05-02 09:34:13 -07001008 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -08001009
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -07001010 if ((df_attributes & DF_NULL_TRANSFER_N) != 0u) {
1011 // The algorithm was written in a phi agnostic way.
1012 continue;
1013 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001014
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001015 // Might need a null check?
1016 if (df_attributes & DF_HAS_NULL_CHKS) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001017 int src_vreg;
1018 if (df_attributes & DF_NULL_CHK_OUT0) {
1019 DCHECK_NE(df_attributes & DF_IS_INVOKE, 0u);
1020 src_vreg = mir->dalvikInsn.vC;
1021 } else if (df_attributes & DF_NULL_CHK_B) {
1022 DCHECK_NE(df_attributes & DF_REF_B, 0u);
1023 src_vreg = mir->dalvikInsn.vB;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001024 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001025 DCHECK_NE(df_attributes & DF_NULL_CHK_A, 0u);
1026 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1027 src_vreg = mir->dalvikInsn.vA;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001028 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001029 if (!vregs_to_check->IsBitSet(src_vreg)) {
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001030 // Eliminate the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001031 mir->optimization_flags |= MIR_MARK;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001032 } else {
1033 // Do the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001034 mir->optimization_flags &= ~MIR_MARK;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001035 // Mark src_vreg as null-checked.
1036 vregs_to_check->ClearBit(src_vreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001037 }
1038 }
1039
1040 if ((df_attributes & DF_A_WIDE) ||
1041 (df_attributes & (DF_REF_A | DF_SETS_CONST | DF_NULL_TRANSFER)) == 0) {
1042 continue;
1043 }
1044
1045 /*
1046 * First, mark all object definitions as requiring null check.
1047 * Note: we can't tell if a CONST definition might be used as an object, so treat
1048 * them all as object definitions.
1049 */
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001050 if ((df_attributes & (DF_DA | DF_REF_A)) == (DF_DA | DF_REF_A) ||
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001051 (df_attributes & DF_SETS_CONST)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001052 vregs_to_check->SetBit(mir->dalvikInsn.vA);
buzbee4db179d2013-10-23 12:16:39 -07001053 }
1054
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001055 // Then, remove mark from all object definitions we know are non-null.
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001056 if (df_attributes & DF_NON_NULL_DST) {
1057 // Mark target of NEW* as non-null
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001058 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1059 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001060 }
1061
buzbee311ca162013-02-28 15:56:43 -08001062 // Mark non-null returns from invoke-style NEW*
1063 if (df_attributes & DF_NON_NULL_RET) {
1064 MIR* next_mir = mir->next;
1065 // Next should be an MOVE_RESULT_OBJECT
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001066 if (UNLIKELY(next_mir == nullptr)) {
1067 // The MethodVerifier makes sure there's no MOVE_RESULT at the catch entry or branch
1068 // target, so the MOVE_RESULT cannot be broken away into another block.
1069 LOG(WARNING) << "Unexpected end of block following new";
1070 } else if (UNLIKELY(next_mir->dalvikInsn.opcode != Instruction::MOVE_RESULT_OBJECT)) {
1071 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
buzbee311ca162013-02-28 15:56:43 -08001072 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001073 // Mark as null checked.
1074 vregs_to_check->ClearBit(next_mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001075 }
1076 }
1077
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001078 // Propagate null check state on register copies.
1079 if (df_attributes & DF_NULL_TRANSFER_0) {
1080 DCHECK_EQ(df_attributes | ~(DF_DA | DF_REF_A | DF_UB | DF_REF_B), static_cast<uint64_t>(-1));
1081 if (vregs_to_check->IsBitSet(mir->dalvikInsn.vB)) {
1082 vregs_to_check->SetBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001083 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001084 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001085 }
1086 }
buzbee311ca162013-02-28 15:56:43 -08001087 }
1088
1089 // Did anything change?
Vladimir Markobfea9c22014-01-17 17:49:33 +00001090 bool nce_changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001091 ArenaBitVector* old_ending_ssa_regs_to_check = temp_.nce.ending_vregs_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001092 if (old_ending_ssa_regs_to_check == nullptr) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001093 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001094 nce_changed = vregs_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001095 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001096 // Create a new vregs_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001097 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1098 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001099 } else if (!vregs_to_check->SameBitsSet(old_ending_ssa_regs_to_check)) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001100 nce_changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001101 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
1102 temp_.nce.work_vregs_to_check = old_ending_ssa_regs_to_check; // Reuse for next BB.
buzbee311ca162013-02-28 15:56:43 -08001103 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001104 return nce_changed;
buzbee311ca162013-02-28 15:56:43 -08001105}
1106
Vladimir Marko67c72b82014-10-09 12:26:10 +01001107void MIRGraph::EliminateNullChecksEnd() {
1108 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001109 temp_.nce.num_vregs = 0u;
1110 temp_.nce.work_vregs_to_check = nullptr;
1111 temp_.nce.ending_vregs_to_check_matrix = nullptr;
Vladimir Marko67c72b82014-10-09 12:26:10 +01001112 DCHECK(temp_scoped_alloc_.get() != nullptr);
1113 temp_scoped_alloc_.reset();
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001114
1115 // converge MIR_MARK with MIR_IGNORE_NULL_CHECK
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001116 AllNodesIterator iter(this);
1117 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001118 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001119 constexpr int kMarkToIgnoreNullCheckShift = kMIRMark - kMIRIgnoreNullCheck;
Andreas Gampe785d2f22014-11-03 22:57:30 -08001120 static_assert(kMarkToIgnoreNullCheckShift > 0, "Not a valid right-shift");
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001121 uint16_t mirMarkAdjustedToIgnoreNullCheck =
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001122 (mir->optimization_flags & MIR_MARK) >> kMarkToIgnoreNullCheckShift;
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001123 mir->optimization_flags |= mirMarkAdjustedToIgnoreNullCheck;
1124 }
1125 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001126}
1127
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001128void MIRGraph::InferTypesStart() {
1129 DCHECK(temp_scoped_alloc_ != nullptr);
1130 temp_.ssa.ti = new (temp_scoped_alloc_.get()) TypeInference(this, temp_scoped_alloc_.get());
1131}
1132
Vladimir Marko67c72b82014-10-09 12:26:10 +01001133/*
1134 * Perform type and size inference for a basic block.
1135 */
1136bool MIRGraph::InferTypes(BasicBlock* bb) {
1137 if (bb->data_flow_info == nullptr) return false;
1138
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001139 DCHECK(temp_.ssa.ti != nullptr);
1140 return temp_.ssa.ti->Apply(bb);
1141}
Vladimir Marko67c72b82014-10-09 12:26:10 +01001142
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001143void MIRGraph::InferTypesEnd() {
1144 DCHECK(temp_.ssa.ti != nullptr);
1145 temp_.ssa.ti->Finish();
1146 delete temp_.ssa.ti;
1147 temp_.ssa.ti = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001148}
1149
1150bool MIRGraph::EliminateClassInitChecksGate() {
1151 if ((cu_->disable_opt & (1 << kClassInitCheckElimination)) != 0 ||
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001152 (merged_df_flags_ & DF_CLINIT) == 0) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001153 return false;
1154 }
1155
Vladimir Markobfea9c22014-01-17 17:49:33 +00001156 DCHECK(temp_scoped_alloc_.get() == nullptr);
1157 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1158
1159 // 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 -07001160 const size_t end = (GetNumDalvikInsns() + 1u) / 2u;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001161 temp_.cice.indexes = temp_scoped_alloc_->AllocArray<uint16_t>(end, kArenaAllocGrowableArray);
Vladimir Markof585e542014-11-21 13:41:32 +00001162 std::fill_n(temp_.cice.indexes, end, 0xffffu);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001163
1164 uint32_t unique_class_count = 0u;
1165 {
1166 // Get unique_class_count and store indexes in temp_insn_data_ using a map on a nested
1167 // ScopedArenaAllocator.
1168
1169 // Embed the map value in the entry to save space.
1170 struct MapEntry {
1171 // Map key: the class identified by the declaring dex file and type index.
1172 const DexFile* declaring_dex_file;
1173 uint16_t declaring_class_idx;
1174 // Map value: index into bit vectors of classes requiring initialization checks.
1175 uint16_t index;
1176 };
1177 struct MapEntryComparator {
1178 bool operator()(const MapEntry& lhs, const MapEntry& rhs) const {
1179 if (lhs.declaring_class_idx != rhs.declaring_class_idx) {
1180 return lhs.declaring_class_idx < rhs.declaring_class_idx;
1181 }
1182 return lhs.declaring_dex_file < rhs.declaring_dex_file;
1183 }
1184 };
1185
Vladimir Markobfea9c22014-01-17 17:49:33 +00001186 ScopedArenaAllocator allocator(&cu_->arena_stack);
Vladimir Marko69f08ba2014-04-11 12:28:11 +01001187 ScopedArenaSet<MapEntry, MapEntryComparator> class_to_index_map(MapEntryComparator(),
1188 allocator.Adapter());
Vladimir Markobfea9c22014-01-17 17:49:33 +00001189
1190 // First, find all SGET/SPUTs that may need class initialization checks, record INVOKE_STATICs.
1191 AllNodesIterator iter(this);
1192 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001193 if (bb->block_type == kDalvikByteCode) {
1194 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001195 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001196 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001197 if (!field_info.IsReferrersClass()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001198 DCHECK_LT(class_to_index_map.size(), 0xffffu);
1199 MapEntry entry = {
1200 // Treat unresolved fields as if each had its own class.
1201 field_info.IsResolved() ? field_info.DeclaringDexFile()
1202 : nullptr,
1203 field_info.IsResolved() ? field_info.DeclaringClassIndex()
1204 : field_info.FieldIndex(),
1205 static_cast<uint16_t>(class_to_index_map.size())
1206 };
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001207 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001208 // Using offset/2 for index into temp_.cice.indexes.
1209 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001210 }
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001211 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001212 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
1213 DCHECK(method_info.IsStatic());
1214 if (method_info.FastPath() && !method_info.IsReferrersClass()) {
1215 MapEntry entry = {
1216 method_info.DeclaringDexFile(),
1217 method_info.DeclaringClassIndex(),
1218 static_cast<uint16_t>(class_to_index_map.size())
1219 };
1220 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001221 // Using offset/2 for index into temp_.cice.indexes.
1222 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001223 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001224 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001225 }
1226 }
1227 }
1228 unique_class_count = static_cast<uint32_t>(class_to_index_map.size());
1229 }
1230
1231 if (unique_class_count == 0u) {
1232 // All SGET/SPUTs refer to initialized classes. Nothing to do.
Vladimir Markof585e542014-11-21 13:41:32 +00001233 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001234 temp_scoped_alloc_.reset();
1235 return false;
1236 }
1237
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001238 // 2 bits for each class: is class initialized, is class in dex cache.
Vladimir Markof585e542014-11-21 13:41:32 +00001239 temp_.cice.num_class_bits = 2u * unique_class_count;
1240 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1241 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001242 temp_.cice.ending_classes_to_check_matrix =
1243 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +00001244 std::fill_n(temp_.cice.ending_classes_to_check_matrix, GetNumBlocks(), nullptr);
1245 DCHECK_GT(temp_.cice.num_class_bits, 0u);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001246 return true;
1247}
1248
1249/*
1250 * Eliminate unnecessary class initialization checks for a basic block.
1251 */
1252bool MIRGraph::EliminateClassInitChecks(BasicBlock* bb) {
1253 DCHECK_EQ((cu_->disable_opt & (1 << kClassInitCheckElimination)), 0u);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001254 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
1255 // Ignore the kExitBlock as well.
1256 DCHECK(bb->first_mir_insn == nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001257 return false;
1258 }
1259
1260 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +01001261 * Set initial state. Catch blocks don't need any special treatment.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001262 */
Vladimir Markof585e542014-11-21 13:41:32 +00001263 ArenaBitVector* classes_to_check = temp_.cice.work_classes_to_check;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001264 DCHECK(classes_to_check != nullptr);
Vladimir Marko0a810d22014-07-11 14:44:36 +01001265 if (bb->block_type == kEntryBlock) {
Vladimir Markof585e542014-11-21 13:41:32 +00001266 classes_to_check->SetInitialBits(temp_.cice.num_class_bits);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001267 } else {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001268 // Starting state is union of all incoming arcs.
1269 bool copied_first = false;
1270 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +00001271 if (temp_.cice.ending_classes_to_check_matrix[pred_id] == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001272 continue;
1273 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001274 if (!copied_first) {
1275 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001276 classes_to_check->Copy(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001277 } else {
Vladimir Markof585e542014-11-21 13:41:32 +00001278 classes_to_check->Union(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001279 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001280 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001281 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001282 }
1283 // At this point, classes_to_check shows which classes need clinit checks.
1284
1285 // Walk through the instruction in the block, updating as necessary
1286 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markof585e542014-11-21 13:41:32 +00001287 uint16_t index = temp_.cice.indexes[mir->offset / 2u];
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001288 if (index != 0xffffu) {
1289 bool check_initialization = false;
1290 bool check_dex_cache = false;
1291
1292 // NOTE: index != 0xffff does not guarantee that this is an SGET/SPUT/INVOKE_STATIC.
1293 // Dex instructions with width 1 can have the same offset/2.
1294
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001295 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001296 check_initialization = true;
1297 check_dex_cache = true;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001298 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001299 check_initialization = true;
1300 // NOTE: INVOKE_STATIC doesn't guarantee that the type will be in the dex cache.
1301 }
1302
1303 if (check_dex_cache) {
1304 uint32_t check_dex_cache_index = 2u * index + 1u;
1305 if (!classes_to_check->IsBitSet(check_dex_cache_index)) {
1306 // Eliminate the class init check.
1307 mir->optimization_flags |= MIR_CLASS_IS_IN_DEX_CACHE;
1308 } else {
1309 // Do the class init check.
1310 mir->optimization_flags &= ~MIR_CLASS_IS_IN_DEX_CACHE;
1311 }
1312 classes_to_check->ClearBit(check_dex_cache_index);
1313 }
1314 if (check_initialization) {
1315 uint32_t check_clinit_index = 2u * index;
1316 if (!classes_to_check->IsBitSet(check_clinit_index)) {
1317 // Eliminate the class init check.
1318 mir->optimization_flags |= MIR_CLASS_IS_INITIALIZED;
1319 } else {
1320 // Do the class init check.
1321 mir->optimization_flags &= ~MIR_CLASS_IS_INITIALIZED;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001322 }
1323 // Mark the class as initialized.
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001324 classes_to_check->ClearBit(check_clinit_index);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001325 }
1326 }
1327 }
1328
1329 // Did anything change?
1330 bool changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001331 ArenaBitVector* old_ending_classes_to_check = temp_.cice.ending_classes_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001332 if (old_ending_classes_to_check == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001333 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001334 changed = classes_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001335 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001336 // Create a new classes_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001337 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1338 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Marko5229cf12014-10-09 14:57:59 +01001339 } else if (!classes_to_check->Equal(old_ending_classes_to_check)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001340 changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001341 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
1342 temp_.cice.work_classes_to_check = old_ending_classes_to_check; // Reuse for next BB.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001343 }
1344 return changed;
1345}
1346
1347void MIRGraph::EliminateClassInitChecksEnd() {
1348 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001349 temp_.cice.num_class_bits = 0u;
1350 temp_.cice.work_classes_to_check = nullptr;
1351 temp_.cice.ending_classes_to_check_matrix = nullptr;
1352 DCHECK(temp_.cice.indexes != nullptr);
1353 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001354 DCHECK(temp_scoped_alloc_.get() != nullptr);
1355 temp_scoped_alloc_.reset();
1356}
1357
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001358static void DisableGVNDependentOptimizations(CompilationUnit* cu) {
1359 cu->disable_opt |= (1u << kGvnDeadCodeElimination);
1360}
1361
Vladimir Marko95a05972014-05-30 10:01:32 +01001362bool MIRGraph::ApplyGlobalValueNumberingGate() {
Vladimir Marko415ac882014-09-30 18:09:14 +01001363 if (GlobalValueNumbering::Skip(cu_)) {
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001364 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001365 return false;
1366 }
1367
1368 DCHECK(temp_scoped_alloc_ == nullptr);
1369 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001370 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001371 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001372 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001373 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
Vladimir Markof585e542014-11-21 13:41:32 +00001374 DCHECK(temp_.gvn.gvn == nullptr);
1375 temp_.gvn.gvn = new (temp_scoped_alloc_.get()) GlobalValueNumbering(
1376 cu_, temp_scoped_alloc_.get(), GlobalValueNumbering::kModeGvn);
Vladimir Marko95a05972014-05-30 10:01:32 +01001377 return true;
1378}
1379
1380bool MIRGraph::ApplyGlobalValueNumbering(BasicBlock* bb) {
Vladimir Markof585e542014-11-21 13:41:32 +00001381 DCHECK(temp_.gvn.gvn != nullptr);
1382 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001383 if (lvn != nullptr) {
1384 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1385 lvn->GetValueNumber(mir);
1386 }
1387 }
Vladimir Markof585e542014-11-21 13:41:32 +00001388 bool change = (lvn != nullptr) && temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001389 return change;
1390}
1391
1392void MIRGraph::ApplyGlobalValueNumberingEnd() {
1393 // Perform modifications.
Vladimir Markof585e542014-11-21 13:41:32 +00001394 DCHECK(temp_.gvn.gvn != nullptr);
1395 if (temp_.gvn.gvn->Good()) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001396 temp_.gvn.gvn->StartPostProcessing();
Vladimir Marko415ac882014-09-30 18:09:14 +01001397 if (max_nested_loops_ != 0u) {
Vladimir Marko415ac882014-09-30 18:09:14 +01001398 TopologicalSortIterator iter(this);
1399 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1400 ScopedArenaAllocator allocator(&cu_->arena_stack); // Reclaim memory after each LVN.
Vladimir Markof585e542014-11-21 13:41:32 +00001401 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb, &allocator);
Vladimir Marko415ac882014-09-30 18:09:14 +01001402 if (lvn != nullptr) {
1403 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1404 lvn->GetValueNumber(mir);
1405 }
Vladimir Markof585e542014-11-21 13:41:32 +00001406 bool change = temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko415ac882014-09-30 18:09:14 +01001407 DCHECK(!change) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko95a05972014-05-30 10:01:32 +01001408 }
Vladimir Marko95a05972014-05-30 10:01:32 +01001409 }
1410 }
Vladimir Marko415ac882014-09-30 18:09:14 +01001411 // GVN was successful, running the LVN would be useless.
1412 cu_->disable_opt |= (1u << kLocalValueNumbering);
Vladimir Marko95a05972014-05-30 10:01:32 +01001413 } else {
1414 LOG(WARNING) << "GVN failed for " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001415 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001416 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001417}
1418
1419bool MIRGraph::EliminateDeadCodeGate() {
Vladimir Markoad677272015-04-20 10:48:13 +01001420 if ((cu_->disable_opt & (1 << kGvnDeadCodeElimination)) != 0 || temp_.gvn.gvn == nullptr) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001421 return false;
1422 }
1423 DCHECK(temp_scoped_alloc_ != nullptr);
1424 temp_.gvn.dce = new (temp_scoped_alloc_.get()) GvnDeadCodeElimination(temp_.gvn.gvn,
1425 temp_scoped_alloc_.get());
1426 return true;
1427}
1428
1429bool MIRGraph::EliminateDeadCode(BasicBlock* bb) {
1430 DCHECK(temp_scoped_alloc_ != nullptr);
1431 DCHECK(temp_.gvn.gvn != nullptr);
1432 if (bb->block_type != kDalvikByteCode) {
1433 return false;
1434 }
1435 DCHECK(temp_.gvn.dce != nullptr);
1436 temp_.gvn.dce->Apply(bb);
1437 return false; // No need to repeat.
1438}
1439
1440void MIRGraph::EliminateDeadCodeEnd() {
Vladimir Markoad677272015-04-20 10:48:13 +01001441 if (kIsDebugBuild) {
1442 // DCE can make some previously dead vregs alive again. Make sure the obsolete
1443 // live-in information is not used anymore.
1444 AllNodesIterator iter(this);
1445 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1446 if (bb->data_flow_info != nullptr) {
1447 bb->data_flow_info->live_in_v = nullptr;
1448 }
1449 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001450 }
Vladimir Markoad677272015-04-20 10:48:13 +01001451}
1452
1453void MIRGraph::GlobalValueNumberingCleanup() {
1454 delete temp_.gvn.dce;
1455 temp_.gvn.dce = nullptr;
Vladimir Markof585e542014-11-21 13:41:32 +00001456 delete temp_.gvn.gvn;
1457 temp_.gvn.gvn = nullptr;
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001458 temp_.gvn.ifield_ids = nullptr;
1459 temp_.gvn.sfield_ids = nullptr;
Vladimir Marko95a05972014-05-30 10:01:32 +01001460 DCHECK(temp_scoped_alloc_ != nullptr);
1461 temp_scoped_alloc_.reset();
1462}
1463
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001464void MIRGraph::ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput) {
1465 uint32_t method_index = invoke->meta.method_lowering_info;
Vladimir Markof585e542014-11-21 13:41:32 +00001466 if (temp_.smi.processed_indexes->IsBitSet(method_index)) {
1467 iget_or_iput->meta.ifield_lowering_info = temp_.smi.lowering_infos[method_index];
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001468 DCHECK_EQ(field_idx, GetIFieldLoweringInfo(iget_or_iput).FieldIndex());
1469 return;
1470 }
1471
1472 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(invoke);
1473 MethodReference target = method_info.GetTargetMethod();
1474 DexCompilationUnit inlined_unit(
1475 cu_, cu_->class_loader, cu_->class_linker, *target.dex_file,
1476 nullptr /* code_item not used */, 0u /* class_def_idx not used */, target.dex_method_index,
1477 0u /* access_flags not used */, nullptr /* verified_method not used */);
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001478 DexMemAccessType type = IGetOrIPutMemAccessType(iget_or_iput->dalvikInsn.opcode);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001479 MirIFieldLoweringInfo inlined_field_info(field_idx, type, false);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001480 MirIFieldLoweringInfo::Resolve(cu_->compiler_driver, &inlined_unit, &inlined_field_info, 1u);
1481 DCHECK(inlined_field_info.IsResolved());
1482
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001483 uint32_t field_info_index = ifield_lowering_infos_.size();
1484 ifield_lowering_infos_.push_back(inlined_field_info);
Vladimir Markof585e542014-11-21 13:41:32 +00001485 temp_.smi.processed_indexes->SetBit(method_index);
1486 temp_.smi.lowering_infos[method_index] = field_info_index;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001487 iget_or_iput->meta.ifield_lowering_info = field_info_index;
1488}
1489
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001490bool MIRGraph::InlineSpecialMethodsGate() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001491 if ((cu_->disable_opt & (1 << kSuppressMethodInlining)) != 0 ||
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001492 method_lowering_infos_.size() == 0u) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001493 return false;
1494 }
1495 if (cu_->compiler_driver->GetMethodInlinerMap() == nullptr) {
1496 // This isn't the Quick compiler.
1497 return false;
1498 }
1499 return true;
1500}
1501
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001502void MIRGraph::InlineSpecialMethodsStart() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001503 // Prepare for inlining getters/setters. Since we're inlining at most 1 IGET/IPUT from
1504 // each INVOKE, we can index the data by the MIR::meta::method_lowering_info index.
1505
1506 DCHECK(temp_scoped_alloc_.get() == nullptr);
1507 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001508 temp_.smi.num_indexes = method_lowering_infos_.size();
1509 temp_.smi.processed_indexes = new (temp_scoped_alloc_.get()) ArenaBitVector(
1510 temp_scoped_alloc_.get(), temp_.smi.num_indexes, false, kBitMapMisc);
1511 temp_.smi.processed_indexes->ClearAllBits();
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001512 temp_.smi.lowering_infos =
1513 temp_scoped_alloc_->AllocArray<uint16_t>(temp_.smi.num_indexes, kArenaAllocGrowableArray);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001514}
1515
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001516void MIRGraph::InlineSpecialMethods(BasicBlock* bb) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001517 if (bb->block_type != kDalvikByteCode) {
1518 return;
1519 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001520 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001521 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee35ba7f32014-05-31 08:59:01 -07001522 continue;
1523 }
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001524 if (!(mir->dalvikInsn.FlagsOf() & Instruction::kInvoke)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001525 continue;
1526 }
1527 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
Vladimir Marko87b7c522015-04-08 10:01:01 +01001528 if (!method_info.FastPath() || !method_info.IsSpecial()) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001529 continue;
1530 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001531
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001532 InvokeType sharp_type = method_info.GetSharpType();
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001533 if ((sharp_type != kDirect) && (sharp_type != kStatic)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001534 continue;
1535 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001536
1537 if (sharp_type == kStatic) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001538 bool needs_clinit = !method_info.IsClassInitialized() &&
1539 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) == 0);
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001540 if (needs_clinit) {
1541 continue;
1542 }
1543 }
1544
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001545 DCHECK(cu_->compiler_driver->GetMethodInlinerMap() != nullptr);
1546 MethodReference target = method_info.GetTargetMethod();
1547 if (cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(target.dex_file)
1548 ->GenInline(this, bb, mir, target.dex_method_index)) {
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001549 if (cu_->verbose || cu_->print_pass) {
1550 LOG(INFO) << "SpecialMethodInliner: Inlined " << method_info.GetInvokeType() << " ("
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001551 << sharp_type << ") call to \"" << PrettyMethod(target.dex_method_index,
1552 *target.dex_file)
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001553 << "\" from \"" << PrettyMethod(cu_->method_idx, *cu_->dex_file)
1554 << "\" @0x" << std::hex << mir->offset;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001555 }
1556 }
1557 }
1558}
1559
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001560void MIRGraph::InlineSpecialMethodsEnd() {
Vladimir Markof585e542014-11-21 13:41:32 +00001561 // Clean up temporaries.
1562 DCHECK(temp_.smi.lowering_infos != nullptr);
1563 temp_.smi.lowering_infos = nullptr;
1564 temp_.smi.num_indexes = 0u;
1565 DCHECK(temp_.smi.processed_indexes != nullptr);
1566 temp_.smi.processed_indexes = nullptr;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001567 DCHECK(temp_scoped_alloc_.get() != nullptr);
1568 temp_scoped_alloc_.reset();
1569}
1570
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001571void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -08001572 Checkstats* stats =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001573 static_cast<Checkstats*>(arena_->Alloc(sizeof(Checkstats), kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001574 checkstats_ = stats;
buzbee56c71782013-09-05 17:13:19 -07001575 AllNodesIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001576 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
buzbee311ca162013-02-28 15:56:43 -08001577 CountChecks(bb);
1578 }
1579 if (stats->null_checks > 0) {
1580 float eliminated = static_cast<float>(stats->null_checks_eliminated);
1581 float checks = static_cast<float>(stats->null_checks);
1582 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1583 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
1584 << (eliminated/checks) * 100.0 << "%";
1585 }
1586 if (stats->range_checks > 0) {
1587 float eliminated = static_cast<float>(stats->range_checks_eliminated);
1588 float checks = static_cast<float>(stats->range_checks);
1589 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1590 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
1591 << (eliminated/checks) * 100.0 << "%";
1592 }
1593}
1594
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001595bool MIRGraph::BuildExtendedBBList(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -08001596 if (bb->visited) return false;
1597 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
1598 || (bb->block_type == kExitBlock))) {
1599 // Ignore special blocks
1600 bb->visited = true;
1601 return false;
1602 }
1603 // Must be head of extended basic block.
1604 BasicBlock* start_bb = bb;
buzbee0d829482013-10-11 15:24:55 -07001605 extended_basic_blocks_.push_back(bb->id);
buzbee311ca162013-02-28 15:56:43 -08001606 bool terminated_by_return = false;
buzbee1da1e2f2013-11-15 13:37:01 -08001607 bool do_local_value_numbering = false;
buzbee311ca162013-02-28 15:56:43 -08001608 // Visit blocks strictly dominated by this head.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001609 while (bb != nullptr) {
buzbee311ca162013-02-28 15:56:43 -08001610 bb->visited = true;
1611 terminated_by_return |= bb->terminated_by_return;
buzbee1da1e2f2013-11-15 13:37:01 -08001612 do_local_value_numbering |= bb->use_lvn;
buzbee311ca162013-02-28 15:56:43 -08001613 bb = NextDominatedBlock(bb);
1614 }
buzbee1da1e2f2013-11-15 13:37:01 -08001615 if (terminated_by_return || do_local_value_numbering) {
1616 // Do lvn for all blocks in this extended set.
buzbee311ca162013-02-28 15:56:43 -08001617 bb = start_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001618 while (bb != nullptr) {
buzbee1da1e2f2013-11-15 13:37:01 -08001619 bb->use_lvn = do_local_value_numbering;
1620 bb->dominates_return = terminated_by_return;
buzbee311ca162013-02-28 15:56:43 -08001621 bb = NextDominatedBlock(bb);
1622 }
1623 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001624 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -08001625}
1626
Vladimir Markoffda4992014-12-18 17:05:58 +00001627void MIRGraph::BasicBlockOptimizationStart() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001628 if ((cu_->disable_opt & (1 << kLocalValueNumbering)) == 0) {
1629 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001630 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001631 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001632 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001633 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
1634 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001635}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001636
Vladimir Markoffda4992014-12-18 17:05:58 +00001637void MIRGraph::BasicBlockOptimization() {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001638 if ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) {
1639 ClearAllVisitedFlags();
1640 PreOrderDfsIterator iter2(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001641 for (BasicBlock* bb = iter2.Next(); bb != nullptr; bb = iter2.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001642 BuildExtendedBBList(bb);
buzbee311ca162013-02-28 15:56:43 -08001643 }
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001644 // Perform extended basic block optimizations.
1645 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
1646 BasicBlockOpt(GetBasicBlock(extended_basic_blocks_[i]));
1647 }
1648 } else {
1649 PreOrderDfsIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001650 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001651 BasicBlockOpt(bb);
1652 }
buzbee311ca162013-02-28 15:56:43 -08001653 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001654}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001655
Vladimir Markoffda4992014-12-18 17:05:58 +00001656void MIRGraph::BasicBlockOptimizationEnd() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001657 // Clean up after LVN.
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001658 temp_.gvn.ifield_ids = nullptr;
1659 temp_.gvn.sfield_ids = nullptr;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001660 temp_scoped_alloc_.reset();
buzbee311ca162013-02-28 15:56:43 -08001661}
1662
Vladimir Marko8b858e12014-11-27 14:52:37 +00001663bool MIRGraph::EliminateSuspendChecksGate() {
1664 if ((cu_->disable_opt & (1 << kSuspendCheckElimination)) != 0 || // Disabled.
1665 GetMaxNestedLoops() == 0u || // Nothing to do.
1666 GetMaxNestedLoops() >= 32u || // Only 32 bits in suspend_checks_in_loops_[.].
1667 // Exclude 32 as well to keep bit shifts well-defined.
1668 !HasInvokes()) { // No invokes to actually eliminate any suspend checks.
1669 return false;
1670 }
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001671 suspend_checks_in_loops_ = arena_->AllocArray<uint32_t>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Marko8b858e12014-11-27 14:52:37 +00001672 return true;
1673}
1674
1675bool MIRGraph::EliminateSuspendChecks(BasicBlock* bb) {
1676 if (bb->block_type != kDalvikByteCode) {
1677 return false;
1678 }
1679 DCHECK_EQ(GetTopologicalSortOrderLoopHeadStack()->size(), bb->nesting_depth);
1680 if (bb->nesting_depth == 0u) {
1681 // Out of loops.
1682 DCHECK_EQ(suspend_checks_in_loops_[bb->id], 0u); // The array was zero-initialized.
1683 return false;
1684 }
1685 uint32_t suspend_checks_in_loops = (1u << bb->nesting_depth) - 1u; // Start with all loop heads.
1686 bool found_invoke = false;
1687 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko87b7c522015-04-08 10:01:01 +01001688 if ((IsInstructionInvoke(mir->dalvikInsn.opcode) ||
1689 IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) &&
1690 !GetMethodLoweringInfo(mir).IsIntrinsic()) {
Vladimir Marko8b858e12014-11-27 14:52:37 +00001691 // Non-intrinsic invoke, rely on a suspend point in the invoked method.
1692 found_invoke = true;
1693 break;
1694 }
1695 }
1696 if (!found_invoke) {
1697 // Intersect suspend checks from predecessors.
1698 uint16_t bb_topo_idx = topological_order_indexes_[bb->id];
1699 uint32_t pred_mask_union = 0u;
1700 for (BasicBlockId pred_id : bb->predecessors) {
1701 uint16_t pred_topo_idx = topological_order_indexes_[pred_id];
1702 if (pred_topo_idx < bb_topo_idx) {
1703 // Determine the loop depth of the predecessors relative to this block.
1704 size_t pred_loop_depth = topological_order_loop_head_stack_.size();
1705 while (pred_loop_depth != 0u &&
1706 pred_topo_idx < topological_order_loop_head_stack_[pred_loop_depth - 1].first) {
1707 --pred_loop_depth;
1708 }
1709 DCHECK_LE(pred_loop_depth, GetBasicBlock(pred_id)->nesting_depth);
1710 uint32_t pred_mask = (1u << pred_loop_depth) - 1u;
1711 // Intersect pred_mask bits in suspend_checks_in_loops with
1712 // suspend_checks_in_loops_[pred_id].
1713 uint32_t pred_loops_without_checks = pred_mask & ~suspend_checks_in_loops_[pred_id];
1714 suspend_checks_in_loops = suspend_checks_in_loops & ~pred_loops_without_checks;
1715 pred_mask_union |= pred_mask;
1716 }
1717 }
1718 DCHECK_EQ(((1u << (IsLoopHead(bb->id) ? bb->nesting_depth - 1u: bb->nesting_depth)) - 1u),
1719 pred_mask_union);
1720 suspend_checks_in_loops &= pred_mask_union;
1721 }
1722 suspend_checks_in_loops_[bb->id] = suspend_checks_in_loops;
1723 if (suspend_checks_in_loops == 0u) {
1724 return false;
1725 }
1726 // Apply MIR_IGNORE_SUSPEND_CHECK if appropriate.
1727 if (bb->taken != NullBasicBlockId) {
1728 DCHECK(bb->last_mir_insn != nullptr);
1729 DCHECK(IsInstructionIfCc(bb->last_mir_insn->dalvikInsn.opcode) ||
1730 IsInstructionIfCcZ(bb->last_mir_insn->dalvikInsn.opcode) ||
1731 IsInstructionGoto(bb->last_mir_insn->dalvikInsn.opcode) ||
1732 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) >= kMirOpFusedCmplFloat &&
1733 static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) <= kMirOpFusedCmpLong));
1734 if (!IsSuspendCheckEdge(bb, bb->taken) &&
1735 (bb->fall_through == NullBasicBlockId || !IsSuspendCheckEdge(bb, bb->fall_through))) {
1736 bb->last_mir_insn->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
1737 }
1738 } else if (bb->fall_through != NullBasicBlockId && IsSuspendCheckEdge(bb, bb->fall_through)) {
1739 // We've got a fall-through suspend edge. Add an artificial GOTO to force suspend check.
1740 MIR* mir = NewMIR();
1741 mir->dalvikInsn.opcode = Instruction::GOTO;
1742 mir->dalvikInsn.vA = 0; // Branch offset.
1743 mir->offset = GetBasicBlock(bb->fall_through)->start_offset;
1744 mir->m_unit_index = current_method_;
1745 mir->ssa_rep = reinterpret_cast<SSARepresentation*>(
1746 arena_->Alloc(sizeof(SSARepresentation), kArenaAllocDFInfo)); // Zero-initialized.
1747 bb->AppendMIR(mir);
1748 std::swap(bb->fall_through, bb->taken); // The fall-through has become taken.
1749 }
1750 return true;
1751}
1752
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001753bool MIRGraph::CanThrow(MIR* mir) const {
Ningsheng Jiana262f772014-11-25 16:48:07 +08001754 if ((mir->dalvikInsn.FlagsOf() & Instruction::kThrow) == 0) {
1755 return false;
1756 }
1757 const int opt_flags = mir->optimization_flags;
1758 uint64_t df_attributes = GetDataFlowAttributes(mir);
1759
Vladimir Marko315cc202014-12-18 17:01:02 +00001760 // First, check if the insn can still throw NPE.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001761 if (((df_attributes & DF_HAS_NULL_CHKS) != 0) && ((opt_flags & MIR_IGNORE_NULL_CHECK) == 0)) {
1762 return true;
1763 }
Vladimir Marko315cc202014-12-18 17:01:02 +00001764
1765 // Now process specific instructions.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001766 if ((df_attributes & DF_IFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001767 // The IGET/IPUT family. We have processed the IGET/IPUT null check above.
1768 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1769 // If not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001770 const MirIFieldLoweringInfo& field_info = GetIFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001771 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
1772 return !fast;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001773 } else if ((df_attributes & DF_SFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001774 // The SGET/SPUT family. Check for potentially throwing class initialization.
1775 // Also, if not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001776 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001777 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
Ningsheng Jiana262f772014-11-25 16:48:07 +08001778 bool is_class_initialized = field_info.IsClassInitialized() ||
1779 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0);
Vladimir Marko315cc202014-12-18 17:01:02 +00001780 return !(fast && is_class_initialized);
1781 } else if ((df_attributes & DF_HAS_RANGE_CHKS) != 0) {
1782 // Only AGET/APUT have range checks. We have processed the AGET/APUT null check above.
1783 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1784 // Non-throwing only if range check has been eliminated.
1785 return ((opt_flags & MIR_IGNORE_RANGE_CHECK) == 0);
Vladimir Marko22fe45d2015-03-18 11:33:58 +00001786 } else if (mir->dalvikInsn.opcode == Instruction::CHECK_CAST &&
1787 (opt_flags & MIR_IGNORE_CHECK_CAST) != 0) {
1788 return false;
Vladimir Marko315cc202014-12-18 17:01:02 +00001789 } else if (mir->dalvikInsn.opcode == Instruction::ARRAY_LENGTH ||
Vladimir Marko315cc202014-12-18 17:01:02 +00001790 static_cast<int>(mir->dalvikInsn.opcode) == kMirOpNullCheck) {
1791 // No more checks for these (null check was processed above).
1792 return false;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001793 }
1794 return true;
1795}
1796
1797bool MIRGraph::HasAntiDependency(MIR* first, MIR* second) {
1798 DCHECK(first->ssa_rep != nullptr);
1799 DCHECK(second->ssa_rep != nullptr);
1800 if ((second->ssa_rep->num_defs > 0) && (first->ssa_rep->num_uses > 0)) {
1801 int vreg0 = SRegToVReg(second->ssa_rep->defs[0]);
1802 int vreg1 = (second->ssa_rep->num_defs == 2) ?
1803 SRegToVReg(second->ssa_rep->defs[1]) : INVALID_VREG;
1804 for (int i = 0; i < first->ssa_rep->num_uses; i++) {
1805 int32_t use = SRegToVReg(first->ssa_rep->uses[i]);
1806 if (use == vreg0 || use == vreg1) {
1807 return true;
1808 }
1809 }
1810 }
1811 return false;
1812}
1813
1814void MIRGraph::CombineMultiplyAdd(MIR* mul_mir, MIR* add_mir, bool mul_is_first_addend,
1815 bool is_wide, bool is_sub) {
1816 if (is_wide) {
1817 if (is_sub) {
1818 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubLong);
1819 } else {
1820 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddLong);
1821 }
1822 } else {
1823 if (is_sub) {
1824 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubInt);
1825 } else {
1826 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddInt);
1827 }
1828 }
1829 add_mir->ssa_rep->num_uses = is_wide ? 6 : 3;
1830 int32_t addend0 = INVALID_SREG;
1831 int32_t addend1 = INVALID_SREG;
1832 if (is_wide) {
1833 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[2] : add_mir->ssa_rep->uses[0];
1834 addend1 = mul_is_first_addend ? add_mir->ssa_rep->uses[3] : add_mir->ssa_rep->uses[1];
1835 } else {
1836 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[1] : add_mir->ssa_rep->uses[0];
1837 }
1838
1839 AllocateSSAUseData(add_mir, add_mir->ssa_rep->num_uses);
1840 add_mir->ssa_rep->uses[0] = mul_mir->ssa_rep->uses[0];
1841 add_mir->ssa_rep->uses[1] = mul_mir->ssa_rep->uses[1];
1842 // Clear the original multiply product ssa use count, as it is not used anymore.
1843 raw_use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1844 use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1845 if (is_wide) {
1846 DCHECK_EQ(add_mir->ssa_rep->num_uses, 6);
1847 add_mir->ssa_rep->uses[2] = mul_mir->ssa_rep->uses[2];
1848 add_mir->ssa_rep->uses[3] = mul_mir->ssa_rep->uses[3];
1849 add_mir->ssa_rep->uses[4] = addend0;
1850 add_mir->ssa_rep->uses[5] = addend1;
1851 raw_use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1852 use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1853 } else {
1854 DCHECK_EQ(add_mir->ssa_rep->num_uses, 3);
1855 add_mir->ssa_rep->uses[2] = addend0;
1856 }
1857 // Copy in the decoded instruction information.
1858 add_mir->dalvikInsn.vB = SRegToVReg(add_mir->ssa_rep->uses[0]);
1859 if (is_wide) {
1860 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[2]);
1861 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[4]);
1862 } else {
1863 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[1]);
1864 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[2]);
1865 }
1866 // Original multiply MIR is set to Nop.
1867 mul_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1868}
1869
1870void MIRGraph::MultiplyAddOpt(BasicBlock* bb) {
1871 if (bb->block_type == kDead) {
1872 return;
1873 }
1874 ScopedArenaAllocator allocator(&cu_->arena_stack);
1875 ScopedArenaSafeMap<uint32_t, MIR*> ssa_mul_map(std::less<uint32_t>(), allocator.Adapter());
1876 ScopedArenaSafeMap<uint32_t, MIR*>::iterator map_it;
1877 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1878 Instruction::Code opcode = mir->dalvikInsn.opcode;
1879 bool is_sub = true;
1880 bool is_candidate_multiply = false;
1881 switch (opcode) {
1882 case Instruction::MUL_INT:
1883 case Instruction::MUL_INT_2ADDR:
1884 is_candidate_multiply = true;
1885 break;
1886 case Instruction::MUL_LONG:
1887 case Instruction::MUL_LONG_2ADDR:
1888 if (cu_->target64) {
1889 is_candidate_multiply = true;
1890 }
1891 break;
1892 case Instruction::ADD_INT:
1893 case Instruction::ADD_INT_2ADDR:
1894 is_sub = false;
1895 FALLTHROUGH_INTENDED;
1896 case Instruction::SUB_INT:
1897 case Instruction::SUB_INT_2ADDR:
1898 if (((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end()) && !is_sub) {
1899 // a*b+c
1900 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1901 false /* is_wide */, false /* is_sub */);
1902 ssa_mul_map.erase(mir->ssa_rep->uses[0]);
1903 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[1])) != ssa_mul_map.end()) {
1904 // c+a*b or c-a*b
1905 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1906 false /* is_wide */, is_sub);
1907 ssa_mul_map.erase(map_it);
1908 }
1909 break;
1910 case Instruction::ADD_LONG:
1911 case Instruction::ADD_LONG_2ADDR:
1912 is_sub = false;
1913 FALLTHROUGH_INTENDED;
1914 case Instruction::SUB_LONG:
1915 case Instruction::SUB_LONG_2ADDR:
1916 if (!cu_->target64) {
1917 break;
1918 }
1919 if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end() && !is_sub) {
1920 // a*b+c
1921 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1922 true /* is_wide */, false /* is_sub */);
1923 ssa_mul_map.erase(map_it);
1924 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[2])) != ssa_mul_map.end()) {
1925 // c+a*b or c-a*b
1926 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1927 true /* is_wide */, is_sub);
1928 ssa_mul_map.erase(map_it);
1929 }
1930 break;
1931 default:
1932 if (!ssa_mul_map.empty() && CanThrow(mir)) {
1933 // Should not combine multiply and add MIRs across potential exception.
1934 ssa_mul_map.clear();
1935 }
1936 break;
1937 }
1938
1939 // Exclude the case when an MIR writes a vreg which is previous candidate multiply MIR's uses.
1940 // It is because that current RA may allocate the same physical register to them. For this
1941 // kind of cases, the multiplier has been updated, we should not use updated value to the
1942 // multiply-add insn.
1943 if (ssa_mul_map.size() > 0) {
1944 for (auto it = ssa_mul_map.begin(); it != ssa_mul_map.end();) {
1945 MIR* mul = it->second;
1946 if (HasAntiDependency(mul, mir)) {
1947 it = ssa_mul_map.erase(it);
1948 } else {
1949 ++it;
1950 }
1951 }
1952 }
1953
1954 if (is_candidate_multiply &&
1955 (GetRawUseCount(mir->ssa_rep->defs[0]) == 1) && (mir->next != nullptr)) {
1956 ssa_mul_map.Put(mir->ssa_rep->defs[0], mir);
1957 }
1958 }
1959}
1960
buzbee311ca162013-02-28 15:56:43 -08001961} // namespace art