blob: 304afc32c1a75b86735af9202e02aaf3dbb5281c [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 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
17#include "instruction_simplifier.h"
18
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
Calin Juravle69158982016-03-16 11:53:41 +000037 MaybeRecordStat(kInstructionSimplifications);
38 }
39
40 void MaybeRecordStat(MethodCompilationStat stat) {
41 if (stats_ != nullptr) {
42 stats_->RecordStat(stat);
Alexandre Rames188d4312015-04-09 18:30:21 +010043 }
44 }
45
Scott Wakeling40a04bf2015-12-11 09:50:36 +000046 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
47 bool TryReplaceWithRotate(HBinaryOperation* instruction);
48 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
49 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
50 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51
Alexandre Rames188d4312015-04-09 18:30:21 +010052 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000053 // `op` should be either HOr or HAnd.
54 // De Morgan's laws:
55 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
56 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000057 void VisitShift(HBinaryOperation* shift);
58
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000059 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010060 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
61 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010062 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
63 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000064 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000065 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000066 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080067 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000068 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000069 void VisitAdd(HAdd* instruction) OVERRIDE;
70 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040071 void VisitCondition(HCondition* instruction) OVERRIDE;
72 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
73 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
74 void VisitLessThan(HLessThan* condition) OVERRIDE;
75 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060076 void VisitBelow(HBelow* condition) OVERRIDE;
77 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
78 void VisitAbove(HAbove* condition) OVERRIDE;
79 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000080 void VisitDiv(HDiv* instruction) OVERRIDE;
81 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010082 void VisitNeg(HNeg* instruction) OVERRIDE;
83 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000084 void VisitOr(HOr* instruction) OVERRIDE;
85 void VisitShl(HShl* instruction) OVERRIDE;
86 void VisitShr(HShr* instruction) OVERRIDE;
87 void VisitSub(HSub* instruction) OVERRIDE;
88 void VisitUShr(HUShr* instruction) OVERRIDE;
89 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000090 void VisitSelect(HSelect* select) OVERRIDE;
91 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010092 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010093 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070094 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010095
96 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000097
Roland Levillain22c49222016-03-18 14:04:28 +000098 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010099 void SimplifySystemArrayCopy(HInvoke* invoke);
100 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000101 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800102 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800103 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko51c103e2016-04-28 13:10:02 +0100104 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800105 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100106
Calin Juravleacf735c2015-02-12 15:25:22 +0000107 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100108 bool simplification_occurred_ = false;
109 int simplifications_at_current_position_ = 0;
110 // We ensure we do not loop infinitely. The value is a finger in the air guess
111 // that should allow enough simplification.
112 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000113};
114
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100115void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000116 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100117 visitor.Run();
118}
119
120void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100121 // Iterate in reverse post order to open up more simplifications to users
122 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
124 // The simplification of an instruction to another instruction may yield
125 // possibilities for other simplifications. So although we perform a reverse
126 // post order visit, we sometimes need to revisit an instruction index.
127 simplification_occurred_ = false;
128 VisitBasicBlock(it.Current());
129 if (simplification_occurred_ &&
130 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
131 // New simplifications may be applicable to the instruction at the
132 // current index, so don't advance the iterator.
133 continue;
134 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100135 simplifications_at_current_position_ = 0;
136 it.Advance();
137 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100138}
139
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000140namespace {
141
142bool AreAllBitsSet(HConstant* constant) {
143 return Int64FromConstant(constant) == -1;
144}
145
146} // namespace
147
Alexandre Rames188d4312015-04-09 18:30:21 +0100148// Returns true if the code was simplified to use only one negation operation
149// after the binary operation instead of one on each of the inputs.
150bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
151 DCHECK(binop->IsAdd() || binop->IsSub());
152 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
153 HNeg* left_neg = binop->GetLeft()->AsNeg();
154 HNeg* right_neg = binop->GetRight()->AsNeg();
155 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
156 !right_neg->HasOnlyOneNonEnvironmentUse()) {
157 return false;
158 }
159 // Replace code looking like
160 // NEG tmp1, a
161 // NEG tmp2, b
162 // ADD dst, tmp1, tmp2
163 // with
164 // ADD tmp, a, b
165 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600166 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
167 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
168 // while the later yields `-0.0`.
169 if (!Primitive::IsIntegralType(binop->GetType())) {
170 return false;
171 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100172 binop->ReplaceInput(left_neg->GetInput(), 0);
173 binop->ReplaceInput(right_neg->GetInput(), 1);
174 left_neg->GetBlock()->RemoveInstruction(left_neg);
175 right_neg->GetBlock()->RemoveInstruction(right_neg);
176 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
177 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
178 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
179 RecordSimplification();
180 return true;
181}
182
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000183bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
184 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
185 Primitive::Type type = op->GetType();
186 HInstruction* left = op->GetLeft();
187 HInstruction* right = op->GetRight();
188
189 // We can apply De Morgan's laws if both inputs are Not's and are only used
190 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000191 if (((left->IsNot() && right->IsNot()) ||
192 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000193 left->HasOnlyOneNonEnvironmentUse() &&
194 right->HasOnlyOneNonEnvironmentUse()) {
195 // Replace code looking like
196 // NOT nota, a
197 // NOT notb, b
198 // AND dst, nota, notb (respectively OR)
199 // with
200 // OR or, a, b (respectively AND)
201 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000202 HInstruction* src_left = left->InputAt(0);
203 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000204 uint32_t dex_pc = op->GetDexPc();
205
206 // Remove the negations on the inputs.
207 left->ReplaceWith(src_left);
208 right->ReplaceWith(src_right);
209 left->GetBlock()->RemoveInstruction(left);
210 right->GetBlock()->RemoveInstruction(right);
211
212 // Replace the `HAnd` or `HOr`.
213 HBinaryOperation* hbin;
214 if (op->IsAnd()) {
215 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
216 } else {
217 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
218 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000219 HInstruction* hnot;
220 if (left->IsBooleanNot()) {
221 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
222 } else {
223 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
224 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000225
226 op->GetBlock()->InsertInstructionBefore(hbin, op);
227 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
228
229 RecordSimplification();
230 return true;
231 }
232
233 return false;
234}
235
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000236void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
237 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames7e773ee2016-06-27 11:39:19 +0100238 HInstruction* shift_amount = instruction->GetRight();
239 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000240
Alexandre Rames7e773ee2016-06-27 11:39:19 +0100241 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
242 ? kMaxLongShiftDistance
243 : kMaxIntShiftDistance;
244
245 if (shift_amount->IsConstant()) {
246 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
247 if ((cst & implicit_mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400248 // Replace code looking like
Alexandre Rames7e773ee2016-06-27 11:39:19 +0100249 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400250 // with
Alexandre Rames7e773ee2016-06-27 11:39:19 +0100251 // value
252 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400253 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +0100254 RecordSimplification();
Alexandre Rames7e773ee2016-06-27 11:39:19 +0100255 return;
256 }
257 }
258
259 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
260 // unnecessary explicit masking operations on the shift amount.
261 // Replace code looking like
262 // AND masked_shift, shift, <superset of implicit mask>
263 // SHL dst, value, masked_shift
264 // with
265 // SHL dst, value, shift
266 if (shift_amount->IsAnd()) {
267 HAnd* and_insn = shift_amount->AsAnd();
268 HConstant* mask = and_insn->GetConstantRight();
269 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
270 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
271 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400272 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000273 }
274}
275
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000276static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
277 return (sub->GetRight() == other &&
278 sub->GetLeft()->IsConstant() &&
279 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
280}
281
282bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
283 HUShr* ushr,
284 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000285 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
286 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000287 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
288 if (!ushr->HasUses()) {
289 ushr->GetBlock()->RemoveInstruction(ushr);
290 }
291 if (!ushr->GetRight()->HasUses()) {
292 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
293 }
294 if (!shl->HasUses()) {
295 shl->GetBlock()->RemoveInstruction(shl);
296 }
297 if (!shl->GetRight()->HasUses()) {
298 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
299 }
Alexandre Rames4e3b2632016-05-25 15:01:06 +0100300 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000301 return true;
302}
303
304// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
305bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000306 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
307 HInstruction* left = op->GetLeft();
308 HInstruction* right = op->GetRight();
309 // If we have an UShr and a Shl (in either order).
310 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
311 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
312 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
313 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
314 if (ushr->GetType() == shl->GetType() &&
315 ushr->GetLeft() == shl->GetLeft()) {
316 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
317 // Shift distances are both constant, try replacing with Ror if they
318 // add up to the register size.
319 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
320 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
321 // Shift distances are potentially of the form x and (reg_size - x).
322 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
323 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
324 // Shift distances are potentially of the form d and -d.
325 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
326 }
327 }
328 }
329 return false;
330}
331
332// Try replacing code looking like (x >>> #rdist OP x << #ldist):
333// UShr dst, x, #rdist
334// Shl tmp, x, #ldist
335// OP dst, dst, tmp
336// or like (x >>> #rdist OP x << #-ldist):
337// UShr dst, x, #rdist
338// Shl tmp, x, #-ldist
339// OP dst, dst, tmp
340// with
341// Ror dst, x, #rdist
342bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
343 HUShr* ushr,
344 HShl* shl) {
345 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
346 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
347 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
348 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
349 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
350 ReplaceRotateWithRor(op, ushr, shl);
351 return true;
352 }
353 return false;
354}
355
356// Replace code looking like (x >>> -d OP x << d):
357// Neg neg, d
358// UShr dst, x, neg
359// Shl tmp, x, d
360// OP dst, dst, tmp
361// with
362// Neg neg, d
363// Ror dst, x, neg
364// *** OR ***
365// Replace code looking like (x >>> d OP x << -d):
366// UShr dst, x, d
367// Neg neg, d
368// Shl tmp, x, neg
369// OP dst, dst, tmp
370// with
371// Ror dst, x, d
372bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
373 HUShr* ushr,
374 HShl* shl) {
375 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
376 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
377 bool neg_is_left = shl->GetRight()->IsNeg();
378 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
379 // And the shift distance being negated is the distance being shifted the other way.
380 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
381 ReplaceRotateWithRor(op, ushr, shl);
382 }
383 return false;
384}
385
386// Try replacing code looking like (x >>> d OP x << (#bits - d)):
387// UShr dst, x, d
388// Sub ld, #bits, d
389// Shl tmp, x, ld
390// OP dst, dst, tmp
391// with
392// Ror dst, x, d
393// *** OR ***
394// Replace code looking like (x >>> (#bits - d) OP x << d):
395// Sub rd, #bits, d
396// UShr dst, x, rd
397// Shl tmp, x, d
398// OP dst, dst, tmp
399// with
400// Neg neg, d
401// Ror dst, x, neg
402bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
403 HUShr* ushr,
404 HShl* shl) {
405 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
406 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
407 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
408 HInstruction* shl_shift = shl->GetRight();
409 HInstruction* ushr_shift = ushr->GetRight();
410 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
411 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
412 return ReplaceRotateWithRor(op, ushr, shl);
413 }
414 return false;
415}
416
Calin Juravle10e244f2015-01-26 18:54:32 +0000417void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
418 HInstruction* obj = null_check->InputAt(0);
419 if (!obj->CanBeNull()) {
420 null_check->ReplaceWith(obj);
421 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000422 if (stats_ != nullptr) {
423 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
424 }
425 }
426}
427
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100428bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
429 if (!input->CanBeNull()) {
430 return true;
431 }
432
Vladimir Markod59f3b12016-03-29 12:21:58 +0100433 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
434 HInstruction* user = use.GetUser();
435 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100436 return true;
437 }
438 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100439
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100440 return false;
441}
442
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100443// Returns whether doing a type test between the class of `object` against `klass` has
444// a statically known outcome. The result of the test is stored in `outcome`.
445static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000446 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
447 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
448 ScopedObjectAccess soa(Thread::Current());
449 if (!obj_rti.IsValid()) {
450 // We run the simplifier before the reference type propagation so type info might not be
451 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100452 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000453 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100454
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100455 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100456 if (!class_rti.IsValid()) {
457 // Happens when the loaded class is unresolved.
458 return false;
459 }
460 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000461 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100462 *outcome = true;
463 return true;
464 } else if (obj_rti.IsExact()) {
465 // The test failed at compile time so will also fail at runtime.
466 *outcome = false;
467 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100468 } else if (!class_rti.IsInterface()
469 && !obj_rti.IsInterface()
470 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100471 // Different type hierarchy. The test will fail.
472 *outcome = false;
473 return true;
474 }
475 return false;
476}
477
478void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
479 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100480 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
481 if (load_class->NeedsAccessCheck()) {
482 // If we need to perform an access check we cannot remove the instruction.
483 return;
484 }
485
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100486 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100487 check_cast->ClearMustDoNullCheck();
488 }
489
490 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000491 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000492 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100493 return;
494 }
495
Vladimir Markoa65ed302016-03-14 21:21:29 +0000496 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
497 // the return value check with the `outcome` check, b/27651442 .
498 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700499 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100500 if (outcome) {
501 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000502 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700503 if (!load_class->HasUses()) {
504 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
505 // However, here we know that it cannot because the checkcast was successfull, hence
506 // the class was already loaded.
507 load_class->GetBlock()->RemoveInstruction(load_class);
508 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100509 } else {
510 // Don't do anything for exceptional cases for now. Ideally we should remove
511 // all instructions and blocks this instruction dominates.
512 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000513 }
514}
515
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100516void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100517 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100518 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
519 if (load_class->NeedsAccessCheck()) {
520 // If we need to perform an access check we cannot remove the instruction.
521 return;
522 }
523
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100524 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100525 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100526 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100527 instruction->ClearMustDoNullCheck();
528 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100529
530 HGraph* graph = GetGraph();
531 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000532 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100533 instruction->ReplaceWith(graph->GetIntConstant(0));
534 instruction->GetBlock()->RemoveInstruction(instruction);
535 RecordSimplification();
536 return;
537 }
538
Vladimir Marko24bd8952016-03-15 10:40:33 +0000539 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
540 // the return value check with the `outcome` check, b/27651442 .
541 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700542 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000543 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100544 if (outcome && can_be_null) {
545 // Type test will succeed, we just need a null test.
546 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
547 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
548 instruction->ReplaceWith(test);
549 } else {
550 // We've statically determined the result of the instanceof.
551 instruction->ReplaceWith(graph->GetIntConstant(outcome));
552 }
553 RecordSimplification();
554 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700555 if (outcome && !load_class->HasUses()) {
556 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
557 // However, here we know that it cannot because the instanceof check was successfull, hence
558 // the class was already loaded.
559 load_class->GetBlock()->RemoveInstruction(load_class);
560 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100561 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100562}
563
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100564void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
565 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100566 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100567 instruction->ClearValueCanBeNull();
568 }
569}
570
571void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
572 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100573 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100574 instruction->ClearValueCanBeNull();
575 }
576}
577
Anton Shaminbdd79352016-02-15 12:48:36 +0600578static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
579 HInstruction *lhs = cond->InputAt(0);
580 HInstruction *rhs = cond->InputAt(1);
581 switch (cond->GetKind()) {
582 case HInstruction::kEqual:
583 return new (arena) HEqual(rhs, lhs);
584 case HInstruction::kNotEqual:
585 return new (arena) HNotEqual(rhs, lhs);
586 case HInstruction::kLessThan:
587 return new (arena) HGreaterThan(rhs, lhs);
588 case HInstruction::kLessThanOrEqual:
589 return new (arena) HGreaterThanOrEqual(rhs, lhs);
590 case HInstruction::kGreaterThan:
591 return new (arena) HLessThan(rhs, lhs);
592 case HInstruction::kGreaterThanOrEqual:
593 return new (arena) HLessThanOrEqual(rhs, lhs);
594 case HInstruction::kBelow:
595 return new (arena) HAbove(rhs, lhs);
596 case HInstruction::kBelowOrEqual:
597 return new (arena) HAboveOrEqual(rhs, lhs);
598 case HInstruction::kAbove:
599 return new (arena) HBelow(rhs, lhs);
600 case HInstruction::kAboveOrEqual:
601 return new (arena) HBelowOrEqual(rhs, lhs);
602 default:
603 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
604 }
605 return nullptr;
606}
607
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000608void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100609 HInstruction* input_const = equal->GetConstantRight();
610 if (input_const != nullptr) {
611 HInstruction* input_value = equal->GetLeastConstantLeft();
612 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
613 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100614 // We are comparing the boolean to a constant which is of type int and can
615 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000616 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100617 // Replace (bool_value == true) with bool_value
618 equal->ReplaceWith(input_value);
619 block->RemoveInstruction(equal);
620 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000621 } else if (input_const->AsIntConstant()->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500622 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
623 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100624 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100625 } else {
626 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
627 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
628 block->RemoveInstruction(equal);
629 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100630 }
Mark Mendellc4701932015-04-10 13:18:51 -0400631 } else {
632 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100633 }
Mark Mendellc4701932015-04-10 13:18:51 -0400634 } else {
635 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100636 }
637}
638
David Brazdil0d13fee2015-04-17 14:52:19 +0100639void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
640 HInstruction* input_const = not_equal->GetConstantRight();
641 if (input_const != nullptr) {
642 HInstruction* input_value = not_equal->GetLeastConstantLeft();
643 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
644 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100645 // We are comparing the boolean to a constant which is of type int and can
646 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000647 if (input_const->AsIntConstant()->IsTrue()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500648 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
649 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100650 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000651 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100652 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100653 not_equal->ReplaceWith(input_value);
654 block->RemoveInstruction(not_equal);
655 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100656 } else {
657 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
658 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
659 block->RemoveInstruction(not_equal);
660 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100661 }
Mark Mendellc4701932015-04-10 13:18:51 -0400662 } else {
663 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100664 }
Mark Mendellc4701932015-04-10 13:18:51 -0400665 } else {
666 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100667 }
668}
669
670void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000671 HInstruction* input = bool_not->InputAt(0);
672 HInstruction* replace_with = nullptr;
673
674 if (input->IsIntConstant()) {
675 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000676 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000677 replace_with = GetGraph()->GetIntConstant(0);
678 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000679 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000680 replace_with = GetGraph()->GetIntConstant(1);
681 }
682 } else if (input->IsBooleanNot()) {
683 // Replace (!(!bool_value)) with bool_value.
684 replace_with = input->InputAt(0);
685 } else if (input->IsCondition() &&
686 // Don't change FP compares. The definition of compares involving
687 // NaNs forces the compares to be done as written by the user.
688 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
689 // Replace condition with its opposite.
690 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
691 }
692
693 if (replace_with != nullptr) {
694 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100695 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000696 RecordSimplification();
697 }
698}
699
700void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
701 HInstruction* replace_with = nullptr;
702 HInstruction* condition = select->GetCondition();
703 HInstruction* true_value = select->GetTrueValue();
704 HInstruction* false_value = select->GetFalseValue();
705
706 if (condition->IsBooleanNot()) {
707 // Change ((!cond) ? x : y) to (cond ? y : x).
708 condition = condition->InputAt(0);
709 std::swap(true_value, false_value);
710 select->ReplaceInput(false_value, 0);
711 select->ReplaceInput(true_value, 1);
712 select->ReplaceInput(condition, 2);
713 RecordSimplification();
714 }
715
716 if (true_value == false_value) {
717 // Replace (cond ? x : x) with (x).
718 replace_with = true_value;
719 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000720 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000721 // Replace (true ? x : y) with (x).
722 replace_with = true_value;
723 } else {
724 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000725 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000726 replace_with = false_value;
727 }
728 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000729 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000730 // Replace (cond ? true : false) with (cond).
731 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000732 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000733 // Replace (cond ? false : true) with (!cond).
734 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
735 }
736 }
737
738 if (replace_with != nullptr) {
739 select->ReplaceWith(replace_with);
740 select->GetBlock()->RemoveInstruction(select);
741 RecordSimplification();
742 }
743}
744
745void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
746 HInstruction* condition = instruction->InputAt(0);
747 if (condition->IsBooleanNot()) {
748 // Swap successors if input is negated.
749 instruction->ReplaceInput(condition->InputAt(0), 0);
750 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100751 RecordSimplification();
752 }
753}
754
Mingyao Yang0304e182015-01-30 16:41:29 -0800755void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
756 HInstruction* input = instruction->InputAt(0);
757 // If the array is a NewArray with constant size, replace the array length
758 // with the constant instruction. This helps the bounds check elimination phase.
759 if (input->IsNewArray()) {
760 input = input->InputAt(0);
761 if (input->IsIntConstant()) {
762 instruction->ReplaceWith(input);
763 }
764 }
765}
766
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000767void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000768 HInstruction* value = instruction->GetValue();
769 if (value->GetType() != Primitive::kPrimNot) return;
770
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100771 if (CanEnsureNotNullAt(value, instruction)) {
772 instruction->ClearValueCanBeNull();
773 }
774
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000775 if (value->IsArrayGet()) {
776 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
777 // If the code is just swapping elements in the array, no need for a type check.
778 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100779 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000780 }
781 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100782
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100783 if (value->IsNullConstant()) {
784 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100785 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100786 }
787
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100788 ScopedObjectAccess soa(Thread::Current());
789 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
790 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
791 if (!array_rti.IsValid()) {
792 return;
793 }
794
795 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
796 instruction->ClearNeedsTypeCheck();
797 return;
798 }
799
800 if (array_rti.IsObjectArray()) {
801 if (array_rti.IsExact()) {
802 instruction->ClearNeedsTypeCheck();
803 return;
804 }
805 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100806 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000807}
808
Vladimir Markob52bbde2016-02-12 12:06:05 +0000809static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100810 // Invariant: We should never generate a conversion to a Boolean value.
811 DCHECK_NE(Primitive::kPrimBoolean, result_type);
812
Vladimir Markob52bbde2016-02-12 12:06:05 +0000813 // Besides conversion to the same type, widening integral conversions are implicit,
814 // excluding conversions to long and the byte->char conversion where we need to
815 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
816 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100817 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
818 input_type == Primitive::kPrimByte ||
819 input_type == Primitive::kPrimShort ||
820 input_type == Primitive::kPrimChar)) ||
821 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
822 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
823 input_type == Primitive::kPrimByte)) ||
824 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000825}
826
827static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
828 // The conversion to a larger type is loss-less with the exception of two cases,
829 // - conversion to char, the only unsigned type, where we may lose some bits, and
830 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
831 // For integral to FP conversions this holds because the FP mantissa is large enough.
832 DCHECK_NE(input_type, result_type);
833 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
834 result_type != Primitive::kPrimChar &&
835 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
836}
837
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000838void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000839 HInstruction* input = instruction->GetInput();
840 Primitive::Type input_type = input->GetType();
841 Primitive::Type result_type = instruction->GetResultType();
842 if (IsTypeConversionImplicit(input_type, result_type)) {
843 // Remove the implicit conversion; this includes conversion to the same type.
844 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000845 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000846 RecordSimplification();
847 return;
848 }
849
850 if (input->IsTypeConversion()) {
851 HTypeConversion* input_conversion = input->AsTypeConversion();
852 HInstruction* original_input = input_conversion->GetInput();
853 Primitive::Type original_type = original_input->GetType();
854
855 // When the first conversion is lossless, a direct conversion from the original type
856 // to the final type yields the same result, even for a lossy second conversion, for
857 // example float->double->int or int->double->float.
858 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
859
860 // For integral conversions, see if the first conversion loses only bits that the second
861 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
862 // conversion yields the same result, for example long->int->short or int->char->short.
863 bool integral_conversions_with_non_widening_second =
864 Primitive::IsIntegralType(input_type) &&
865 Primitive::IsIntegralType(original_type) &&
866 Primitive::IsIntegralType(result_type) &&
867 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
868
869 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
870 // If the merged conversion is implicit, do the simplification unconditionally.
871 if (IsTypeConversionImplicit(original_type, result_type)) {
872 instruction->ReplaceWith(original_input);
873 instruction->GetBlock()->RemoveInstruction(instruction);
874 if (!input_conversion->HasUses()) {
875 // Don't wait for DCE.
876 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
877 }
878 RecordSimplification();
879 return;
880 }
881 // Otherwise simplify only if the first conversion has no other use.
882 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
883 input_conversion->ReplaceWith(original_input);
884 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
885 RecordSimplification();
886 return;
887 }
888 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000889 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000890 DCHECK(Primitive::IsIntegralType(input_type));
891 HAnd* input_and = input->AsAnd();
892 HConstant* constant = input_and->GetConstantRight();
893 if (constant != nullptr) {
894 int64_t value = Int64FromConstant(constant);
895 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
896 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
897 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
898 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000899 HInstruction* original_input = input_and->GetLeastConstantLeft();
900 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
901 instruction->ReplaceWith(original_input);
902 instruction->GetBlock()->RemoveInstruction(instruction);
903 RecordSimplification();
904 return;
905 } else if (input->HasOnlyOneNonEnvironmentUse()) {
906 input_and->ReplaceWith(original_input);
907 input_and->GetBlock()->RemoveInstruction(input_and);
908 RecordSimplification();
909 return;
910 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000911 }
912 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000913 }
914}
915
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000916void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
917 HConstant* input_cst = instruction->GetConstantRight();
918 HInstruction* input_other = instruction->GetLeastConstantLeft();
Roland Levillain1a653882016-03-18 18:05:57 +0000919 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000920 // Replace code looking like
921 // ADD dst, src, 0
922 // with
923 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600924 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
925 // `x` is `-0.0`, the former expression yields `0.0`, while the later
926 // yields `-0.0`.
927 if (Primitive::IsIntegralType(instruction->GetType())) {
928 instruction->ReplaceWith(input_other);
929 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +0100930 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600931 return;
932 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100933 }
934
935 HInstruction* left = instruction->GetLeft();
936 HInstruction* right = instruction->GetRight();
937 bool left_is_neg = left->IsNeg();
938 bool right_is_neg = right->IsNeg();
939
940 if (left_is_neg && right_is_neg) {
941 if (TryMoveNegOnInputsAfterBinop(instruction)) {
942 return;
943 }
944 }
945
946 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
947 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
948 // Replace code looking like
949 // NEG tmp, b
950 // ADD dst, a, tmp
951 // with
952 // SUB dst, a, b
953 // We do not perform the optimization if the input negation has environment
954 // uses or multiple non-environment uses as it could lead to worse code. In
955 // particular, we do not want the live range of `b` to be extended if we are
956 // not sure the initial 'NEG' instruction can be removed.
957 HInstruction* other = left_is_neg ? right : left;
958 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
959 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
960 RecordSimplification();
961 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000962 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000963 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000964
965 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000966}
967
968void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
969 HConstant* input_cst = instruction->GetConstantRight();
970 HInstruction* input_other = instruction->GetLeastConstantLeft();
971
Vladimir Marko452c1b62015-09-25 14:44:17 +0100972 if (input_cst != nullptr) {
973 int64_t value = Int64FromConstant(input_cst);
974 if (value == -1) {
975 // Replace code looking like
976 // AND dst, src, 0xFFF...FF
977 // with
978 // src
979 instruction->ReplaceWith(input_other);
980 instruction->GetBlock()->RemoveInstruction(instruction);
981 RecordSimplification();
982 return;
983 }
984 // Eliminate And from UShr+And if the And-mask contains all the bits that
985 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
986 // precisely clears the shifted-in sign bits.
987 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
988 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
989 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
990 size_t num_tail_bits_set = CTZ(value + 1);
991 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
992 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
993 instruction->ReplaceWith(input_other);
994 instruction->GetBlock()->RemoveInstruction(instruction);
995 RecordSimplification();
996 return;
997 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
998 input_other->HasOnlyOneNonEnvironmentUse()) {
999 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1000 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1001 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1002 input_other->InputAt(0),
1003 input_other->InputAt(1),
1004 input_other->GetDexPc());
1005 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1006 input_other->GetBlock()->RemoveInstruction(input_other);
1007 RecordSimplification();
1008 return;
1009 }
1010 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001011 }
1012
1013 // We assume that GVN has run before, so we only perform a pointer comparison.
1014 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001015 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001016 if (instruction->GetLeft() == instruction->GetRight()) {
1017 // Replace code looking like
1018 // AND dst, src, src
1019 // with
1020 // src
1021 instruction->ReplaceWith(instruction->GetLeft());
1022 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001023 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001024 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001025 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001026
1027 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001028}
1029
Mark Mendellc4701932015-04-10 13:18:51 -04001030void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1031 VisitCondition(condition);
1032}
1033
1034void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1035 VisitCondition(condition);
1036}
1037
1038void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1039 VisitCondition(condition);
1040}
1041
1042void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1043 VisitCondition(condition);
1044}
1045
Anton Shaminbdd79352016-02-15 12:48:36 +06001046void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1047 VisitCondition(condition);
1048}
1049
1050void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1051 VisitCondition(condition);
1052}
1053
1054void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1055 VisitCondition(condition);
1056}
1057
1058void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1059 VisitCondition(condition);
1060}
Aart Bike9f37602015-10-09 11:15:55 -07001061
Mark Mendellc4701932015-04-10 13:18:51 -04001062void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001063 // Reverse condition if left is constant. Our code generators prefer constant
1064 // on the right hand side.
1065 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1066 HBasicBlock* block = condition->GetBlock();
1067 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1068 // If it is a fp we must set the opposite bias.
1069 if (replacement != nullptr) {
1070 if (condition->IsLtBias()) {
1071 replacement->SetBias(ComparisonBias::kGtBias);
1072 } else if (condition->IsGtBias()) {
1073 replacement->SetBias(ComparisonBias::kLtBias);
1074 }
1075 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1076 RecordSimplification();
1077
1078 condition = replacement;
1079 }
1080 }
Mark Mendellc4701932015-04-10 13:18:51 -04001081
Mark Mendellc4701932015-04-10 13:18:51 -04001082 HInstruction* left = condition->GetLeft();
1083 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001084
1085 // Try to fold an HCompare into this HCondition.
1086
Mark Mendellc4701932015-04-10 13:18:51 -04001087 // We can only replace an HCondition which compares a Compare to 0.
1088 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1089 // condition with a long, float or double comparison as input.
1090 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1091 // Conversion is not possible.
1092 return;
1093 }
1094
1095 // Is the Compare only used for this purpose?
Vladimir Markod59f3b12016-03-29 12:21:58 +01001096 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001097 // Someone else also wants the result of the compare.
1098 return;
1099 }
1100
Vladimir Markod59f3b12016-03-29 12:21:58 +01001101 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001102 // There is a reference to the compare result in an environment. Do we really need it?
1103 if (GetGraph()->IsDebuggable()) {
1104 return;
1105 }
1106
1107 // We have to ensure that there are no deopt points in the sequence.
1108 if (left->HasAnyEnvironmentUseBefore(condition)) {
1109 return;
1110 }
1111 }
1112
1113 // Clean up any environment uses from the HCompare, if any.
1114 left->RemoveEnvironmentUsers();
1115
1116 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1117 condition->SetBias(left->AsCompare()->GetBias());
1118
1119 // Replace the operands of the HCondition.
1120 condition->ReplaceInput(left->InputAt(0), 0);
1121 condition->ReplaceInput(left->InputAt(1), 1);
1122
1123 // Remove the HCompare.
1124 left->GetBlock()->RemoveInstruction(left);
1125
1126 RecordSimplification();
1127}
1128
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001129void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1130 HConstant* input_cst = instruction->GetConstantRight();
1131 HInstruction* input_other = instruction->GetLeastConstantLeft();
1132 Primitive::Type type = instruction->GetType();
1133
1134 if ((input_cst != nullptr) && input_cst->IsOne()) {
1135 // Replace code looking like
1136 // DIV dst, src, 1
1137 // with
1138 // src
1139 instruction->ReplaceWith(input_other);
1140 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001141 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001142 return;
1143 }
1144
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001145 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001146 // Replace code looking like
1147 // DIV dst, src, -1
1148 // with
1149 // NEG dst, src
1150 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001151 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001152 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001153 return;
1154 }
1155
1156 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1157 // Try replacing code looking like
1158 // DIV dst, src, constant
1159 // with
1160 // MUL dst, src, 1 / constant
1161 HConstant* reciprocal = nullptr;
1162 if (type == Primitive::Primitive::kPrimDouble) {
1163 double value = input_cst->AsDoubleConstant()->GetValue();
1164 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1165 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1166 }
1167 } else {
1168 DCHECK_EQ(type, Primitive::kPrimFloat);
1169 float value = input_cst->AsFloatConstant()->GetValue();
1170 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1171 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1172 }
1173 }
1174
1175 if (reciprocal != nullptr) {
1176 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1177 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1178 RecordSimplification();
1179 return;
1180 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001181 }
1182}
1183
1184void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1185 HConstant* input_cst = instruction->GetConstantRight();
1186 HInstruction* input_other = instruction->GetLeastConstantLeft();
1187 Primitive::Type type = instruction->GetType();
1188 HBasicBlock* block = instruction->GetBlock();
1189 ArenaAllocator* allocator = GetGraph()->GetArena();
1190
1191 if (input_cst == nullptr) {
1192 return;
1193 }
1194
1195 if (input_cst->IsOne()) {
1196 // Replace code looking like
1197 // MUL dst, src, 1
1198 // with
1199 // src
1200 instruction->ReplaceWith(input_other);
1201 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001202 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001203 return;
1204 }
1205
1206 if (input_cst->IsMinusOne() &&
1207 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1208 // Replace code looking like
1209 // MUL dst, src, -1
1210 // with
1211 // NEG dst, src
1212 HNeg* neg = new (allocator) HNeg(type, input_other);
1213 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001214 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001215 return;
1216 }
1217
1218 if (Primitive::IsFloatingPointType(type) &&
1219 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1220 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1221 // Replace code looking like
1222 // FP_MUL dst, src, 2.0
1223 // with
1224 // FP_ADD dst, src, src
1225 // The 'int' and 'long' cases are handled below.
1226 block->ReplaceAndRemoveInstructionWith(instruction,
1227 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001228 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001229 return;
1230 }
1231
1232 if (Primitive::IsIntOrLongType(type)) {
1233 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001234 // Even though constant propagation also takes care of the zero case, other
1235 // optimizations can lead to having a zero multiplication.
1236 if (factor == 0) {
1237 // Replace code looking like
1238 // MUL dst, src, 0
1239 // with
1240 // 0
1241 instruction->ReplaceWith(input_cst);
1242 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001243 RecordSimplification();
Serguei Katkov53849192015-04-20 14:22:27 +06001244 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001245 // Replace code looking like
1246 // MUL dst, src, pow_of_2
1247 // with
1248 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001249 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001250 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001251 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001252 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001253 } else if (IsPowerOfTwo(factor - 1)) {
1254 // Transform code looking like
1255 // MUL dst, src, (2^n + 1)
1256 // into
1257 // SHL tmp, src, n
1258 // ADD dst, src, tmp
1259 HShl* shl = new (allocator) HShl(type,
1260 input_other,
1261 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1262 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1263
1264 block->InsertInstructionBefore(shl, instruction);
1265 block->ReplaceAndRemoveInstructionWith(instruction, add);
1266 RecordSimplification();
1267 } else if (IsPowerOfTwo(factor + 1)) {
1268 // Transform code looking like
1269 // MUL dst, src, (2^n - 1)
1270 // into
1271 // SHL tmp, src, n
1272 // SUB dst, tmp, src
1273 HShl* shl = new (allocator) HShl(type,
1274 input_other,
1275 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1276 HSub* sub = new (allocator) HSub(type, shl, input_other);
1277
1278 block->InsertInstructionBefore(shl, instruction);
1279 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1280 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001281 }
1282 }
1283}
1284
Alexandre Rames188d4312015-04-09 18:30:21 +01001285void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1286 HInstruction* input = instruction->GetInput();
1287 if (input->IsNeg()) {
1288 // Replace code looking like
1289 // NEG tmp, src
1290 // NEG dst, tmp
1291 // with
1292 // src
1293 HNeg* previous_neg = input->AsNeg();
1294 instruction->ReplaceWith(previous_neg->GetInput());
1295 instruction->GetBlock()->RemoveInstruction(instruction);
1296 // We perform the optimization even if the input negation has environment
1297 // uses since it allows removing the current instruction. But we only delete
1298 // the input negation only if it is does not have any uses left.
1299 if (!previous_neg->HasUses()) {
1300 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1301 }
1302 RecordSimplification();
1303 return;
1304 }
1305
Serguei Katkov339dfc22015-04-20 12:29:32 +06001306 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1307 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001308 // Replace code looking like
1309 // SUB tmp, a, b
1310 // NEG dst, tmp
1311 // with
1312 // SUB dst, b, a
1313 // We do not perform the optimization if the input subtraction has
1314 // environment uses or multiple non-environment uses as it could lead to
1315 // worse code. In particular, we do not want the live ranges of `a` and `b`
1316 // to be extended if we are not sure the initial 'SUB' instruction can be
1317 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001318 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001319 HSub* sub = input->AsSub();
1320 HSub* new_sub =
1321 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1322 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1323 if (!sub->HasUses()) {
1324 sub->GetBlock()->RemoveInstruction(sub);
1325 }
1326 RecordSimplification();
1327 }
1328}
1329
1330void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1331 HInstruction* input = instruction->GetInput();
1332 if (input->IsNot()) {
1333 // Replace code looking like
1334 // NOT tmp, src
1335 // NOT dst, tmp
1336 // with
1337 // src
1338 // We perform the optimization even if the input negation has environment
1339 // uses since it allows removing the current instruction. But we only delete
1340 // the input negation only if it is does not have any uses left.
1341 HNot* previous_not = input->AsNot();
1342 instruction->ReplaceWith(previous_not->GetInput());
1343 instruction->GetBlock()->RemoveInstruction(instruction);
1344 if (!previous_not->HasUses()) {
1345 previous_not->GetBlock()->RemoveInstruction(previous_not);
1346 }
1347 RecordSimplification();
1348 }
1349}
1350
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001351void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1352 HConstant* input_cst = instruction->GetConstantRight();
1353 HInstruction* input_other = instruction->GetLeastConstantLeft();
1354
Roland Levillain1a653882016-03-18 18:05:57 +00001355 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001356 // Replace code looking like
1357 // OR dst, src, 0
1358 // with
1359 // src
1360 instruction->ReplaceWith(input_other);
1361 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001362 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001363 return;
1364 }
1365
1366 // We assume that GVN has run before, so we only perform a pointer comparison.
1367 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001368 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001369 if (instruction->GetLeft() == instruction->GetRight()) {
1370 // Replace code looking like
1371 // OR dst, src, src
1372 // with
1373 // src
1374 instruction->ReplaceWith(instruction->GetLeft());
1375 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001376 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001377 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001378 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001379
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001380 if (TryDeMorganNegationFactoring(instruction)) return;
1381
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001382 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001383}
1384
1385void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1386 VisitShift(instruction);
1387}
1388
1389void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1390 VisitShift(instruction);
1391}
1392
1393void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1394 HConstant* input_cst = instruction->GetConstantRight();
1395 HInstruction* input_other = instruction->GetLeastConstantLeft();
1396
Serguei Katkov115b53f2015-08-05 17:03:30 +06001397 Primitive::Type type = instruction->GetType();
1398 if (Primitive::IsFloatingPointType(type)) {
1399 return;
1400 }
1401
Roland Levillain1a653882016-03-18 18:05:57 +00001402 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001403 // Replace code looking like
1404 // SUB dst, src, 0
1405 // with
1406 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001407 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1408 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1409 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001410 instruction->ReplaceWith(input_other);
1411 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001412 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001413 return;
1414 }
1415
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001416 HBasicBlock* block = instruction->GetBlock();
1417 ArenaAllocator* allocator = GetGraph()->GetArena();
1418
Alexandre Rames188d4312015-04-09 18:30:21 +01001419 HInstruction* left = instruction->GetLeft();
1420 HInstruction* right = instruction->GetRight();
1421 if (left->IsConstant()) {
1422 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001423 // Replace code looking like
1424 // SUB dst, 0, src
1425 // with
1426 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001427 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001428 // `x` is `0.0`, the former expression yields `0.0`, while the later
1429 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001430 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001431 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001432 RecordSimplification();
1433 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001434 }
1435 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001436
1437 if (left->IsNeg() && right->IsNeg()) {
1438 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1439 return;
1440 }
1441 }
1442
1443 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1444 // Replace code looking like
1445 // NEG tmp, b
1446 // SUB dst, a, tmp
1447 // with
1448 // ADD dst, a, b
1449 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1450 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1451 RecordSimplification();
1452 right->GetBlock()->RemoveInstruction(right);
1453 return;
1454 }
1455
1456 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1457 // Replace code looking like
1458 // NEG tmp, a
1459 // SUB dst, tmp, b
1460 // with
1461 // ADD tmp, a, b
1462 // NEG dst, tmp
1463 // The second version is not intrinsically better, but enables more
1464 // transformations.
1465 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1466 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1467 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1468 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1469 instruction->ReplaceWith(neg);
1470 instruction->GetBlock()->RemoveInstruction(instruction);
1471 RecordSimplification();
1472 left->GetBlock()->RemoveInstruction(left);
1473 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001474}
1475
1476void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1477 VisitShift(instruction);
1478}
1479
1480void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1481 HConstant* input_cst = instruction->GetConstantRight();
1482 HInstruction* input_other = instruction->GetLeastConstantLeft();
1483
Roland Levillain1a653882016-03-18 18:05:57 +00001484 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001485 // Replace code looking like
1486 // XOR dst, src, 0
1487 // with
1488 // src
1489 instruction->ReplaceWith(input_other);
1490 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames4e3b2632016-05-25 15:01:06 +01001491 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001492 return;
1493 }
1494
1495 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1496 // Replace code looking like
1497 // XOR dst, src, 0xFFF...FF
1498 // with
1499 // NOT dst, src
1500 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1501 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001502 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001503 return;
1504 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001505
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001506 HInstruction* left = instruction->GetLeft();
1507 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001508 if (((left->IsNot() && right->IsNot()) ||
1509 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001510 left->HasOnlyOneNonEnvironmentUse() &&
1511 right->HasOnlyOneNonEnvironmentUse()) {
1512 // Replace code looking like
1513 // NOT nota, a
1514 // NOT notb, b
1515 // XOR dst, nota, notb
1516 // with
1517 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001518 instruction->ReplaceInput(left->InputAt(0), 0);
1519 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001520 left->GetBlock()->RemoveInstruction(left);
1521 right->GetBlock()->RemoveInstruction(right);
1522 RecordSimplification();
1523 return;
1524 }
1525
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001526 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001527}
1528
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001529void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1530 HInstruction* argument = instruction->InputAt(1);
1531 HInstruction* receiver = instruction->InputAt(0);
1532 if (receiver == argument) {
1533 // Because String.equals is an instance call, the receiver is
1534 // a null check if we don't know it's null. The argument however, will
1535 // be the actual object. So we cannot end up in a situation where both
1536 // are equal but could be null.
1537 DCHECK(CanEnsureNotNullAt(argument, instruction));
1538 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1539 instruction->GetBlock()->RemoveInstruction(instruction);
1540 } else {
1541 StringEqualsOptimizations optimizations(instruction);
1542 if (CanEnsureNotNullAt(argument, instruction)) {
1543 optimizations.SetArgumentNotNull();
1544 }
1545 ScopedObjectAccess soa(Thread::Current());
1546 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1547 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1548 optimizations.SetArgumentIsString();
1549 }
1550 }
1551}
1552
Roland Levillain22c49222016-03-18 14:04:28 +00001553void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1554 bool is_left,
1555 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001556 DCHECK(invoke->IsInvokeStaticOrDirect());
1557 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001558 HInstruction* value = invoke->InputAt(0);
1559 HInstruction* distance = invoke->InputAt(1);
1560 // Replace the invoke with an HRor.
1561 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001562 // Unconditionally set the type of the negated distance to `int`,
1563 // as shift and rotate operations expect a 32-bit (or narrower)
1564 // value for their distance input.
1565 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001566 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1567 }
Roland Levillain22c49222016-03-18 14:04:28 +00001568 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001569 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1570 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko3925c6e2016-05-17 16:30:10 +01001571 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001572 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1573 clinit->GetBlock()->RemoveInstruction(clinit);
1574 HInstruction* ldclass = clinit->InputAt(0);
1575 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1576 ldclass->GetBlock()->RemoveInstruction(ldclass);
1577 }
1578 }
1579}
1580
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001581static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1582 if (potential_length->IsArrayLength()) {
1583 return potential_length->InputAt(0) == potential_array;
1584 }
1585
1586 if (potential_array->IsNewArray()) {
1587 return potential_array->InputAt(0) == potential_length;
1588 }
1589
1590 return false;
1591}
1592
1593void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1594 HInstruction* source = instruction->InputAt(0);
1595 HInstruction* destination = instruction->InputAt(2);
1596 HInstruction* count = instruction->InputAt(4);
1597 SystemArrayCopyOptimizations optimizations(instruction);
1598 if (CanEnsureNotNullAt(source, instruction)) {
1599 optimizations.SetSourceIsNotNull();
1600 }
1601 if (CanEnsureNotNullAt(destination, instruction)) {
1602 optimizations.SetDestinationIsNotNull();
1603 }
1604 if (destination == source) {
1605 optimizations.SetDestinationIsSource();
1606 }
1607
1608 if (IsArrayLengthOf(count, source)) {
1609 optimizations.SetCountIsSourceLength();
1610 }
1611
1612 if (IsArrayLengthOf(count, destination)) {
1613 optimizations.SetCountIsDestinationLength();
1614 }
1615
1616 {
1617 ScopedObjectAccess soa(Thread::Current());
1618 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1619 if (destination_rti.IsValid()) {
1620 if (destination_rti.IsObjectArray()) {
1621 if (destination_rti.IsExact()) {
1622 optimizations.SetDoesNotNeedTypeCheck();
1623 }
1624 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001625 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001626 if (destination_rti.IsPrimitiveArrayClass()) {
1627 optimizations.SetDestinationIsPrimitiveArray();
1628 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1629 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001630 }
1631 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001632 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1633 if (source_rti.IsValid()) {
1634 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1635 optimizations.SetDoesNotNeedTypeCheck();
1636 }
1637 if (source_rti.IsPrimitiveArrayClass()) {
1638 optimizations.SetSourceIsPrimitiveArray();
1639 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1640 optimizations.SetSourceIsNonPrimitiveArray();
1641 }
1642 }
1643 }
1644}
1645
Roland Levillaina5c4a402016-03-15 15:02:50 +00001646void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1647 bool is_signum,
1648 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001649 DCHECK(invoke->IsInvokeStaticOrDirect());
1650 uint32_t dex_pc = invoke->GetDexPc();
1651 HInstruction* left = invoke->InputAt(0);
1652 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001653 if (!is_signum) {
1654 right = invoke->InputAt(1);
1655 } else if (type == Primitive::kPrimLong) {
1656 right = GetGraph()->GetLongConstant(0);
1657 } else {
1658 right = GetGraph()->GetIntConstant(0);
1659 }
1660 HCompare* compare = new (GetGraph()->GetArena())
1661 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1662 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1663}
1664
Aart Bik75a38b22016-02-17 10:41:50 -08001665void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1666 DCHECK(invoke->IsInvokeStaticOrDirect());
1667 uint32_t dex_pc = invoke->GetDexPc();
1668 // IsNaN(x) is the same as x != x.
1669 HInstruction* x = invoke->InputAt(0);
1670 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001671 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001672 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1673}
1674
Aart Bik2a6aad92016-02-25 11:32:32 -08001675void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1676 DCHECK(invoke->IsInvokeStaticOrDirect());
1677 uint32_t dex_pc = invoke->GetDexPc();
1678 HInstruction* x = invoke->InputAt(0);
1679 Primitive::Type type = x->GetType();
1680 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1681 HInstruction* nan;
1682 if (type == Primitive::kPrimDouble) {
1683 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1684 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1685 kNeedsEnvironmentOrCache,
1686 kNoSideEffects,
1687 kNoThrow);
1688 } else {
1689 DCHECK_EQ(type, Primitive::kPrimFloat);
1690 nan = GetGraph()->GetIntConstant(0x7fc00000);
1691 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1692 kNeedsEnvironmentOrCache,
1693 kNoSideEffects,
1694 kNoThrow);
1695 }
1696 // Test IsNaN(x), which is the same as x != x.
1697 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1698 condition->SetBias(ComparisonBias::kLtBias);
1699 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1700 // Select between the two.
1701 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1702 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1703 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1704}
1705
Vladimir Marko51c103e2016-04-28 13:10:02 +01001706void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1707 HInstruction* str = invoke->InputAt(0);
1708 uint32_t dex_pc = invoke->GetDexPc();
1709 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1710 // so create the HArrayLength.
1711 HArrayLength* length = new (GetGraph()->GetArena()) HArrayLength(str, dex_pc);
1712 length->MarkAsStringLength();
1713 HInstruction* replacement;
1714 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1715 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1716 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1717 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1718 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1719 replacement = equal;
1720 } else {
1721 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1722 replacement = length;
1723 }
1724 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1725}
1726
Aart Bik11932592016-03-08 12:42:25 -08001727void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1728 uint32_t dex_pc = invoke->GetDexPc();
1729 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1730 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1731}
1732
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001733void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001734 switch (instruction->GetIntrinsic()) {
1735 case Intrinsics::kStringEquals:
1736 SimplifyStringEquals(instruction);
1737 break;
1738 case Intrinsics::kSystemArrayCopy:
1739 SimplifySystemArrayCopy(instruction);
1740 break;
1741 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001742 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
1743 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001744 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001745 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001746 break;
1747 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001748 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
1749 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001750 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001751 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001752 break;
1753 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001754 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
1755 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001756 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001757 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001758 break;
1759 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001760 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
1761 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001762 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001763 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001764 break;
1765 case Intrinsics::kFloatIsNaN:
1766 case Intrinsics::kDoubleIsNaN:
1767 SimplifyIsNaN(instruction);
1768 break;
1769 case Intrinsics::kFloatFloatToIntBits:
1770 case Intrinsics::kDoubleDoubleToLongBits:
1771 SimplifyFP2Int(instruction);
1772 break;
Vladimir Marko51c103e2016-04-28 13:10:02 +01001773 case Intrinsics::kStringIsEmpty:
1774 case Intrinsics::kStringLength:
1775 SimplifyStringIsEmptyOrLength(instruction);
1776 break;
Aart Bik11932592016-03-08 12:42:25 -08001777 case Intrinsics::kUnsafeLoadFence:
1778 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1779 break;
1780 case Intrinsics::kUnsafeStoreFence:
1781 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1782 break;
1783 case Intrinsics::kUnsafeFullFence:
1784 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1785 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001786 default:
1787 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001788 }
1789}
1790
Aart Bikbb245d12015-10-19 11:05:03 -07001791void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1792 HInstruction* cond = deoptimize->InputAt(0);
1793 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001794 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07001795 // Never deopt: instruction can be removed.
1796 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1797 } else {
1798 // Always deopt.
1799 }
1800 }
1801}
1802
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001803} // namespace art