blob: 7679db8bac7f66b4fa6aa976761434df6a551022 [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"
Jeff Hao848f70a2014-01-15 13:49:50 -080021#include "dex/verified_method.h"
Andreas Gampe0b9203e2015-01-22 20:39:27 -080022#include "dex_flags.h"
23#include "driver/compiler_driver.h"
24#include "driver/dex_compilation_unit.h"
Vladimir Marko95a05972014-05-30 10:01:32 +010025#include "global_value_numbering.h"
Vladimir Marko7a01dc22015-01-02 17:00:44 +000026#include "gvn_dead_code_elimination.h"
buzbee311ca162013-02-28 15:56:43 -080027#include "local_value_numbering.h"
Vladimir Markoaf6925b2014-10-31 16:37:32 +000028#include "mir_field_info.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080029#include "mirror/string.h"
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070030#include "quick/dex_file_method_inliner.h"
31#include "quick/dex_file_to_method_inliner_map.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070032#include "stack.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080033#include "type_inference.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "utils.h"
buzbee311ca162013-02-28 15:56:43 -080035
36namespace art {
37
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070038static unsigned int Predecessors(BasicBlock* bb) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +010039 return bb->predecessors.size();
buzbee311ca162013-02-28 15:56:43 -080040}
41
42/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070043void MIRGraph::SetConstant(int32_t ssa_reg, int32_t value) {
buzbee862a7602013-04-05 10:58:54 -070044 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080045 constant_values_[ssa_reg] = value;
Vladimir Marko066f9e42015-01-16 16:04:43 +000046 reg_location_[ssa_reg].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080047}
48
Razvan A Lupusorud04d3092014-08-04 12:30:20 -070049void MIRGraph::SetConstantWide(int32_t ssa_reg, int64_t value) {
buzbee862a7602013-04-05 10:58:54 -070050 is_constant_v_->SetBit(ssa_reg);
Serguei Katkov597da1f2014-07-15 17:25:46 +070051 is_constant_v_->SetBit(ssa_reg + 1);
buzbee311ca162013-02-28 15:56:43 -080052 constant_values_[ssa_reg] = Low32Bits(value);
53 constant_values_[ssa_reg + 1] = High32Bits(value);
Vladimir Marko066f9e42015-01-16 16:04:43 +000054 reg_location_[ssa_reg].is_const = true;
55 reg_location_[ssa_reg + 1].is_const = true;
buzbee311ca162013-02-28 15:56:43 -080056}
57
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -080058void MIRGraph::DoConstantPropagation(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -080059 MIR* mir;
buzbee311ca162013-02-28 15:56:43 -080060
Mathieu Chartier2cebb242015-04-21 16:50:40 -070061 for (mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070062 // Skip pass if BB has MIR without SSA representation.
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070063 if (mir->ssa_rep == nullptr) {
Alexei Zavjalov9d894662014-04-21 20:45:24 +070064 return;
65 }
66
Jean Christophe Beylercc794c32014-05-02 09:34:13 -070067 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -080068
Ian Rogers29a26482014-05-02 15:27:29 -070069 MIR::DecodedInstruction* d_insn = &mir->dalvikInsn;
buzbee311ca162013-02-28 15:56:43 -080070
71 if (!(df_attributes & DF_HAS_DEFS)) continue;
72
73 /* Handle instructions that set up constants directly */
74 if (df_attributes & DF_SETS_CONST) {
75 if (df_attributes & DF_DA) {
76 int32_t vB = static_cast<int32_t>(d_insn->vB);
77 switch (d_insn->opcode) {
78 case Instruction::CONST_4:
79 case Instruction::CONST_16:
80 case Instruction::CONST:
81 SetConstant(mir->ssa_rep->defs[0], vB);
82 break;
83 case Instruction::CONST_HIGH16:
84 SetConstant(mir->ssa_rep->defs[0], vB << 16);
85 break;
86 case Instruction::CONST_WIDE_16:
87 case Instruction::CONST_WIDE_32:
88 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
89 break;
90 case Instruction::CONST_WIDE:
Brian Carlstromb1eba212013-07-17 18:07:19 -070091 SetConstantWide(mir->ssa_rep->defs[0], d_insn->vB_wide);
buzbee311ca162013-02-28 15:56:43 -080092 break;
93 case Instruction::CONST_WIDE_HIGH16:
94 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
95 break;
96 default:
97 break;
98 }
99 }
100 /* Handle instructions that set up constants directly */
101 } else if (df_attributes & DF_IS_MOVE) {
102 int i;
103
104 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
buzbee862a7602013-04-05 10:58:54 -0700105 if (!is_constant_v_->IsBitSet(mir->ssa_rep->uses[i])) break;
buzbee311ca162013-02-28 15:56:43 -0800106 }
107 /* Move a register holding a constant to another register */
108 if (i == mir->ssa_rep->num_uses) {
109 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
110 if (df_attributes & DF_A_WIDE) {
111 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
112 }
113 }
114 }
115 }
116 /* TODO: implement code to handle arithmetic operations */
buzbee311ca162013-02-28 15:56:43 -0800117}
118
buzbee311ca162013-02-28 15:56:43 -0800119/* Advance to next strictly dominated MIR node in an extended basic block */
buzbee0d829482013-10-11 15:24:55 -0700120MIR* MIRGraph::AdvanceMIR(BasicBlock** p_bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800121 BasicBlock* bb = *p_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 if (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800123 mir = mir->next;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700124 while (mir == nullptr) {
buzbee0d829482013-10-11 15:24:55 -0700125 bb = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 if ((bb == nullptr) || Predecessors(bb) != 1) {
Serguei Katkovea392162015-01-29 17:08:05 +0600127 // mir is null and we cannot proceed further.
128 break;
buzbee311ca162013-02-28 15:56:43 -0800129 } else {
Serguei Katkovea392162015-01-29 17:08:05 +0600130 *p_bb = bb;
131 mir = bb->first_mir_insn;
buzbee311ca162013-02-28 15:56:43 -0800132 }
133 }
134 }
135 return mir;
136}
137
138/*
139 * To be used at an invoke mir. If the logically next mir node represents
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700140 * a move-result, return it. Else, return nullptr. If a move-result exists,
buzbee311ca162013-02-28 15:56:43 -0800141 * it is required to immediately follow the invoke with no intervening
142 * opcodes or incoming arcs. However, if the result of the invoke is not
143 * used, a move-result may not be present.
144 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700145MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800146 BasicBlock* tbb = bb;
147 mir = AdvanceMIR(&tbb, mir);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700148 while (mir != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800149 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
150 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
151 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
152 break;
153 }
154 // Keep going if pseudo op, otherwise terminate
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -0700155 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee311ca162013-02-28 15:56:43 -0800156 mir = AdvanceMIR(&tbb, mir);
buzbee35ba7f32014-05-31 08:59:01 -0700157 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700158 mir = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800159 }
160 }
161 return mir;
162}
163
buzbee0d829482013-10-11 15:24:55 -0700164BasicBlock* MIRGraph::NextDominatedBlock(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800165 if (bb->block_type == kDead) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700166 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800167 }
168 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
169 || (bb->block_type == kExitBlock));
buzbee0d829482013-10-11 15:24:55 -0700170 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
171 BasicBlock* bb_fall_through = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700172 if (((bb_fall_through == nullptr) && (bb_taken != nullptr)) &&
buzbee0d829482013-10-11 15:24:55 -0700173 ((bb_taken->block_type == kDalvikByteCode) || (bb_taken->block_type == kExitBlock))) {
buzbeecbcfaf32013-08-19 07:37:40 -0700174 // Follow simple unconditional branches.
buzbee0d829482013-10-11 15:24:55 -0700175 bb = bb_taken;
buzbeecbcfaf32013-08-19 07:37:40 -0700176 } else {
177 // Follow simple fallthrough
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700178 bb = (bb_taken != nullptr) ? nullptr : bb_fall_through;
buzbeecbcfaf32013-08-19 07:37:40 -0700179 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700180 if (bb == nullptr || (Predecessors(bb) != 1)) {
181 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800182 }
183 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
184 return bb;
185}
186
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700187static MIR* FindPhi(BasicBlock* bb, int ssa_name) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700188 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800189 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
190 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
191 if (mir->ssa_rep->uses[i] == ssa_name) {
192 return mir;
193 }
194 }
195 }
196 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700197 return nullptr;
buzbee311ca162013-02-28 15:56:43 -0800198}
199
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700200static SelectInstructionKind SelectKind(MIR* mir) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700201 // Work with the case when mir is null.
Chao-ying Fu8ac41af2014-10-01 16:53:04 -0700202 if (mir == nullptr) {
203 return kSelectNone;
204 }
buzbee311ca162013-02-28 15:56:43 -0800205 switch (mir->dalvikInsn.opcode) {
206 case Instruction::MOVE:
207 case Instruction::MOVE_OBJECT:
208 case Instruction::MOVE_16:
209 case Instruction::MOVE_OBJECT_16:
210 case Instruction::MOVE_FROM16:
211 case Instruction::MOVE_OBJECT_FROM16:
212 return kSelectMove;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700213 case Instruction::CONST:
214 case Instruction::CONST_4:
215 case Instruction::CONST_16:
buzbee311ca162013-02-28 15:56:43 -0800216 return kSelectConst;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700217 case Instruction::GOTO:
218 case Instruction::GOTO_16:
219 case Instruction::GOTO_32:
buzbee311ca162013-02-28 15:56:43 -0800220 return kSelectGoto;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700221 default:
222 return kSelectNone;
buzbee311ca162013-02-28 15:56:43 -0800223 }
buzbee311ca162013-02-28 15:56:43 -0800224}
225
Vladimir Markoa1a70742014-03-03 10:28:05 +0000226static constexpr ConditionCode kIfCcZConditionCodes[] = {
227 kCondEq, kCondNe, kCondLt, kCondGe, kCondGt, kCondLe
228};
229
Andreas Gampe785d2f22014-11-03 22:57:30 -0800230static_assert(arraysize(kIfCcZConditionCodes) == Instruction::IF_LEZ - Instruction::IF_EQZ + 1,
231 "if_ccz_ccodes_size1");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000232
Vladimir Markoa1a70742014-03-03 10:28:05 +0000233static constexpr ConditionCode ConditionCodeForIfCcZ(Instruction::Code opcode) {
234 return kIfCcZConditionCodes[opcode - Instruction::IF_EQZ];
235}
236
Andreas Gampe785d2f22014-11-03 22:57:30 -0800237static_assert(ConditionCodeForIfCcZ(Instruction::IF_EQZ) == kCondEq, "if_eqz ccode");
238static_assert(ConditionCodeForIfCcZ(Instruction::IF_NEZ) == kCondNe, "if_nez ccode");
239static_assert(ConditionCodeForIfCcZ(Instruction::IF_LTZ) == kCondLt, "if_ltz ccode");
240static_assert(ConditionCodeForIfCcZ(Instruction::IF_GEZ) == kCondGe, "if_gez ccode");
241static_assert(ConditionCodeForIfCcZ(Instruction::IF_GTZ) == kCondGt, "if_gtz ccode");
242static_assert(ConditionCodeForIfCcZ(Instruction::IF_LEZ) == kCondLe, "if_lez ccode");
Vladimir Markoa1a70742014-03-03 10:28:05 +0000243
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700244int MIRGraph::GetSSAUseCount(int s_reg) {
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100245 DCHECK_LT(static_cast<size_t>(s_reg), ssa_subscripts_.size());
246 return raw_use_counts_[s_reg];
buzbee311ca162013-02-28 15:56:43 -0800247}
248
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700249size_t MIRGraph::GetNumBytesForSpecialTemps() const {
250 // This logic is written with assumption that Method* is only special temp.
251 DCHECK_EQ(max_available_special_compiler_temps_, 1u);
252 return sizeof(StackReference<mirror::ArtMethod>);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800253}
254
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700255size_t MIRGraph::GetNumAvailableVRTemps() {
256 // First take into account all temps reserved for backend.
257 if (max_available_non_special_compiler_temps_ < reserved_temps_for_backend_) {
258 return 0;
259 }
260
261 // Calculate remaining ME temps available.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700262 size_t remaining_me_temps = max_available_non_special_compiler_temps_ -
263 reserved_temps_for_backend_;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700264
265 if (num_non_special_compiler_temps_ >= remaining_me_temps) {
266 return 0;
267 } else {
268 return remaining_me_temps - num_non_special_compiler_temps_;
269 }
270}
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000271
272// FIXME - will probably need to revisit all uses of this, as type not defined.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800273static const RegLocation temp_loc = {kLocCompilerTemp,
buzbee091cc402014-03-31 10:14:40 -0700274 0, 1 /*defined*/, 0, 0, 0, 0, 0, 1 /*home*/,
Bill Buzbee00e1ec62014-02-27 23:44:13 +0000275 RegStorage(), INVALID_SREG, INVALID_SREG};
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800276
277CompilerTemp* MIRGraph::GetNewCompilerTemp(CompilerTempType ct_type, bool wide) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700278 // Once the compiler temps have been committed, new ones cannot be requested anymore.
279 DCHECK_EQ(compiler_temps_committed_, false);
280 // Make sure that reserved for BE set is sane.
281 DCHECK_LE(reserved_temps_for_backend_, max_available_non_special_compiler_temps_);
282
283 bool verbose = cu_->verbose;
284 const char* ct_type_str = nullptr;
285
286 if (verbose) {
287 switch (ct_type) {
288 case kCompilerTempBackend:
289 ct_type_str = "backend";
290 break;
291 case kCompilerTempSpecialMethodPtr:
292 ct_type_str = "method*";
293 break;
294 case kCompilerTempVR:
295 ct_type_str = "VR";
296 break;
297 default:
298 ct_type_str = "unknown";
299 break;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800300 }
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700301 LOG(INFO) << "CompilerTemps: A compiler temp of type " << ct_type_str << " that is "
302 << (wide ? "wide is being requested." : "not wide is being requested.");
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800303 }
304
305 CompilerTemp *compiler_temp = static_cast<CompilerTemp *>(arena_->Alloc(sizeof(CompilerTemp),
Vladimir Marko83cc7ae2014-02-12 18:02:05 +0000306 kArenaAllocRegAlloc));
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800307
308 // Create the type of temp requested. Special temps need special handling because
309 // they have a specific virtual register assignment.
310 if (ct_type == kCompilerTempSpecialMethodPtr) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700311 // This has a special location on stack which is 32-bit or 64-bit depending
312 // on mode. However, we don't want to overlap with non-special section
313 // and thus even for 64-bit, we allow only a non-wide temp to be requested.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800314 DCHECK_EQ(wide, false);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800315
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700316 // The vreg is always the first special temp for method ptr.
317 compiler_temp->v_reg = GetFirstSpecialTempVR();
318
319 } else if (ct_type == kCompilerTempBackend) {
320 requested_backend_temp_ = true;
321
322 // Make sure that we are not exceeding temps reserved for BE.
323 // Since VR temps cannot be requested once the BE temps are requested, we
324 // allow reservation of VR temps as well for BE. We
325 size_t available_temps = reserved_temps_for_backend_ + GetNumAvailableVRTemps();
Vladimir Markocc234812015-04-07 09:36:09 +0100326 size_t needed_temps = wide ? 2u : 1u;
327 if (available_temps < needed_temps) {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700328 if (verbose) {
Vladimir Markocc234812015-04-07 09:36:09 +0100329 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
330 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700331 }
332 return nullptr;
333 }
334
335 // Update the remaining reserved temps since we have now used them.
336 // Note that the code below is actually subtracting to remove them from reserve
337 // once they have been claimed. It is careful to not go below zero.
Vladimir Markocc234812015-04-07 09:36:09 +0100338 reserved_temps_for_backend_ =
339 std::max(reserved_temps_for_backend_, needed_temps) - needed_temps;
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700340
341 // The new non-special compiler temp must receive a unique v_reg.
342 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
343 num_non_special_compiler_temps_++;
344 } else if (ct_type == kCompilerTempVR) {
345 // Once we start giving out BE temps, we don't allow anymore ME temps to be requested.
346 // This is done in order to prevent problems with ssa since these structures are allocated
347 // and managed by the ME.
348 DCHECK_EQ(requested_backend_temp_, false);
349
350 // There is a limit to the number of non-special temps so check to make sure it wasn't exceeded.
351 size_t available_temps = GetNumAvailableVRTemps();
352 if (available_temps <= 0 || (available_temps <= 1 && wide)) {
353 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700354 LOG(INFO) << "CompilerTemps: Not enough temp(s) of type " << ct_type_str
355 << " are available.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700356 }
357 return nullptr;
358 }
359
360 // The new non-special compiler temp must receive a unique v_reg.
361 compiler_temp->v_reg = GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_;
362 num_non_special_compiler_temps_++;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800363 } else {
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700364 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << ct_type_str << ".";
365 }
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800366
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700367 // We allocate an sreg as well to make developer life easier.
368 // However, if this is requested from an ME pass that will recalculate ssa afterwards,
369 // this sreg is no longer valid. The caller should be aware of this.
370 compiler_temp->s_reg_low = AddNewSReg(compiler_temp->v_reg);
371
372 if (verbose) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700373 LOG(INFO) << "CompilerTemps: New temp of type " << ct_type_str << " with v"
374 << compiler_temp->v_reg << " and s" << compiler_temp->s_reg_low << " has been created.";
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700375 }
376
377 if (wide) {
378 // Only non-special temps are handled as wide for now.
379 // Note that the number of non special temps is incremented below.
380 DCHECK(ct_type == kCompilerTempBackend || ct_type == kCompilerTempVR);
381
382 // Ensure that the two registers are consecutive.
383 int ssa_reg_low = compiler_temp->s_reg_low;
384 int ssa_reg_high = AddNewSReg(compiler_temp->v_reg + 1);
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800385 num_non_special_compiler_temps_++;
386
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700387 if (verbose) {
388 LOG(INFO) << "CompilerTemps: The wide part of temp of type " << ct_type_str << " is v"
389 << compiler_temp->v_reg + 1 << " and s" << ssa_reg_high << ".";
390 }
Chao-ying Fu54d36b62014-05-22 17:25:02 -0700391
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700392 if (reg_location_ != nullptr) {
393 reg_location_[ssa_reg_high] = temp_loc;
394 reg_location_[ssa_reg_high].high_word = true;
395 reg_location_[ssa_reg_high].s_reg_low = ssa_reg_low;
396 reg_location_[ssa_reg_high].wide = true;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800397 }
398 }
399
Razvan A Lupusoru8d0d03e2014-06-06 17:04:52 -0700400 // If the register locations have already been allocated, add the information
401 // about the temp. We will not overflow because they have been initialized
402 // to support the maximum number of temps. For ME temps that have multiple
403 // ssa versions, the structures below will be expanded on the post pass cleanup.
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800404 if (reg_location_ != nullptr) {
405 int ssa_reg_low = compiler_temp->s_reg_low;
406 reg_location_[ssa_reg_low] = temp_loc;
407 reg_location_[ssa_reg_low].s_reg_low = ssa_reg_low;
408 reg_location_[ssa_reg_low].wide = wide;
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800409 }
410
Razvan A Lupusoruda7a69b2014-01-08 15:09:50 -0800411 return compiler_temp;
412}
buzbee311ca162013-02-28 15:56:43 -0800413
Vladimir Markocc234812015-04-07 09:36:09 +0100414void MIRGraph::RemoveLastCompilerTemp(CompilerTempType ct_type, bool wide, CompilerTemp* temp) {
415 // Once the compiler temps have been committed, it's too late for any modifications.
416 DCHECK_EQ(compiler_temps_committed_, false);
417
418 size_t used_temps = wide ? 2u : 1u;
419
420 if (ct_type == kCompilerTempBackend) {
421 DCHECK(requested_backend_temp_);
422
423 // Make the temps available to backend again.
424 reserved_temps_for_backend_ += used_temps;
425 } else if (ct_type == kCompilerTempVR) {
426 DCHECK(!requested_backend_temp_);
427 } else {
428 UNIMPLEMENTED(FATAL) << "No handling for compiler temp type " << static_cast<int>(ct_type);
429 }
430
431 // Reduce the number of non-special compiler temps.
432 DCHECK_LE(used_temps, num_non_special_compiler_temps_);
433 num_non_special_compiler_temps_ -= used_temps;
434
435 // Check that this was really the last temp.
436 DCHECK_EQ(static_cast<size_t>(temp->v_reg),
437 GetFirstNonSpecialTempVR() + num_non_special_compiler_temps_);
438
439 if (cu_->verbose) {
440 LOG(INFO) << "Last temporary has been removed.";
441 }
442}
443
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000444static bool EvaluateBranch(Instruction::Code opcode, int32_t src1, int32_t src2) {
445 bool is_taken;
446 switch (opcode) {
447 case Instruction::IF_EQ: is_taken = (src1 == src2); break;
448 case Instruction::IF_NE: is_taken = (src1 != src2); break;
449 case Instruction::IF_LT: is_taken = (src1 < src2); break;
450 case Instruction::IF_GE: is_taken = (src1 >= src2); break;
451 case Instruction::IF_GT: is_taken = (src1 > src2); break;
452 case Instruction::IF_LE: is_taken = (src1 <= src2); break;
453 case Instruction::IF_EQZ: is_taken = (src1 == 0); break;
454 case Instruction::IF_NEZ: is_taken = (src1 != 0); break;
455 case Instruction::IF_LTZ: is_taken = (src1 < 0); break;
456 case Instruction::IF_GEZ: is_taken = (src1 >= 0); break;
457 case Instruction::IF_GTZ: is_taken = (src1 > 0); break;
458 case Instruction::IF_LEZ: is_taken = (src1 <= 0); break;
459 default:
460 LOG(FATAL) << "Unexpected opcode " << opcode;
461 UNREACHABLE();
462 }
463 return is_taken;
464}
465
buzbee311ca162013-02-28 15:56:43 -0800466/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700467bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800468 if (bb->block_type == kDead) {
469 return true;
470 }
Ningsheng Jiana262f772014-11-25 16:48:07 +0800471 // Currently multiply-accumulate backend supports are only available on arm32 and arm64.
472 if (cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2) {
473 MultiplyAddOpt(bb);
474 }
Vladimir Marko415ac882014-09-30 18:09:14 +0100475 bool use_lvn = bb->use_lvn && (cu_->disable_opt & (1u << kLocalValueNumbering)) == 0u;
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100476 std::unique_ptr<ScopedArenaAllocator> allocator;
Vladimir Marko95a05972014-05-30 10:01:32 +0100477 std::unique_ptr<GlobalValueNumbering> global_valnum;
Ian Rogers700a4022014-05-19 16:49:03 -0700478 std::unique_ptr<LocalValueNumbering> local_valnum;
buzbee1da1e2f2013-11-15 13:37:01 -0800479 if (use_lvn) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100480 allocator.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko415ac882014-09-30 18:09:14 +0100481 global_valnum.reset(new (allocator.get()) GlobalValueNumbering(cu_, allocator.get(),
482 GlobalValueNumbering::kModeLvn));
Vladimir Markob19955d2014-07-29 12:04:10 +0100483 local_valnum.reset(new (allocator.get()) LocalValueNumbering(global_valnum.get(), bb->id,
484 allocator.get()));
buzbee1da1e2f2013-11-15 13:37:01 -0800485 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700486 while (bb != nullptr) {
487 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
buzbee311ca162013-02-28 15:56:43 -0800488 // TUNING: use the returned value number for CSE.
buzbee1da1e2f2013-11-15 13:37:01 -0800489 if (use_lvn) {
490 local_valnum->GetValueNumber(mir);
491 }
buzbee311ca162013-02-28 15:56:43 -0800492 // Look for interesting opcodes, skip otherwise
493 Instruction::Code opcode = mir->dalvikInsn.opcode;
494 switch (opcode) {
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000495 case Instruction::IF_EQ:
496 case Instruction::IF_NE:
497 case Instruction::IF_LT:
498 case Instruction::IF_GE:
499 case Instruction::IF_GT:
500 case Instruction::IF_LE:
501 if (!IsConst(mir->ssa_rep->uses[1])) {
502 break;
503 }
504 FALLTHROUGH_INTENDED;
505 case Instruction::IF_EQZ:
506 case Instruction::IF_NEZ:
507 case Instruction::IF_LTZ:
508 case Instruction::IF_GEZ:
509 case Instruction::IF_GTZ:
510 case Instruction::IF_LEZ:
511 // Result known at compile time?
512 if (IsConst(mir->ssa_rep->uses[0])) {
513 int32_t rhs = (mir->ssa_rep->num_uses == 2) ? ConstantValue(mir->ssa_rep->uses[1]) : 0;
514 bool is_taken = EvaluateBranch(opcode, ConstantValue(mir->ssa_rep->uses[0]), rhs);
515 BasicBlockId edge_to_kill = is_taken ? bb->fall_through : bb->taken;
516 if (is_taken) {
517 // Replace with GOTO.
518 bb->fall_through = NullBasicBlockId;
519 mir->dalvikInsn.opcode = Instruction::GOTO;
520 mir->dalvikInsn.vA =
521 IsInstructionIfCc(opcode) ? mir->dalvikInsn.vC : mir->dalvikInsn.vB;
522 } else {
523 // Make NOP.
524 bb->taken = NullBasicBlockId;
525 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
526 }
527 mir->ssa_rep->num_uses = 0;
528 BasicBlock* successor_to_unlink = GetBasicBlock(edge_to_kill);
529 successor_to_unlink->ErasePredecessor(bb->id);
Vladimir Marko341e4252014-12-19 10:29:51 +0000530 // We have changed the graph structure.
531 dfs_orders_up_to_date_ = false;
532 domination_up_to_date_ = false;
533 topological_order_up_to_date_ = false;
534 // Keep MIR SSA rep, the worst that can happen is a Phi with just 1 input.
Vladimir Marko7ab2fce2014-11-28 13:38:28 +0000535 }
536 break;
buzbee311ca162013-02-28 15:56:43 -0800537 case Instruction::CMPL_FLOAT:
538 case Instruction::CMPL_DOUBLE:
539 case Instruction::CMPG_FLOAT:
540 case Instruction::CMPG_DOUBLE:
541 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700542 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800543 // Bitcode doesn't allow this optimization.
544 break;
545 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700546 if (mir->next != nullptr) {
buzbee311ca162013-02-28 15:56:43 -0800547 MIR* mir_next = mir->next;
buzbee311ca162013-02-28 15:56:43 -0800548 // Make sure result of cmp is used by next insn and nowhere else
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700549 if (IsInstructionIfCcZ(mir_next->dalvikInsn.opcode) &&
buzbee311ca162013-02-28 15:56:43 -0800550 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
551 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
Vladimir Markoa1a70742014-03-03 10:28:05 +0000552 mir_next->meta.ccode = ConditionCodeForIfCcZ(mir_next->dalvikInsn.opcode);
Brian Carlstromdf629502013-07-17 22:39:56 -0700553 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800554 case Instruction::CMPL_FLOAT:
555 mir_next->dalvikInsn.opcode =
556 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
557 break;
558 case Instruction::CMPL_DOUBLE:
559 mir_next->dalvikInsn.opcode =
560 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
561 break;
562 case Instruction::CMPG_FLOAT:
563 mir_next->dalvikInsn.opcode =
564 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
565 break;
566 case Instruction::CMPG_DOUBLE:
567 mir_next->dalvikInsn.opcode =
568 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
569 break;
570 case Instruction::CMP_LONG:
571 mir_next->dalvikInsn.opcode =
572 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
573 break;
574 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
575 }
576 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
Zheng Xub218c852014-12-08 18:18:01 +0800577 // Clear use count of temp VR.
578 use_counts_[mir->ssa_rep->defs[0]] = 0;
579 raw_use_counts_[mir->ssa_rep->defs[0]] = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700580 // Copy the SSA information that is relevant.
buzbee311ca162013-02-28 15:56:43 -0800581 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
582 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
buzbee311ca162013-02-28 15:56:43 -0800583 mir_next->ssa_rep->num_defs = 0;
584 mir->ssa_rep->num_uses = 0;
585 mir->ssa_rep->num_defs = 0;
Jean Christophe Beylerc26efa82014-06-01 11:39:39 -0700586 // Copy in the decoded instruction information for potential SSA re-creation.
587 mir_next->dalvikInsn.vA = mir->dalvikInsn.vB;
588 mir_next->dalvikInsn.vB = mir->dalvikInsn.vC;
buzbee311ca162013-02-28 15:56:43 -0800589 }
590 }
591 break;
buzbee311ca162013-02-28 15:56:43 -0800592 default:
593 break;
594 }
595 // Is this the select pattern?
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800596 // TODO: flesh out support for Mips. NOTE: llvm's select op doesn't quite work here.
buzbee311ca162013-02-28 15:56:43 -0800597 // TUNING: expand to support IF_xx compare & branches
Elliott Hughes956af0f2014-12-11 14:34:28 -0800598 if ((cu_->instruction_set == kArm64 || cu_->instruction_set == kThumb2 ||
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100599 cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64) &&
Vladimir Markoa1a70742014-03-03 10:28:05 +0000600 IsInstructionIfCcZ(mir->dalvikInsn.opcode)) {
buzbee0d829482013-10-11 15:24:55 -0700601 BasicBlock* ft = GetBasicBlock(bb->fall_through);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700602 DCHECK(ft != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700603 BasicBlock* ft_ft = GetBasicBlock(ft->fall_through);
604 BasicBlock* ft_tk = GetBasicBlock(ft->taken);
buzbee311ca162013-02-28 15:56:43 -0800605
buzbee0d829482013-10-11 15:24:55 -0700606 BasicBlock* tk = GetBasicBlock(bb->taken);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700607 DCHECK(tk != nullptr);
buzbee0d829482013-10-11 15:24:55 -0700608 BasicBlock* tk_ft = GetBasicBlock(tk->fall_through);
609 BasicBlock* tk_tk = GetBasicBlock(tk->taken);
buzbee311ca162013-02-28 15:56:43 -0800610
611 /*
612 * In the select pattern, the taken edge goes to a block that unconditionally
613 * transfers to the rejoin block and the fall_though edge goes to a block that
614 * unconditionally falls through to the rejoin block.
615 */
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700616 if ((tk_ft == nullptr) && (ft_tk == nullptr) && (tk_tk == ft_ft) &&
buzbee311ca162013-02-28 15:56:43 -0800617 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
618 /*
Vladimir Marko8b858e12014-11-27 14:52:37 +0000619 * Okay - we have the basic diamond shape.
buzbee311ca162013-02-28 15:56:43 -0800620 */
Serban Constantinescu05e27ff2014-05-28 13:21:45 +0100621
622 // TODO: Add logic for LONG.
buzbee311ca162013-02-28 15:56:43 -0800623 // Are the block bodies something we can handle?
624 if ((ft->first_mir_insn == ft->last_mir_insn) &&
625 (tk->first_mir_insn != tk->last_mir_insn) &&
626 (tk->first_mir_insn->next == tk->last_mir_insn) &&
627 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
628 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
629 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
630 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
631 // Almost there. Are the instructions targeting the same vreg?
632 MIR* if_true = tk->first_mir_insn;
633 MIR* if_false = ft->first_mir_insn;
634 // It's possible that the target of the select isn't used - skip those (rare) cases.
635 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700636 if ((phi != nullptr) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
buzbee311ca162013-02-28 15:56:43 -0800637 /*
638 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
639 * Phi node in the merge block and delete it (while using the SSA name
640 * of the merge as the target of the SELECT. Delete both taken and
641 * fallthrough blocks, and set fallthrough to merge block.
642 * NOTE: not updating other dataflow info (no longer used at this point).
643 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
644 */
Vladimir Markoa1a70742014-03-03 10:28:05 +0000645 mir->meta.ccode = ConditionCodeForIfCcZ(mir->dalvikInsn.opcode);
buzbee311ca162013-02-28 15:56:43 -0800646 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
647 bool const_form = (SelectKind(if_true) == kSelectConst);
648 if ((SelectKind(if_true) == kSelectMove)) {
649 if (IsConst(if_true->ssa_rep->uses[0]) &&
650 IsConst(if_false->ssa_rep->uses[0])) {
651 const_form = true;
652 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
653 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
654 }
655 }
656 if (const_form) {
Razvan A Lupusorue27b3bf2014-01-23 09:41:45 -0800657 /*
658 * TODO: If both constants are the same value, then instead of generating
659 * a select, we should simply generate a const bytecode. This should be
660 * considered after inlining which can lead to CFG of this form.
661 */
buzbee311ca162013-02-28 15:56:43 -0800662 // "true" set val in vB
663 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
664 // "false" set val in vC
665 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
666 } else {
667 DCHECK_EQ(SelectKind(if_true), kSelectMove);
668 DCHECK_EQ(SelectKind(if_false), kSelectMove);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000669 int32_t* src_ssa = arena_->AllocArray<int32_t>(3, kArenaAllocDFInfo);
buzbee311ca162013-02-28 15:56:43 -0800670 src_ssa[0] = mir->ssa_rep->uses[0];
671 src_ssa[1] = if_true->ssa_rep->uses[0];
672 src_ssa[2] = if_false->ssa_rep->uses[0];
673 mir->ssa_rep->uses = src_ssa;
674 mir->ssa_rep->num_uses = 3;
675 }
Vladimir Markoc91df2d2015-04-23 09:29:21 +0000676 AllocateSSADefData(mir, 1);
buzbee311ca162013-02-28 15:56:43 -0800677 /*
678 * There is usually a Phi node in the join block for our two cases. If the
679 * Phi node only contains our two cases as input, we will use the result
680 * SSA name of the Phi node as our select result and delete the Phi. If
681 * the Phi node has more than two operands, we will arbitrarily use the SSA
Vladimir Marko341e4252014-12-19 10:29:51 +0000682 * name of the "false" path, delete the SSA name of the "true" path from the
buzbee311ca162013-02-28 15:56:43 -0800683 * Phi node (and fix up the incoming arc list).
684 */
685 if (phi->ssa_rep->num_uses == 2) {
686 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000687 // Rather than changing the Phi to kMirOpNop, remove it completely.
688 // This avoids leaving other Phis after kMirOpNop (i.e. a non-Phi) insn.
689 tk_tk->RemoveMIR(phi);
690 int dead_false_def = if_false->ssa_rep->defs[0];
691 raw_use_counts_[dead_false_def] = use_counts_[dead_false_def] = 0;
buzbee311ca162013-02-28 15:56:43 -0800692 } else {
Vladimir Marko341e4252014-12-19 10:29:51 +0000693 int live_def = if_false->ssa_rep->defs[0];
buzbee311ca162013-02-28 15:56:43 -0800694 mir->ssa_rep->defs[0] = live_def;
buzbee311ca162013-02-28 15:56:43 -0800695 }
Vladimir Marko341e4252014-12-19 10:29:51 +0000696 int dead_true_def = if_true->ssa_rep->defs[0];
697 raw_use_counts_[dead_true_def] = use_counts_[dead_true_def] = 0;
Vladimir Marko6e071832015-03-25 11:13:39 +0000698 // Update ending vreg->sreg map for GC maps generation.
699 int def_vreg = SRegToVReg(mir->ssa_rep->defs[0]);
700 bb->data_flow_info->vreg_to_ssa_map_exit[def_vreg] = mir->ssa_rep->defs[0];
Vladimir Marko341e4252014-12-19 10:29:51 +0000701 // We want to remove ft and tk and link bb directly to ft_ft. First, we need
702 // to update all Phi inputs correctly with UpdatePredecessor(ft->id, bb->id)
703 // since the live_def above comes from ft->first_mir_insn (if_false).
704 DCHECK(if_false == ft->first_mir_insn);
705 ft_ft->UpdatePredecessor(ft->id, bb->id);
706 // Correct the rest of the links between bb, ft and ft_ft.
707 ft->ErasePredecessor(bb->id);
708 ft->fall_through = NullBasicBlockId;
709 bb->fall_through = ft_ft->id;
710 // Now we can kill tk and ft.
711 tk->Kill(this);
712 ft->Kill(this);
713 // NOTE: DFS order, domination info and topological order are still usable
714 // despite the newly dead blocks.
buzbee311ca162013-02-28 15:56:43 -0800715 }
716 }
717 }
718 }
719 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700720 bb = ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) ? NextDominatedBlock(bb) :
721 nullptr;
buzbee311ca162013-02-28 15:56:43 -0800722 }
Vladimir Marko95a05972014-05-30 10:01:32 +0100723 if (use_lvn && UNLIKELY(!global_valnum->Good())) {
Vladimir Marko2ac01fc2014-05-22 12:09:08 +0100724 LOG(WARNING) << "LVN overflow in " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
725 }
buzbee311ca162013-02-28 15:56:43 -0800726
buzbee311ca162013-02-28 15:56:43 -0800727 return true;
728}
729
buzbee311ca162013-02-28 15:56:43 -0800730/* Collect stats on number of checks removed */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700731void MIRGraph::CountChecks(class BasicBlock* bb) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700732 if (bb->data_flow_info != nullptr) {
733 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
734 if (mir->ssa_rep == nullptr) {
buzbee862a7602013-04-05 10:58:54 -0700735 continue;
buzbee311ca162013-02-28 15:56:43 -0800736 }
Jean Christophe Beylercc794c32014-05-02 09:34:13 -0700737 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee862a7602013-04-05 10:58:54 -0700738 if (df_attributes & DF_HAS_NULL_CHKS) {
739 checkstats_->null_checks++;
740 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
741 checkstats_->null_checks_eliminated++;
742 }
743 }
744 if (df_attributes & DF_HAS_RANGE_CHKS) {
745 checkstats_->range_checks++;
746 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
747 checkstats_->range_checks_eliminated++;
748 }
buzbee311ca162013-02-28 15:56:43 -0800749 }
750 }
751 }
buzbee311ca162013-02-28 15:56:43 -0800752}
753
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700754/* Try to make common case the fallthrough path. */
buzbee0d829482013-10-11 15:24:55 -0700755bool MIRGraph::LayoutBlocks(BasicBlock* bb) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700756 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback.
buzbee311ca162013-02-28 15:56:43 -0800757 if (!bb->explicit_throw) {
758 return false;
759 }
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700760
761 // If we visited it, we are done.
762 if (bb->visited) {
763 return false;
764 }
765 bb->visited = true;
766
buzbee311ca162013-02-28 15:56:43 -0800767 BasicBlock* walker = bb;
768 while (true) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700769 // Check termination conditions.
buzbee311ca162013-02-28 15:56:43 -0800770 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
771 break;
772 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100773 DCHECK(!walker->predecessors.empty());
774 BasicBlock* prev = GetBasicBlock(walker->predecessors[0]);
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700775
776 // If we visited the predecessor, we are done.
777 if (prev->visited) {
778 return false;
779 }
780 prev->visited = true;
781
buzbee311ca162013-02-28 15:56:43 -0800782 if (prev->conditional_branch) {
buzbee0d829482013-10-11 15:24:55 -0700783 if (GetBasicBlock(prev->fall_through) == walker) {
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700784 // Already done - return.
buzbee311ca162013-02-28 15:56:43 -0800785 break;
786 }
buzbee0d829482013-10-11 15:24:55 -0700787 DCHECK_EQ(walker, GetBasicBlock(prev->taken));
Jean Christophe Beyler75bcc372014-09-04 08:15:11 -0700788 // Got one. Flip it and exit.
buzbee311ca162013-02-28 15:56:43 -0800789 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
790 switch (opcode) {
791 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
792 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
793 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
794 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
795 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
796 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
797 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
798 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
799 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
800 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
801 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
802 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
803 default: LOG(FATAL) << "Unexpected opcode " << opcode;
804 }
805 prev->last_mir_insn->dalvikInsn.opcode = opcode;
buzbee0d829482013-10-11 15:24:55 -0700806 BasicBlockId t_bb = prev->taken;
buzbee311ca162013-02-28 15:56:43 -0800807 prev->taken = prev->fall_through;
808 prev->fall_through = t_bb;
809 break;
810 }
811 walker = prev;
812 }
813 return false;
814}
815
816/* Combine any basic blocks terminated by instructions that we now know can't throw */
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700817void MIRGraph::CombineBlocks(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800818 // Loop here to allow combining a sequence of blocks
Vladimir Marko312eb252014-10-07 15:01:57 +0100819 while ((bb->block_type == kDalvikByteCode) &&
820 (bb->last_mir_insn != nullptr) &&
821 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) == kMirOpCheck)) {
822 MIR* mir = bb->last_mir_insn;
823 DCHECK(bb->first_mir_insn != nullptr);
824
Vladimir Marko315cc202014-12-18 17:01:02 +0000825 // Get the paired insn and check if it can still throw.
Vladimir Marko312eb252014-10-07 15:01:57 +0100826 MIR* throw_insn = mir->meta.throw_insn;
Vladimir Marko315cc202014-12-18 17:01:02 +0000827 if (CanThrow(throw_insn)) {
buzbee311ca162013-02-28 15:56:43 -0800828 break;
829 }
830
buzbee311ca162013-02-28 15:56:43 -0800831 // OK - got one. Combine
buzbee0d829482013-10-11 15:24:55 -0700832 BasicBlock* bb_next = GetBasicBlock(bb->fall_through);
buzbee311ca162013-02-28 15:56:43 -0800833 DCHECK(!bb_next->catch_entry);
Vladimir Marko312eb252014-10-07 15:01:57 +0100834 DCHECK_EQ(bb_next->predecessors.size(), 1u);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700835
836 // Now move instructions from bb_next to bb. Start off with doing a sanity check
837 // that kMirOpCheck's throw instruction is first one in the bb_next.
buzbee311ca162013-02-28 15:56:43 -0800838 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700839 // Now move all instructions (throw instruction to last one) from bb_next to bb.
840 MIR* last_to_move = bb_next->last_mir_insn;
841 bb_next->RemoveMIRList(throw_insn, last_to_move);
842 bb->InsertMIRListAfter(bb->last_mir_insn, throw_insn, last_to_move);
843 // The kMirOpCheck instruction is not needed anymore.
844 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
845 bb->RemoveMIR(mir);
846
Vladimir Marko312eb252014-10-07 15:01:57 +0100847 // Before we overwrite successors, remove their predecessor links to bb.
848 bb_next->ErasePredecessor(bb->id);
849 if (bb->taken != NullBasicBlockId) {
850 DCHECK_EQ(bb->successor_block_list_type, kNotUsed);
851 BasicBlock* bb_taken = GetBasicBlock(bb->taken);
852 // bb->taken will be overwritten below.
853 DCHECK_EQ(bb_taken->block_type, kExceptionHandling);
854 DCHECK_EQ(bb_taken->predecessors.size(), 1u);
855 DCHECK_EQ(bb_taken->predecessors[0], bb->id);
856 bb_taken->predecessors.clear();
857 bb_taken->block_type = kDead;
858 DCHECK(bb_taken->data_flow_info == nullptr);
859 } else {
860 DCHECK_EQ(bb->successor_block_list_type, kCatch);
861 for (SuccessorBlockInfo* succ_info : bb->successor_blocks) {
862 if (succ_info->block != NullBasicBlockId) {
863 BasicBlock* succ_bb = GetBasicBlock(succ_info->block);
864 DCHECK(succ_bb->catch_entry);
865 succ_bb->ErasePredecessor(bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100866 }
867 }
868 }
buzbee311ca162013-02-28 15:56:43 -0800869 // Use the successor info from the next block
buzbee0d829482013-10-11 15:24:55 -0700870 bb->successor_block_list_type = bb_next->successor_block_list_type;
Vladimir Markoe39c54e2014-09-22 14:50:02 +0100871 bb->successor_blocks.swap(bb_next->successor_blocks); // Swap instead of copying.
Vladimir Marko312eb252014-10-07 15:01:57 +0100872 bb_next->successor_block_list_type = kNotUsed;
buzbee311ca162013-02-28 15:56:43 -0800873 // Use the ending block linkage from the next block
874 bb->fall_through = bb_next->fall_through;
Vladimir Marko312eb252014-10-07 15:01:57 +0100875 bb_next->fall_through = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800876 bb->taken = bb_next->taken;
Vladimir Marko312eb252014-10-07 15:01:57 +0100877 bb_next->taken = NullBasicBlockId;
buzbee311ca162013-02-28 15:56:43 -0800878 /*
Junmo Parkf1770fd2014-08-12 09:34:54 +0900879 * If lower-half of pair of blocks to combine contained
880 * a return or a conditional branch or an explicit throw,
881 * move the flag to the newly combined block.
buzbee311ca162013-02-28 15:56:43 -0800882 */
883 bb->terminated_by_return = bb_next->terminated_by_return;
Junmo Parkf1770fd2014-08-12 09:34:54 +0900884 bb->conditional_branch = bb_next->conditional_branch;
885 bb->explicit_throw = bb_next->explicit_throw;
Vladimir Marko312eb252014-10-07 15:01:57 +0100886 // Merge the use_lvn flag.
887 bb->use_lvn |= bb_next->use_lvn;
888
889 // Kill the unused block.
890 bb_next->data_flow_info = nullptr;
buzbee311ca162013-02-28 15:56:43 -0800891
892 /*
893 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
894 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
Vladimir Marko312eb252014-10-07 15:01:57 +0100895 * NOTE: GVN uses bb->data_flow_info->live_in_v which is unaffected by the block merge.
buzbee311ca162013-02-28 15:56:43 -0800896 */
897
Vladimir Marko312eb252014-10-07 15:01:57 +0100898 // Kill bb_next and remap now-dead id to parent.
buzbee311ca162013-02-28 15:56:43 -0800899 bb_next->block_type = kDead;
Vladimir Marko312eb252014-10-07 15:01:57 +0100900 bb_next->data_flow_info = nullptr; // Must be null for dead blocks. (Relied on by the GVN.)
buzbee1fd33462013-03-25 13:40:45 -0700901 block_id_map_.Overwrite(bb_next->id, bb->id);
Vladimir Marko312eb252014-10-07 15:01:57 +0100902 // Update predecessors in children.
903 ChildBlockIterator iter(bb, this);
904 for (BasicBlock* child = iter.Next(); child != nullptr; child = iter.Next()) {
905 child->UpdatePredecessor(bb_next->id, bb->id);
906 }
907
Vladimir Markoffda4992014-12-18 17:05:58 +0000908 // DFS orders, domination and topological order are not up to date anymore.
Vladimir Marko312eb252014-10-07 15:01:57 +0100909 dfs_orders_up_to_date_ = false;
Vladimir Markoffda4992014-12-18 17:05:58 +0000910 domination_up_to_date_ = false;
911 topological_order_up_to_date_ = false;
buzbee311ca162013-02-28 15:56:43 -0800912
913 // Now, loop back and see if we can keep going
914 }
buzbee311ca162013-02-28 15:56:43 -0800915}
916
Vladimir Marko67c72b82014-10-09 12:26:10 +0100917bool MIRGraph::EliminateNullChecksGate() {
918 if ((cu_->disable_opt & (1 << kNullCheckElimination)) != 0 ||
919 (merged_df_flags_ & DF_HAS_NULL_CHKS) == 0) {
920 return false;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000921 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100922
Vladimir Marko67c72b82014-10-09 12:26:10 +0100923 DCHECK(temp_scoped_alloc_.get() == nullptr);
924 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -0700925 temp_.nce.num_vregs = GetNumOfCodeAndTempVRs();
Vladimir Markof585e542014-11-21 13:41:32 +0000926 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
927 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +0000928 temp_.nce.ending_vregs_to_check_matrix =
929 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +0000930 std::fill_n(temp_.nce.ending_vregs_to_check_matrix, GetNumBlocks(), nullptr);
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700931
932 // reset MIR_MARK
933 AllNodesIterator iter(this);
934 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700935 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Yevgeny Rouban423b1372014-10-15 17:32:25 +0700936 mir->optimization_flags &= ~MIR_MARK;
937 }
938 }
939
Vladimir Marko67c72b82014-10-09 12:26:10 +0100940 return true;
Vladimir Markobfea9c22014-01-17 17:49:33 +0000941}
942
buzbee1da1e2f2013-11-15 13:37:01 -0800943/*
Vladimir Marko67c72b82014-10-09 12:26:10 +0100944 * Eliminate unnecessary null checks for a basic block.
buzbee1da1e2f2013-11-15 13:37:01 -0800945 */
Vladimir Marko67c72b82014-10-09 12:26:10 +0100946bool MIRGraph::EliminateNullChecks(BasicBlock* bb) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100947 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
948 // Ignore the kExitBlock as well.
949 DCHECK(bb->first_mir_insn == nullptr);
950 return false;
951 }
buzbee311ca162013-02-28 15:56:43 -0800952
Vladimir Markof585e542014-11-21 13:41:32 +0000953 ArenaBitVector* vregs_to_check = temp_.nce.work_vregs_to_check;
Vladimir Marko67c72b82014-10-09 12:26:10 +0100954 /*
955 * Set initial state. Catch blocks don't need any special treatment.
956 */
957 if (bb->block_type == kEntryBlock) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100958 vregs_to_check->ClearAllBits();
Vladimir Marko67c72b82014-10-09 12:26:10 +0100959 // Assume all ins are objects.
960 for (uint16_t in_reg = GetFirstInVR();
961 in_reg < GetNumOfCodeVRs(); in_reg++) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100962 vregs_to_check->SetBit(in_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100963 }
964 if ((cu_->access_flags & kAccStatic) == 0) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100965 // If non-static method, mark "this" as non-null.
Vladimir Marko67c72b82014-10-09 12:26:10 +0100966 int this_reg = GetFirstInVR();
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100967 vregs_to_check->ClearBit(this_reg);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100968 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100969 } else {
970 DCHECK_EQ(bb->block_type, kDalvikByteCode);
971 // Starting state is union of all incoming arcs.
972 bool copied_first = false;
973 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +0000974 if (temp_.nce.ending_vregs_to_check_matrix[pred_id] == nullptr) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100975 continue;
976 }
977 BasicBlock* pred_bb = GetBasicBlock(pred_id);
978 DCHECK(pred_bb != nullptr);
979 MIR* null_check_insn = nullptr;
980 if (pred_bb->block_type == kDalvikByteCode) {
981 // Check to see if predecessor had an explicit null-check.
982 MIR* last_insn = pred_bb->last_mir_insn;
983 if (last_insn != nullptr) {
984 Instruction::Code last_opcode = last_insn->dalvikInsn.opcode;
985 if ((last_opcode == Instruction::IF_EQZ && pred_bb->fall_through == bb->id) ||
986 (last_opcode == Instruction::IF_NEZ && pred_bb->taken == bb->id)) {
987 // Remember the null check insn if there's no other predecessor requiring null check.
988 if (!copied_first || !vregs_to_check->IsBitSet(last_insn->dalvikInsn.vA)) {
989 null_check_insn = last_insn;
990 }
buzbee1da1e2f2013-11-15 13:37:01 -0800991 }
Ian Rogers22fd6a02013-06-13 15:06:54 -0700992 }
993 }
Vladimir Marko67c72b82014-10-09 12:26:10 +0100994 if (!copied_first) {
995 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +0000996 vregs_to_check->Copy(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko67c72b82014-10-09 12:26:10 +0100997 } else {
Vladimir Markof585e542014-11-21 13:41:32 +0000998 vregs_to_check->Union(temp_.nce.ending_vregs_to_check_matrix[pred_id]);
Vladimir Marko7baa6f82014-10-09 18:01:24 +0100999 }
1000 if (null_check_insn != nullptr) {
1001 vregs_to_check->ClearBit(null_check_insn->dalvikInsn.vA);
Vladimir Marko67c72b82014-10-09 12:26:10 +01001002 }
1003 }
1004 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
buzbee311ca162013-02-28 15:56:43 -08001005 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001006 // At this point, vregs_to_check shows which sregs have an object definition with
Vladimir Marko67c72b82014-10-09 12:26:10 +01001007 // no intervening uses.
buzbee311ca162013-02-28 15:56:43 -08001008
1009 // Walk through the instruction in the block, updating as necessary
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001010 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beylercc794c32014-05-02 09:34:13 -07001011 uint64_t df_attributes = GetDataFlowAttributes(mir);
buzbee311ca162013-02-28 15:56:43 -08001012
Razvan A Lupusoruc7a77bf2014-10-29 18:42:27 -07001013 if ((df_attributes & DF_NULL_TRANSFER_N) != 0u) {
1014 // The algorithm was written in a phi agnostic way.
1015 continue;
1016 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001017
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001018 // Might need a null check?
1019 if (df_attributes & DF_HAS_NULL_CHKS) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001020 int src_vreg;
1021 if (df_attributes & DF_NULL_CHK_OUT0) {
1022 DCHECK_NE(df_attributes & DF_IS_INVOKE, 0u);
1023 src_vreg = mir->dalvikInsn.vC;
1024 } else if (df_attributes & DF_NULL_CHK_B) {
1025 DCHECK_NE(df_attributes & DF_REF_B, 0u);
1026 src_vreg = mir->dalvikInsn.vB;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001027 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001028 DCHECK_NE(df_attributes & DF_NULL_CHK_A, 0u);
1029 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1030 src_vreg = mir->dalvikInsn.vA;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001031 }
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001032 if (!vregs_to_check->IsBitSet(src_vreg)) {
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001033 // Eliminate the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001034 mir->optimization_flags |= MIR_MARK;
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001035 } else {
1036 // Do the null check.
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001037 mir->optimization_flags &= ~MIR_MARK;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001038 // Mark src_vreg as null-checked.
1039 vregs_to_check->ClearBit(src_vreg);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001040 }
1041 }
1042
1043 if ((df_attributes & DF_A_WIDE) ||
1044 (df_attributes & (DF_REF_A | DF_SETS_CONST | DF_NULL_TRANSFER)) == 0) {
1045 continue;
1046 }
1047
1048 /*
1049 * First, mark all object definitions as requiring null check.
1050 * Note: we can't tell if a CONST definition might be used as an object, so treat
1051 * them all as object definitions.
1052 */
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001053 if ((df_attributes & (DF_DA | DF_REF_A)) == (DF_DA | DF_REF_A) ||
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001054 (df_attributes & DF_SETS_CONST)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001055 vregs_to_check->SetBit(mir->dalvikInsn.vA);
buzbee4db179d2013-10-23 12:16:39 -07001056 }
1057
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001058 // Then, remove mark from all object definitions we know are non-null.
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001059 if (df_attributes & DF_NON_NULL_DST) {
1060 // Mark target of NEW* as non-null
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001061 DCHECK_NE(df_attributes & DF_REF_A, 0u);
1062 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001063 }
1064
buzbee311ca162013-02-28 15:56:43 -08001065 // Mark non-null returns from invoke-style NEW*
1066 if (df_attributes & DF_NON_NULL_RET) {
1067 MIR* next_mir = mir->next;
1068 // Next should be an MOVE_RESULT_OBJECT
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001069 if (UNLIKELY(next_mir == nullptr)) {
1070 // The MethodVerifier makes sure there's no MOVE_RESULT at the catch entry or branch
1071 // target, so the MOVE_RESULT cannot be broken away into another block.
1072 LOG(WARNING) << "Unexpected end of block following new";
1073 } else if (UNLIKELY(next_mir->dalvikInsn.opcode != Instruction::MOVE_RESULT_OBJECT)) {
1074 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
buzbee311ca162013-02-28 15:56:43 -08001075 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001076 // Mark as null checked.
1077 vregs_to_check->ClearBit(next_mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001078 }
1079 }
1080
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001081 // Propagate null check state on register copies.
1082 if (df_attributes & DF_NULL_TRANSFER_0) {
1083 DCHECK_EQ(df_attributes | ~(DF_DA | DF_REF_A | DF_UB | DF_REF_B), static_cast<uint64_t>(-1));
1084 if (vregs_to_check->IsBitSet(mir->dalvikInsn.vB)) {
1085 vregs_to_check->SetBit(mir->dalvikInsn.vA);
Bill Buzbee0b1191c2013-10-28 22:11:59 +00001086 } else {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001087 vregs_to_check->ClearBit(mir->dalvikInsn.vA);
buzbee311ca162013-02-28 15:56:43 -08001088 }
1089 }
buzbee311ca162013-02-28 15:56:43 -08001090 }
1091
1092 // Did anything change?
Vladimir Markobfea9c22014-01-17 17:49:33 +00001093 bool nce_changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001094 ArenaBitVector* old_ending_ssa_regs_to_check = temp_.nce.ending_vregs_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001095 if (old_ending_ssa_regs_to_check == nullptr) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001096 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001097 nce_changed = vregs_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001098 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001099 // Create a new vregs_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001100 temp_.nce.work_vregs_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1101 temp_scoped_alloc_.get(), temp_.nce.num_vregs, false, kBitMapNullCheck);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001102 } else if (!vregs_to_check->SameBitsSet(old_ending_ssa_regs_to_check)) {
Vladimir Marko67c72b82014-10-09 12:26:10 +01001103 nce_changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001104 temp_.nce.ending_vregs_to_check_matrix[bb->id] = vregs_to_check;
1105 temp_.nce.work_vregs_to_check = old_ending_ssa_regs_to_check; // Reuse for next BB.
buzbee311ca162013-02-28 15:56:43 -08001106 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001107 return nce_changed;
buzbee311ca162013-02-28 15:56:43 -08001108}
1109
Vladimir Marko67c72b82014-10-09 12:26:10 +01001110void MIRGraph::EliminateNullChecksEnd() {
1111 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001112 temp_.nce.num_vregs = 0u;
1113 temp_.nce.work_vregs_to_check = nullptr;
1114 temp_.nce.ending_vregs_to_check_matrix = nullptr;
Vladimir Marko67c72b82014-10-09 12:26:10 +01001115 DCHECK(temp_scoped_alloc_.get() != nullptr);
1116 temp_scoped_alloc_.reset();
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001117
1118 // converge MIR_MARK with MIR_IGNORE_NULL_CHECK
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001119 AllNodesIterator iter(this);
1120 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001121 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001122 constexpr int kMarkToIgnoreNullCheckShift = kMIRMark - kMIRIgnoreNullCheck;
Andreas Gampe785d2f22014-11-03 22:57:30 -08001123 static_assert(kMarkToIgnoreNullCheckShift > 0, "Not a valid right-shift");
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001124 uint16_t mirMarkAdjustedToIgnoreNullCheck =
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001125 (mir->optimization_flags & MIR_MARK) >> kMarkToIgnoreNullCheckShift;
Yevgeny Rouban423b1372014-10-15 17:32:25 +07001126 mir->optimization_flags |= mirMarkAdjustedToIgnoreNullCheck;
1127 }
1128 }
Vladimir Marko67c72b82014-10-09 12:26:10 +01001129}
1130
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001131void MIRGraph::InferTypesStart() {
1132 DCHECK(temp_scoped_alloc_ != nullptr);
1133 temp_.ssa.ti = new (temp_scoped_alloc_.get()) TypeInference(this, temp_scoped_alloc_.get());
1134}
1135
Vladimir Marko67c72b82014-10-09 12:26:10 +01001136/*
1137 * Perform type and size inference for a basic block.
1138 */
1139bool MIRGraph::InferTypes(BasicBlock* bb) {
1140 if (bb->data_flow_info == nullptr) return false;
1141
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001142 DCHECK(temp_.ssa.ti != nullptr);
1143 return temp_.ssa.ti->Apply(bb);
1144}
Vladimir Marko67c72b82014-10-09 12:26:10 +01001145
Vladimir Markoc91df2d2015-04-23 09:29:21 +00001146void MIRGraph::InferTypesEnd() {
1147 DCHECK(temp_.ssa.ti != nullptr);
1148 temp_.ssa.ti->Finish();
1149 delete temp_.ssa.ti;
1150 temp_.ssa.ti = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001151}
1152
1153bool MIRGraph::EliminateClassInitChecksGate() {
1154 if ((cu_->disable_opt & (1 << kClassInitCheckElimination)) != 0 ||
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001155 (merged_df_flags_ & DF_CLINIT) == 0) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001156 return false;
1157 }
1158
Vladimir Markobfea9c22014-01-17 17:49:33 +00001159 DCHECK(temp_scoped_alloc_.get() == nullptr);
1160 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
1161
1162 // 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 -07001163 const size_t end = (GetNumDalvikInsns() + 1u) / 2u;
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001164 temp_.cice.indexes = temp_scoped_alloc_->AllocArray<uint16_t>(end, kArenaAllocGrowableArray);
Vladimir Markof585e542014-11-21 13:41:32 +00001165 std::fill_n(temp_.cice.indexes, end, 0xffffu);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001166
1167 uint32_t unique_class_count = 0u;
1168 {
1169 // Get unique_class_count and store indexes in temp_insn_data_ using a map on a nested
1170 // ScopedArenaAllocator.
1171
1172 // Embed the map value in the entry to save space.
1173 struct MapEntry {
1174 // Map key: the class identified by the declaring dex file and type index.
1175 const DexFile* declaring_dex_file;
1176 uint16_t declaring_class_idx;
1177 // Map value: index into bit vectors of classes requiring initialization checks.
1178 uint16_t index;
1179 };
1180 struct MapEntryComparator {
1181 bool operator()(const MapEntry& lhs, const MapEntry& rhs) const {
1182 if (lhs.declaring_class_idx != rhs.declaring_class_idx) {
1183 return lhs.declaring_class_idx < rhs.declaring_class_idx;
1184 }
1185 return lhs.declaring_dex_file < rhs.declaring_dex_file;
1186 }
1187 };
1188
Vladimir Markobfea9c22014-01-17 17:49:33 +00001189 ScopedArenaAllocator allocator(&cu_->arena_stack);
Vladimir Marko69f08ba2014-04-11 12:28:11 +01001190 ScopedArenaSet<MapEntry, MapEntryComparator> class_to_index_map(MapEntryComparator(),
1191 allocator.Adapter());
Vladimir Markobfea9c22014-01-17 17:49:33 +00001192
1193 // First, find all SGET/SPUTs that may need class initialization checks, record INVOKE_STATICs.
1194 AllNodesIterator iter(this);
1195 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001196 if (bb->block_type == kDalvikByteCode) {
1197 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001198 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001199 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001200 if (!field_info.IsReferrersClass()) {
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001201 DCHECK_LT(class_to_index_map.size(), 0xffffu);
1202 MapEntry entry = {
1203 // Treat unresolved fields as if each had its own class.
1204 field_info.IsResolved() ? field_info.DeclaringDexFile()
1205 : nullptr,
1206 field_info.IsResolved() ? field_info.DeclaringClassIndex()
1207 : field_info.FieldIndex(),
1208 static_cast<uint16_t>(class_to_index_map.size())
1209 };
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001210 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001211 // Using offset/2 for index into temp_.cice.indexes.
1212 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001213 }
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001214 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001215 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
1216 DCHECK(method_info.IsStatic());
1217 if (method_info.FastPath() && !method_info.IsReferrersClass()) {
1218 MapEntry entry = {
1219 method_info.DeclaringDexFile(),
1220 method_info.DeclaringClassIndex(),
1221 static_cast<uint16_t>(class_to_index_map.size())
1222 };
1223 uint16_t index = class_to_index_map.insert(entry).first->index;
Vladimir Markof585e542014-11-21 13:41:32 +00001224 // Using offset/2 for index into temp_.cice.indexes.
1225 temp_.cice.indexes[mir->offset / 2u] = index;
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001226 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001227 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001228 }
1229 }
1230 }
1231 unique_class_count = static_cast<uint32_t>(class_to_index_map.size());
1232 }
1233
1234 if (unique_class_count == 0u) {
1235 // All SGET/SPUTs refer to initialized classes. Nothing to do.
Vladimir Markof585e542014-11-21 13:41:32 +00001236 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001237 temp_scoped_alloc_.reset();
1238 return false;
1239 }
1240
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001241 // 2 bits for each class: is class initialized, is class in dex cache.
Vladimir Markof585e542014-11-21 13:41:32 +00001242 temp_.cice.num_class_bits = 2u * unique_class_count;
1243 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1244 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001245 temp_.cice.ending_classes_to_check_matrix =
1246 temp_scoped_alloc_->AllocArray<ArenaBitVector*>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Markof585e542014-11-21 13:41:32 +00001247 std::fill_n(temp_.cice.ending_classes_to_check_matrix, GetNumBlocks(), nullptr);
1248 DCHECK_GT(temp_.cice.num_class_bits, 0u);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001249 return true;
1250}
1251
1252/*
1253 * Eliminate unnecessary class initialization checks for a basic block.
1254 */
1255bool MIRGraph::EliminateClassInitChecks(BasicBlock* bb) {
1256 DCHECK_EQ((cu_->disable_opt & (1 << kClassInitCheckElimination)), 0u);
Vladimir Marko7baa6f82014-10-09 18:01:24 +01001257 if (bb->block_type != kDalvikByteCode && bb->block_type != kEntryBlock) {
1258 // Ignore the kExitBlock as well.
1259 DCHECK(bb->first_mir_insn == nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001260 return false;
1261 }
1262
1263 /*
Vladimir Marko0a810d22014-07-11 14:44:36 +01001264 * Set initial state. Catch blocks don't need any special treatment.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001265 */
Vladimir Markof585e542014-11-21 13:41:32 +00001266 ArenaBitVector* classes_to_check = temp_.cice.work_classes_to_check;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001267 DCHECK(classes_to_check != nullptr);
Vladimir Marko0a810d22014-07-11 14:44:36 +01001268 if (bb->block_type == kEntryBlock) {
Vladimir Markof585e542014-11-21 13:41:32 +00001269 classes_to_check->SetInitialBits(temp_.cice.num_class_bits);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001270 } else {
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001271 // Starting state is union of all incoming arcs.
1272 bool copied_first = false;
1273 for (BasicBlockId pred_id : bb->predecessors) {
Vladimir Markof585e542014-11-21 13:41:32 +00001274 if (temp_.cice.ending_classes_to_check_matrix[pred_id] == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001275 continue;
1276 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001277 if (!copied_first) {
1278 copied_first = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001279 classes_to_check->Copy(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001280 } else {
Vladimir Markof585e542014-11-21 13:41:32 +00001281 classes_to_check->Union(temp_.cice.ending_classes_to_check_matrix[pred_id]);
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001282 }
Vladimir Markobfea9c22014-01-17 17:49:33 +00001283 }
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001284 DCHECK(copied_first); // At least one predecessor must have been processed before this bb.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001285 }
1286 // At this point, classes_to_check shows which classes need clinit checks.
1287
1288 // Walk through the instruction in the block, updating as necessary
1289 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Markof585e542014-11-21 13:41:32 +00001290 uint16_t index = temp_.cice.indexes[mir->offset / 2u];
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001291 if (index != 0xffffu) {
1292 bool check_initialization = false;
1293 bool check_dex_cache = false;
1294
1295 // NOTE: index != 0xffff does not guarantee that this is an SGET/SPUT/INVOKE_STATIC.
1296 // Dex instructions with width 1 can have the same offset/2.
1297
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001298 if (IsInstructionSGetOrSPut(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001299 check_initialization = true;
1300 check_dex_cache = true;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001301 } else if (IsInstructionInvokeStatic(mir->dalvikInsn.opcode)) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001302 check_initialization = true;
1303 // NOTE: INVOKE_STATIC doesn't guarantee that the type will be in the dex cache.
1304 }
1305
1306 if (check_dex_cache) {
1307 uint32_t check_dex_cache_index = 2u * index + 1u;
1308 if (!classes_to_check->IsBitSet(check_dex_cache_index)) {
1309 // Eliminate the class init check.
1310 mir->optimization_flags |= MIR_CLASS_IS_IN_DEX_CACHE;
1311 } else {
1312 // Do the class init check.
1313 mir->optimization_flags &= ~MIR_CLASS_IS_IN_DEX_CACHE;
1314 }
1315 classes_to_check->ClearBit(check_dex_cache_index);
1316 }
1317 if (check_initialization) {
1318 uint32_t check_clinit_index = 2u * index;
1319 if (!classes_to_check->IsBitSet(check_clinit_index)) {
1320 // Eliminate the class init check.
1321 mir->optimization_flags |= MIR_CLASS_IS_INITIALIZED;
1322 } else {
1323 // Do the class init check.
1324 mir->optimization_flags &= ~MIR_CLASS_IS_INITIALIZED;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001325 }
1326 // Mark the class as initialized.
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001327 classes_to_check->ClearBit(check_clinit_index);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001328 }
1329 }
1330 }
1331
1332 // Did anything change?
1333 bool changed = false;
Vladimir Markof585e542014-11-21 13:41:32 +00001334 ArenaBitVector* old_ending_classes_to_check = temp_.cice.ending_classes_to_check_matrix[bb->id];
Vladimir Marko5229cf12014-10-09 14:57:59 +01001335 if (old_ending_classes_to_check == nullptr) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001336 DCHECK(temp_scoped_alloc_.get() != nullptr);
Vladimir Markobfea9c22014-01-17 17:49:33 +00001337 changed = classes_to_check->GetHighestBitSet() != -1;
Vladimir Markof585e542014-11-21 13:41:32 +00001338 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
Vladimir Marko5229cf12014-10-09 14:57:59 +01001339 // Create a new classes_to_check for next BB.
Vladimir Markof585e542014-11-21 13:41:32 +00001340 temp_.cice.work_classes_to_check = new (temp_scoped_alloc_.get()) ArenaBitVector(
1341 temp_scoped_alloc_.get(), temp_.cice.num_class_bits, false, kBitMapClInitCheck);
Vladimir Marko5229cf12014-10-09 14:57:59 +01001342 } else if (!classes_to_check->Equal(old_ending_classes_to_check)) {
Vladimir Markobfea9c22014-01-17 17:49:33 +00001343 changed = true;
Vladimir Markof585e542014-11-21 13:41:32 +00001344 temp_.cice.ending_classes_to_check_matrix[bb->id] = classes_to_check;
1345 temp_.cice.work_classes_to_check = old_ending_classes_to_check; // Reuse for next BB.
Vladimir Markobfea9c22014-01-17 17:49:33 +00001346 }
1347 return changed;
1348}
1349
1350void MIRGraph::EliminateClassInitChecksEnd() {
1351 // Clean up temporaries.
Vladimir Markof585e542014-11-21 13:41:32 +00001352 temp_.cice.num_class_bits = 0u;
1353 temp_.cice.work_classes_to_check = nullptr;
1354 temp_.cice.ending_classes_to_check_matrix = nullptr;
1355 DCHECK(temp_.cice.indexes != nullptr);
1356 temp_.cice.indexes = nullptr;
Vladimir Markobfea9c22014-01-17 17:49:33 +00001357 DCHECK(temp_scoped_alloc_.get() != nullptr);
1358 temp_scoped_alloc_.reset();
1359}
1360
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001361static void DisableGVNDependentOptimizations(CompilationUnit* cu) {
1362 cu->disable_opt |= (1u << kGvnDeadCodeElimination);
1363}
1364
Vladimir Marko95a05972014-05-30 10:01:32 +01001365bool MIRGraph::ApplyGlobalValueNumberingGate() {
Vladimir Marko415ac882014-09-30 18:09:14 +01001366 if (GlobalValueNumbering::Skip(cu_)) {
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001367 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001368 return false;
1369 }
1370
1371 DCHECK(temp_scoped_alloc_ == nullptr);
1372 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001373 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001374 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001375 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001376 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
Vladimir Markof585e542014-11-21 13:41:32 +00001377 DCHECK(temp_.gvn.gvn == nullptr);
1378 temp_.gvn.gvn = new (temp_scoped_alloc_.get()) GlobalValueNumbering(
1379 cu_, temp_scoped_alloc_.get(), GlobalValueNumbering::kModeGvn);
Vladimir Marko95a05972014-05-30 10:01:32 +01001380 return true;
1381}
1382
1383bool MIRGraph::ApplyGlobalValueNumbering(BasicBlock* bb) {
Vladimir Markof585e542014-11-21 13:41:32 +00001384 DCHECK(temp_.gvn.gvn != nullptr);
1385 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001386 if (lvn != nullptr) {
1387 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1388 lvn->GetValueNumber(mir);
1389 }
1390 }
Vladimir Markof585e542014-11-21 13:41:32 +00001391 bool change = (lvn != nullptr) && temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko95a05972014-05-30 10:01:32 +01001392 return change;
1393}
1394
1395void MIRGraph::ApplyGlobalValueNumberingEnd() {
1396 // Perform modifications.
Vladimir Markof585e542014-11-21 13:41:32 +00001397 DCHECK(temp_.gvn.gvn != nullptr);
1398 if (temp_.gvn.gvn->Good()) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001399 temp_.gvn.gvn->StartPostProcessing();
Vladimir Marko415ac882014-09-30 18:09:14 +01001400 if (max_nested_loops_ != 0u) {
Vladimir Marko415ac882014-09-30 18:09:14 +01001401 TopologicalSortIterator iter(this);
1402 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1403 ScopedArenaAllocator allocator(&cu_->arena_stack); // Reclaim memory after each LVN.
Vladimir Markof585e542014-11-21 13:41:32 +00001404 LocalValueNumbering* lvn = temp_.gvn.gvn->PrepareBasicBlock(bb, &allocator);
Vladimir Marko415ac882014-09-30 18:09:14 +01001405 if (lvn != nullptr) {
1406 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1407 lvn->GetValueNumber(mir);
1408 }
Vladimir Markof585e542014-11-21 13:41:32 +00001409 bool change = temp_.gvn.gvn->FinishBasicBlock(bb);
Vladimir Marko415ac882014-09-30 18:09:14 +01001410 DCHECK(!change) << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Vladimir Marko95a05972014-05-30 10:01:32 +01001411 }
Vladimir Marko95a05972014-05-30 10:01:32 +01001412 }
1413 }
Vladimir Marko415ac882014-09-30 18:09:14 +01001414 // GVN was successful, running the LVN would be useless.
1415 cu_->disable_opt |= (1u << kLocalValueNumbering);
Vladimir Marko95a05972014-05-30 10:01:32 +01001416 } else {
1417 LOG(WARNING) << "GVN failed for " << PrettyMethod(cu_->method_idx, *cu_->dex_file);
Andreas Gampe24d65cc2015-04-25 14:47:31 -07001418 DisableGVNDependentOptimizations(cu_);
Vladimir Marko95a05972014-05-30 10:01:32 +01001419 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001420}
1421
1422bool MIRGraph::EliminateDeadCodeGate() {
Vladimir Markoad677272015-04-20 10:48:13 +01001423 if ((cu_->disable_opt & (1 << kGvnDeadCodeElimination)) != 0 || temp_.gvn.gvn == nullptr) {
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001424 return false;
1425 }
1426 DCHECK(temp_scoped_alloc_ != nullptr);
1427 temp_.gvn.dce = new (temp_scoped_alloc_.get()) GvnDeadCodeElimination(temp_.gvn.gvn,
1428 temp_scoped_alloc_.get());
1429 return true;
1430}
1431
1432bool MIRGraph::EliminateDeadCode(BasicBlock* bb) {
1433 DCHECK(temp_scoped_alloc_ != nullptr);
1434 DCHECK(temp_.gvn.gvn != nullptr);
1435 if (bb->block_type != kDalvikByteCode) {
1436 return false;
1437 }
1438 DCHECK(temp_.gvn.dce != nullptr);
1439 temp_.gvn.dce->Apply(bb);
1440 return false; // No need to repeat.
1441}
1442
1443void MIRGraph::EliminateDeadCodeEnd() {
Vladimir Markoad677272015-04-20 10:48:13 +01001444 if (kIsDebugBuild) {
1445 // DCE can make some previously dead vregs alive again. Make sure the obsolete
1446 // live-in information is not used anymore.
1447 AllNodesIterator iter(this);
1448 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1449 if (bb->data_flow_info != nullptr) {
1450 bb->data_flow_info->live_in_v = nullptr;
1451 }
1452 }
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001453 }
Vladimir Markoad677272015-04-20 10:48:13 +01001454}
1455
1456void MIRGraph::GlobalValueNumberingCleanup() {
Vladimir Markof7255502015-04-25 17:00:45 +01001457 // If the GVN didn't run, these pointers should be null and everything is effectively no-op.
Vladimir Markoad677272015-04-20 10:48:13 +01001458 delete temp_.gvn.dce;
1459 temp_.gvn.dce = nullptr;
Vladimir Markof585e542014-11-21 13:41:32 +00001460 delete temp_.gvn.gvn;
1461 temp_.gvn.gvn = nullptr;
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001462 temp_.gvn.ifield_ids = nullptr;
1463 temp_.gvn.sfield_ids = nullptr;
Vladimir Marko95a05972014-05-30 10:01:32 +01001464 temp_scoped_alloc_.reset();
1465}
1466
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001467void MIRGraph::ComputeInlineIFieldLoweringInfo(uint16_t field_idx, MIR* invoke, MIR* iget_or_iput) {
1468 uint32_t method_index = invoke->meta.method_lowering_info;
Vladimir Markof585e542014-11-21 13:41:32 +00001469 if (temp_.smi.processed_indexes->IsBitSet(method_index)) {
1470 iget_or_iput->meta.ifield_lowering_info = temp_.smi.lowering_infos[method_index];
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001471 DCHECK_EQ(field_idx, GetIFieldLoweringInfo(iget_or_iput).FieldIndex());
1472 return;
1473 }
1474
1475 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(invoke);
1476 MethodReference target = method_info.GetTargetMethod();
1477 DexCompilationUnit inlined_unit(
1478 cu_, cu_->class_loader, cu_->class_linker, *target.dex_file,
1479 nullptr /* code_item not used */, 0u /* class_def_idx not used */, target.dex_method_index,
1480 0u /* access_flags not used */, nullptr /* verified_method not used */);
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001481 DexMemAccessType type = IGetOrIPutMemAccessType(iget_or_iput->dalvikInsn.opcode);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001482 MirIFieldLoweringInfo inlined_field_info(field_idx, type, false);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001483 MirIFieldLoweringInfo::Resolve(cu_->compiler_driver, &inlined_unit, &inlined_field_info, 1u);
1484 DCHECK(inlined_field_info.IsResolved());
1485
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001486 uint32_t field_info_index = ifield_lowering_infos_.size();
1487 ifield_lowering_infos_.push_back(inlined_field_info);
Vladimir Markof585e542014-11-21 13:41:32 +00001488 temp_.smi.processed_indexes->SetBit(method_index);
1489 temp_.smi.lowering_infos[method_index] = field_info_index;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001490 iget_or_iput->meta.ifield_lowering_info = field_info_index;
1491}
1492
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001493bool MIRGraph::InlineSpecialMethodsGate() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001494 if ((cu_->disable_opt & (1 << kSuppressMethodInlining)) != 0 ||
Vladimir Markoe39c54e2014-09-22 14:50:02 +01001495 method_lowering_infos_.size() == 0u) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001496 return false;
1497 }
1498 if (cu_->compiler_driver->GetMethodInlinerMap() == nullptr) {
1499 // This isn't the Quick compiler.
1500 return false;
1501 }
1502 return true;
1503}
1504
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001505void MIRGraph::InlineSpecialMethodsStart() {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001506 // Prepare for inlining getters/setters. Since we're inlining at most 1 IGET/IPUT from
1507 // each INVOKE, we can index the data by the MIR::meta::method_lowering_info index.
1508
1509 DCHECK(temp_scoped_alloc_.get() == nullptr);
1510 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Markof585e542014-11-21 13:41:32 +00001511 temp_.smi.num_indexes = method_lowering_infos_.size();
1512 temp_.smi.processed_indexes = new (temp_scoped_alloc_.get()) ArenaBitVector(
1513 temp_scoped_alloc_.get(), temp_.smi.num_indexes, false, kBitMapMisc);
1514 temp_.smi.processed_indexes->ClearAllBits();
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001515 temp_.smi.lowering_infos =
1516 temp_scoped_alloc_->AllocArray<uint16_t>(temp_.smi.num_indexes, kArenaAllocGrowableArray);
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001517}
1518
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001519void MIRGraph::InlineSpecialMethods(BasicBlock* bb) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001520 if (bb->block_type != kDalvikByteCode) {
1521 return;
1522 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001523 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Jean Christophe Beyler2ab40eb2014-06-02 09:03:14 -07001524 if (MIR::DecodedInstruction::IsPseudoMirOp(mir->dalvikInsn.opcode)) {
buzbee35ba7f32014-05-31 08:59:01 -07001525 continue;
1526 }
Jean Christophe Beylerfb0ea2d2014-07-29 13:20:42 -07001527 if (!(mir->dalvikInsn.FlagsOf() & Instruction::kInvoke)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001528 continue;
1529 }
1530 const MirMethodLoweringInfo& method_info = GetMethodLoweringInfo(mir);
Vladimir Marko87b7c522015-04-08 10:01:01 +01001531 if (!method_info.FastPath() || !method_info.IsSpecial()) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001532 continue;
1533 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001534
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001535 InvokeType sharp_type = method_info.GetSharpType();
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001536 if ((sharp_type != kDirect) && (sharp_type != kStatic)) {
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001537 continue;
1538 }
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001539
1540 if (sharp_type == kStatic) {
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001541 bool needs_clinit = !method_info.IsClassInitialized() &&
1542 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) == 0);
Razvan A Lupusoruc80605d2014-09-11 14:12:17 -07001543 if (needs_clinit) {
1544 continue;
1545 }
1546 }
1547
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001548 DCHECK(cu_->compiler_driver->GetMethodInlinerMap() != nullptr);
1549 MethodReference target = method_info.GetTargetMethod();
1550 if (cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(target.dex_file)
1551 ->GenInline(this, bb, mir, target.dex_method_index)) {
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001552 if (cu_->verbose || cu_->print_pass) {
1553 LOG(INFO) << "SpecialMethodInliner: Inlined " << method_info.GetInvokeType() << " ("
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001554 << sharp_type << ") call to \"" << PrettyMethod(target.dex_method_index,
1555 *target.dex_file)
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001556 << "\" from \"" << PrettyMethod(cu_->method_idx, *cu_->dex_file)
1557 << "\" @0x" << std::hex << mir->offset;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001558 }
1559 }
1560 }
1561}
1562
Razvan A Lupusorucb804742014-07-09 16:42:19 -07001563void MIRGraph::InlineSpecialMethodsEnd() {
Vladimir Markof585e542014-11-21 13:41:32 +00001564 // Clean up temporaries.
1565 DCHECK(temp_.smi.lowering_infos != nullptr);
1566 temp_.smi.lowering_infos = nullptr;
1567 temp_.smi.num_indexes = 0u;
1568 DCHECK(temp_.smi.processed_indexes != nullptr);
1569 temp_.smi.processed_indexes = nullptr;
Vladimir Marko9820b7c2014-01-02 16:40:37 +00001570 DCHECK(temp_scoped_alloc_.get() != nullptr);
1571 temp_scoped_alloc_.reset();
1572}
1573
Brian Carlstrom2ce745c2013-07-17 17:44:30 -07001574void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -08001575 Checkstats* stats =
Vladimir Marko83cc7ae2014-02-12 18:02:05 +00001576 static_cast<Checkstats*>(arena_->Alloc(sizeof(Checkstats), kArenaAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -07001577 checkstats_ = stats;
buzbee56c71782013-09-05 17:13:19 -07001578 AllNodesIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001579 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
buzbee311ca162013-02-28 15:56:43 -08001580 CountChecks(bb);
1581 }
1582 if (stats->null_checks > 0) {
1583 float eliminated = static_cast<float>(stats->null_checks_eliminated);
1584 float checks = static_cast<float>(stats->null_checks);
1585 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1586 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
1587 << (eliminated/checks) * 100.0 << "%";
1588 }
1589 if (stats->range_checks > 0) {
1590 float eliminated = static_cast<float>(stats->range_checks_eliminated);
1591 float checks = static_cast<float>(stats->range_checks);
1592 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
1593 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
1594 << (eliminated/checks) * 100.0 << "%";
1595 }
1596}
1597
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001598bool MIRGraph::BuildExtendedBBList(class BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -08001599 if (bb->visited) return false;
1600 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
1601 || (bb->block_type == kExitBlock))) {
1602 // Ignore special blocks
1603 bb->visited = true;
1604 return false;
1605 }
1606 // Must be head of extended basic block.
1607 BasicBlock* start_bb = bb;
buzbee0d829482013-10-11 15:24:55 -07001608 extended_basic_blocks_.push_back(bb->id);
buzbee311ca162013-02-28 15:56:43 -08001609 bool terminated_by_return = false;
buzbee1da1e2f2013-11-15 13:37:01 -08001610 bool do_local_value_numbering = false;
buzbee311ca162013-02-28 15:56:43 -08001611 // Visit blocks strictly dominated by this head.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001612 while (bb != nullptr) {
buzbee311ca162013-02-28 15:56:43 -08001613 bb->visited = true;
1614 terminated_by_return |= bb->terminated_by_return;
buzbee1da1e2f2013-11-15 13:37:01 -08001615 do_local_value_numbering |= bb->use_lvn;
buzbee311ca162013-02-28 15:56:43 -08001616 bb = NextDominatedBlock(bb);
1617 }
buzbee1da1e2f2013-11-15 13:37:01 -08001618 if (terminated_by_return || do_local_value_numbering) {
1619 // Do lvn for all blocks in this extended set.
buzbee311ca162013-02-28 15:56:43 -08001620 bb = start_bb;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001621 while (bb != nullptr) {
buzbee1da1e2f2013-11-15 13:37:01 -08001622 bb->use_lvn = do_local_value_numbering;
1623 bb->dominates_return = terminated_by_return;
buzbee311ca162013-02-28 15:56:43 -08001624 bb = NextDominatedBlock(bb);
1625 }
1626 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001627 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -08001628}
1629
Vladimir Markoffda4992014-12-18 17:05:58 +00001630void MIRGraph::BasicBlockOptimizationStart() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001631 if ((cu_->disable_opt & (1 << kLocalValueNumbering)) == 0) {
1632 temp_scoped_alloc_.reset(ScopedArenaAllocator::Create(&cu_->arena_stack));
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001633 temp_.gvn.ifield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001634 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), ifield_lowering_infos_);
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001635 temp_.gvn.sfield_ids =
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001636 GlobalValueNumbering::PrepareGvnFieldIds(temp_scoped_alloc_.get(), sfield_lowering_infos_);
1637 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001638}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001639
Vladimir Markoffda4992014-12-18 17:05:58 +00001640void MIRGraph::BasicBlockOptimization() {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001641 if ((cu_->disable_opt & (1 << kSuppressExceptionEdges)) != 0) {
1642 ClearAllVisitedFlags();
1643 PreOrderDfsIterator iter2(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001644 for (BasicBlock* bb = iter2.Next(); bb != nullptr; bb = iter2.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001645 BuildExtendedBBList(bb);
buzbee311ca162013-02-28 15:56:43 -08001646 }
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001647 // Perform extended basic block optimizations.
1648 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
1649 BasicBlockOpt(GetBasicBlock(extended_basic_blocks_[i]));
1650 }
1651 } else {
1652 PreOrderDfsIterator iter(this);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001653 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
Jean Christophe Beyler4e97c532014-01-07 10:07:18 -08001654 BasicBlockOpt(bb);
1655 }
buzbee311ca162013-02-28 15:56:43 -08001656 }
Vladimir Markoffda4992014-12-18 17:05:58 +00001657}
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001658
Vladimir Markoffda4992014-12-18 17:05:58 +00001659void MIRGraph::BasicBlockOptimizationEnd() {
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001660 // Clean up after LVN.
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001661 temp_.gvn.ifield_ids = nullptr;
1662 temp_.gvn.sfield_ids = nullptr;
Vladimir Markoaf6925b2014-10-31 16:37:32 +00001663 temp_scoped_alloc_.reset();
buzbee311ca162013-02-28 15:56:43 -08001664}
1665
Jeff Hao848f70a2014-01-15 13:49:50 -08001666void MIRGraph::StringChange() {
1667 AllNodesIterator iter(this);
1668 for (BasicBlock* bb = iter.Next(); bb != nullptr; bb = iter.Next()) {
1669 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1670 // Look for new instance opcodes, skip otherwise
1671 Instruction::Code opcode = mir->dalvikInsn.opcode;
1672 if (opcode == Instruction::NEW_INSTANCE) {
1673 uint32_t type_idx = mir->dalvikInsn.vB;
1674 if (cu_->compiler_driver->IsStringTypeIndex(type_idx, cu_->dex_file)) {
1675 // Change NEW_INSTANCE and throwing half of the insn (if it exists) into CONST_4 of 0
1676 mir->dalvikInsn.opcode = Instruction::CONST_4;
1677 mir->dalvikInsn.vB = 0;
1678 MIR* check_mir = GetBasicBlock(bb->predecessors[0])->last_mir_insn;
1679 if (check_mir != nullptr &&
1680 static_cast<int>(check_mir->dalvikInsn.opcode) == kMirOpCheck) {
1681 check_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1682 check_mir->dalvikInsn.vB = 0;
1683 }
1684 }
1685 } else if ((opcode == Instruction::INVOKE_DIRECT) ||
1686 (opcode == Instruction::INVOKE_DIRECT_RANGE)) {
1687 uint32_t method_idx = mir->dalvikInsn.vB;
1688 DexFileMethodInliner* inliner =
1689 cu_->compiler_driver->GetMethodInlinerMap()->GetMethodInliner(cu_->dex_file);
1690 if (inliner->IsStringInitMethodIndex(method_idx)) {
1691 bool is_range = (opcode == Instruction::INVOKE_DIRECT_RANGE);
1692 uint32_t orig_this_reg = is_range ? mir->dalvikInsn.vC : mir->dalvikInsn.arg[0];
1693 // Remove this pointer from string init and change to static call.
1694 mir->dalvikInsn.vA--;
1695 if (!is_range) {
1696 mir->dalvikInsn.opcode = Instruction::INVOKE_STATIC;
1697 for (uint32_t i = 0; i < mir->dalvikInsn.vA; i++) {
1698 mir->dalvikInsn.arg[i] = mir->dalvikInsn.arg[i + 1];
1699 }
1700 } else {
1701 mir->dalvikInsn.opcode = Instruction::INVOKE_STATIC_RANGE;
1702 mir->dalvikInsn.vC++;
1703 }
1704 // Insert a move-result instruction to the original this pointer reg.
1705 MIR* move_result_mir = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
1706 move_result_mir->dalvikInsn.opcode = Instruction::MOVE_RESULT_OBJECT;
1707 move_result_mir->dalvikInsn.vA = orig_this_reg;
1708 move_result_mir->offset = mir->offset;
1709 move_result_mir->m_unit_index = mir->m_unit_index;
1710 bb->InsertMIRAfter(mir, move_result_mir);
1711 // Add additional moves if this pointer was copied to other registers.
1712 const VerifiedMethod* verified_method =
1713 cu_->compiler_driver->GetVerifiedMethod(cu_->dex_file, cu_->method_idx);
1714 DCHECK(verified_method != nullptr);
1715 const SafeMap<uint32_t, std::set<uint32_t>>& string_init_map =
1716 verified_method->GetStringInitPcRegMap();
1717 auto map_it = string_init_map.find(mir->offset);
1718 if (map_it != string_init_map.end()) {
1719 const std::set<uint32_t>& reg_set = map_it->second;
1720 for (auto set_it = reg_set.begin(); set_it != reg_set.end(); ++set_it) {
1721 MIR* move_mir = static_cast<MIR *>(arena_->Alloc(sizeof(MIR), kArenaAllocMIR));
1722 move_mir->dalvikInsn.opcode = Instruction::MOVE_OBJECT;
1723 move_mir->dalvikInsn.vA = *set_it;
1724 move_mir->dalvikInsn.vB = orig_this_reg;
1725 move_mir->offset = mir->offset;
1726 move_mir->m_unit_index = mir->m_unit_index;
1727 bb->InsertMIRAfter(move_result_mir, move_mir);
1728 }
1729 }
1730 }
1731 }
1732 }
1733 }
1734}
1735
1736
Vladimir Marko8b858e12014-11-27 14:52:37 +00001737bool MIRGraph::EliminateSuspendChecksGate() {
1738 if ((cu_->disable_opt & (1 << kSuspendCheckElimination)) != 0 || // Disabled.
1739 GetMaxNestedLoops() == 0u || // Nothing to do.
1740 GetMaxNestedLoops() >= 32u || // Only 32 bits in suspend_checks_in_loops_[.].
1741 // Exclude 32 as well to keep bit shifts well-defined.
1742 !HasInvokes()) { // No invokes to actually eliminate any suspend checks.
1743 return false;
1744 }
Vladimir Markoe4fcc5b2015-02-13 10:28:29 +00001745 suspend_checks_in_loops_ = arena_->AllocArray<uint32_t>(GetNumBlocks(), kArenaAllocMisc);
Vladimir Marko8b858e12014-11-27 14:52:37 +00001746 return true;
1747}
1748
1749bool MIRGraph::EliminateSuspendChecks(BasicBlock* bb) {
1750 if (bb->block_type != kDalvikByteCode) {
1751 return false;
1752 }
1753 DCHECK_EQ(GetTopologicalSortOrderLoopHeadStack()->size(), bb->nesting_depth);
1754 if (bb->nesting_depth == 0u) {
1755 // Out of loops.
1756 DCHECK_EQ(suspend_checks_in_loops_[bb->id], 0u); // The array was zero-initialized.
1757 return false;
1758 }
1759 uint32_t suspend_checks_in_loops = (1u << bb->nesting_depth) - 1u; // Start with all loop heads.
1760 bool found_invoke = false;
1761 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
Vladimir Marko87b7c522015-04-08 10:01:01 +01001762 if ((IsInstructionInvoke(mir->dalvikInsn.opcode) ||
1763 IsInstructionQuickInvoke(mir->dalvikInsn.opcode)) &&
1764 !GetMethodLoweringInfo(mir).IsIntrinsic()) {
Vladimir Marko8b858e12014-11-27 14:52:37 +00001765 // Non-intrinsic invoke, rely on a suspend point in the invoked method.
1766 found_invoke = true;
1767 break;
1768 }
1769 }
1770 if (!found_invoke) {
1771 // Intersect suspend checks from predecessors.
1772 uint16_t bb_topo_idx = topological_order_indexes_[bb->id];
1773 uint32_t pred_mask_union = 0u;
1774 for (BasicBlockId pred_id : bb->predecessors) {
1775 uint16_t pred_topo_idx = topological_order_indexes_[pred_id];
1776 if (pred_topo_idx < bb_topo_idx) {
1777 // Determine the loop depth of the predecessors relative to this block.
1778 size_t pred_loop_depth = topological_order_loop_head_stack_.size();
1779 while (pred_loop_depth != 0u &&
1780 pred_topo_idx < topological_order_loop_head_stack_[pred_loop_depth - 1].first) {
1781 --pred_loop_depth;
1782 }
1783 DCHECK_LE(pred_loop_depth, GetBasicBlock(pred_id)->nesting_depth);
1784 uint32_t pred_mask = (1u << pred_loop_depth) - 1u;
1785 // Intersect pred_mask bits in suspend_checks_in_loops with
1786 // suspend_checks_in_loops_[pred_id].
1787 uint32_t pred_loops_without_checks = pred_mask & ~suspend_checks_in_loops_[pred_id];
1788 suspend_checks_in_loops = suspend_checks_in_loops & ~pred_loops_without_checks;
1789 pred_mask_union |= pred_mask;
1790 }
1791 }
1792 DCHECK_EQ(((1u << (IsLoopHead(bb->id) ? bb->nesting_depth - 1u: bb->nesting_depth)) - 1u),
1793 pred_mask_union);
1794 suspend_checks_in_loops &= pred_mask_union;
1795 }
1796 suspend_checks_in_loops_[bb->id] = suspend_checks_in_loops;
1797 if (suspend_checks_in_loops == 0u) {
1798 return false;
1799 }
1800 // Apply MIR_IGNORE_SUSPEND_CHECK if appropriate.
1801 if (bb->taken != NullBasicBlockId) {
1802 DCHECK(bb->last_mir_insn != nullptr);
1803 DCHECK(IsInstructionIfCc(bb->last_mir_insn->dalvikInsn.opcode) ||
1804 IsInstructionIfCcZ(bb->last_mir_insn->dalvikInsn.opcode) ||
1805 IsInstructionGoto(bb->last_mir_insn->dalvikInsn.opcode) ||
1806 (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) >= kMirOpFusedCmplFloat &&
1807 static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) <= kMirOpFusedCmpLong));
1808 if (!IsSuspendCheckEdge(bb, bb->taken) &&
1809 (bb->fall_through == NullBasicBlockId || !IsSuspendCheckEdge(bb, bb->fall_through))) {
1810 bb->last_mir_insn->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
1811 }
1812 } else if (bb->fall_through != NullBasicBlockId && IsSuspendCheckEdge(bb, bb->fall_through)) {
1813 // We've got a fall-through suspend edge. Add an artificial GOTO to force suspend check.
1814 MIR* mir = NewMIR();
1815 mir->dalvikInsn.opcode = Instruction::GOTO;
1816 mir->dalvikInsn.vA = 0; // Branch offset.
1817 mir->offset = GetBasicBlock(bb->fall_through)->start_offset;
1818 mir->m_unit_index = current_method_;
1819 mir->ssa_rep = reinterpret_cast<SSARepresentation*>(
1820 arena_->Alloc(sizeof(SSARepresentation), kArenaAllocDFInfo)); // Zero-initialized.
1821 bb->AppendMIR(mir);
1822 std::swap(bb->fall_through, bb->taken); // The fall-through has become taken.
1823 }
1824 return true;
1825}
1826
Vladimir Marko7a01dc22015-01-02 17:00:44 +00001827bool MIRGraph::CanThrow(MIR* mir) const {
Ningsheng Jiana262f772014-11-25 16:48:07 +08001828 if ((mir->dalvikInsn.FlagsOf() & Instruction::kThrow) == 0) {
1829 return false;
1830 }
1831 const int opt_flags = mir->optimization_flags;
1832 uint64_t df_attributes = GetDataFlowAttributes(mir);
1833
Vladimir Marko315cc202014-12-18 17:01:02 +00001834 // First, check if the insn can still throw NPE.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001835 if (((df_attributes & DF_HAS_NULL_CHKS) != 0) && ((opt_flags & MIR_IGNORE_NULL_CHECK) == 0)) {
1836 return true;
1837 }
Vladimir Marko315cc202014-12-18 17:01:02 +00001838
1839 // Now process specific instructions.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001840 if ((df_attributes & DF_IFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001841 // The IGET/IPUT family. We have processed the IGET/IPUT null check above.
1842 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1843 // If not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001844 const MirIFieldLoweringInfo& field_info = GetIFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001845 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
1846 return !fast;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001847 } else if ((df_attributes & DF_SFIELD) != 0) {
Vladimir Marko315cc202014-12-18 17:01:02 +00001848 // The SGET/SPUT family. Check for potentially throwing class initialization.
1849 // Also, if not fast, weird things can happen and the insn can throw.
Ningsheng Jiana262f772014-11-25 16:48:07 +08001850 const MirSFieldLoweringInfo& field_info = GetSFieldLoweringInfo(mir);
Vladimir Marko315cc202014-12-18 17:01:02 +00001851 bool fast = (df_attributes & DF_DA) != 0 ? field_info.FastGet() : field_info.FastPut();
Ningsheng Jiana262f772014-11-25 16:48:07 +08001852 bool is_class_initialized = field_info.IsClassInitialized() ||
1853 ((mir->optimization_flags & MIR_CLASS_IS_INITIALIZED) != 0);
Vladimir Marko315cc202014-12-18 17:01:02 +00001854 return !(fast && is_class_initialized);
1855 } else if ((df_attributes & DF_HAS_RANGE_CHKS) != 0) {
1856 // Only AGET/APUT have range checks. We have processed the AGET/APUT null check above.
1857 DCHECK_NE(opt_flags & MIR_IGNORE_NULL_CHECK, 0);
1858 // Non-throwing only if range check has been eliminated.
1859 return ((opt_flags & MIR_IGNORE_RANGE_CHECK) == 0);
Vladimir Marko22fe45d2015-03-18 11:33:58 +00001860 } else if (mir->dalvikInsn.opcode == Instruction::CHECK_CAST &&
1861 (opt_flags & MIR_IGNORE_CHECK_CAST) != 0) {
1862 return false;
Vladimir Marko315cc202014-12-18 17:01:02 +00001863 } else if (mir->dalvikInsn.opcode == Instruction::ARRAY_LENGTH ||
Vladimir Marko315cc202014-12-18 17:01:02 +00001864 static_cast<int>(mir->dalvikInsn.opcode) == kMirOpNullCheck) {
1865 // No more checks for these (null check was processed above).
1866 return false;
Ningsheng Jiana262f772014-11-25 16:48:07 +08001867 }
1868 return true;
1869}
1870
1871bool MIRGraph::HasAntiDependency(MIR* first, MIR* second) {
1872 DCHECK(first->ssa_rep != nullptr);
1873 DCHECK(second->ssa_rep != nullptr);
1874 if ((second->ssa_rep->num_defs > 0) && (first->ssa_rep->num_uses > 0)) {
1875 int vreg0 = SRegToVReg(second->ssa_rep->defs[0]);
1876 int vreg1 = (second->ssa_rep->num_defs == 2) ?
1877 SRegToVReg(second->ssa_rep->defs[1]) : INVALID_VREG;
1878 for (int i = 0; i < first->ssa_rep->num_uses; i++) {
1879 int32_t use = SRegToVReg(first->ssa_rep->uses[i]);
1880 if (use == vreg0 || use == vreg1) {
1881 return true;
1882 }
1883 }
1884 }
1885 return false;
1886}
1887
1888void MIRGraph::CombineMultiplyAdd(MIR* mul_mir, MIR* add_mir, bool mul_is_first_addend,
1889 bool is_wide, bool is_sub) {
1890 if (is_wide) {
1891 if (is_sub) {
1892 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubLong);
1893 } else {
1894 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddLong);
1895 }
1896 } else {
1897 if (is_sub) {
1898 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMsubInt);
1899 } else {
1900 add_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpMaddInt);
1901 }
1902 }
1903 add_mir->ssa_rep->num_uses = is_wide ? 6 : 3;
1904 int32_t addend0 = INVALID_SREG;
1905 int32_t addend1 = INVALID_SREG;
1906 if (is_wide) {
1907 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[2] : add_mir->ssa_rep->uses[0];
1908 addend1 = mul_is_first_addend ? add_mir->ssa_rep->uses[3] : add_mir->ssa_rep->uses[1];
1909 } else {
1910 addend0 = mul_is_first_addend ? add_mir->ssa_rep->uses[1] : add_mir->ssa_rep->uses[0];
1911 }
1912
1913 AllocateSSAUseData(add_mir, add_mir->ssa_rep->num_uses);
1914 add_mir->ssa_rep->uses[0] = mul_mir->ssa_rep->uses[0];
1915 add_mir->ssa_rep->uses[1] = mul_mir->ssa_rep->uses[1];
1916 // Clear the original multiply product ssa use count, as it is not used anymore.
1917 raw_use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1918 use_counts_[mul_mir->ssa_rep->defs[0]] = 0;
1919 if (is_wide) {
1920 DCHECK_EQ(add_mir->ssa_rep->num_uses, 6);
1921 add_mir->ssa_rep->uses[2] = mul_mir->ssa_rep->uses[2];
1922 add_mir->ssa_rep->uses[3] = mul_mir->ssa_rep->uses[3];
1923 add_mir->ssa_rep->uses[4] = addend0;
1924 add_mir->ssa_rep->uses[5] = addend1;
1925 raw_use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1926 use_counts_[mul_mir->ssa_rep->defs[1]] = 0;
1927 } else {
1928 DCHECK_EQ(add_mir->ssa_rep->num_uses, 3);
1929 add_mir->ssa_rep->uses[2] = addend0;
1930 }
1931 // Copy in the decoded instruction information.
1932 add_mir->dalvikInsn.vB = SRegToVReg(add_mir->ssa_rep->uses[0]);
1933 if (is_wide) {
1934 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[2]);
1935 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[4]);
1936 } else {
1937 add_mir->dalvikInsn.vC = SRegToVReg(add_mir->ssa_rep->uses[1]);
1938 add_mir->dalvikInsn.arg[0] = SRegToVReg(add_mir->ssa_rep->uses[2]);
1939 }
1940 // Original multiply MIR is set to Nop.
1941 mul_mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
1942}
1943
1944void MIRGraph::MultiplyAddOpt(BasicBlock* bb) {
1945 if (bb->block_type == kDead) {
1946 return;
1947 }
1948 ScopedArenaAllocator allocator(&cu_->arena_stack);
1949 ScopedArenaSafeMap<uint32_t, MIR*> ssa_mul_map(std::less<uint32_t>(), allocator.Adapter());
1950 ScopedArenaSafeMap<uint32_t, MIR*>::iterator map_it;
1951 for (MIR* mir = bb->first_mir_insn; mir != nullptr; mir = mir->next) {
1952 Instruction::Code opcode = mir->dalvikInsn.opcode;
1953 bool is_sub = true;
1954 bool is_candidate_multiply = false;
1955 switch (opcode) {
1956 case Instruction::MUL_INT:
1957 case Instruction::MUL_INT_2ADDR:
1958 is_candidate_multiply = true;
1959 break;
1960 case Instruction::MUL_LONG:
1961 case Instruction::MUL_LONG_2ADDR:
1962 if (cu_->target64) {
1963 is_candidate_multiply = true;
1964 }
1965 break;
1966 case Instruction::ADD_INT:
1967 case Instruction::ADD_INT_2ADDR:
1968 is_sub = false;
1969 FALLTHROUGH_INTENDED;
1970 case Instruction::SUB_INT:
1971 case Instruction::SUB_INT_2ADDR:
1972 if (((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end()) && !is_sub) {
1973 // a*b+c
1974 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1975 false /* is_wide */, false /* is_sub */);
1976 ssa_mul_map.erase(mir->ssa_rep->uses[0]);
1977 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[1])) != ssa_mul_map.end()) {
1978 // c+a*b or c-a*b
1979 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
1980 false /* is_wide */, is_sub);
1981 ssa_mul_map.erase(map_it);
1982 }
1983 break;
1984 case Instruction::ADD_LONG:
1985 case Instruction::ADD_LONG_2ADDR:
1986 is_sub = false;
1987 FALLTHROUGH_INTENDED;
1988 case Instruction::SUB_LONG:
1989 case Instruction::SUB_LONG_2ADDR:
1990 if (!cu_->target64) {
1991 break;
1992 }
1993 if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[0])) != ssa_mul_map.end() && !is_sub) {
1994 // a*b+c
1995 CombineMultiplyAdd(map_it->second, mir, true /* product is the first addend */,
1996 true /* is_wide */, false /* is_sub */);
1997 ssa_mul_map.erase(map_it);
1998 } else if ((map_it = ssa_mul_map.find(mir->ssa_rep->uses[2])) != ssa_mul_map.end()) {
1999 // c+a*b or c-a*b
2000 CombineMultiplyAdd(map_it->second, mir, false /* product is the second addend */,
2001 true /* is_wide */, is_sub);
2002 ssa_mul_map.erase(map_it);
2003 }
2004 break;
2005 default:
2006 if (!ssa_mul_map.empty() && CanThrow(mir)) {
2007 // Should not combine multiply and add MIRs across potential exception.
2008 ssa_mul_map.clear();
2009 }
2010 break;
2011 }
2012
2013 // Exclude the case when an MIR writes a vreg which is previous candidate multiply MIR's uses.
2014 // It is because that current RA may allocate the same physical register to them. For this
2015 // kind of cases, the multiplier has been updated, we should not use updated value to the
2016 // multiply-add insn.
2017 if (ssa_mul_map.size() > 0) {
2018 for (auto it = ssa_mul_map.begin(); it != ssa_mul_map.end();) {
2019 MIR* mul = it->second;
2020 if (HasAntiDependency(mul, mir)) {
2021 it = ssa_mul_map.erase(it);
2022 } else {
2023 ++it;
2024 }
2025 }
2026 }
2027
2028 if (is_candidate_multiply &&
2029 (GetRawUseCount(mir->ssa_rep->defs[0]) == 1) && (mir->next != nullptr)) {
2030 ssa_mul_map.Put(mir->ssa_rep->defs[0], mir);
2031 }
2032 }
2033}
2034
buzbee311ca162013-02-28 15:56:43 -08002035} // namespace art