blob: 85b461dcf68ed29e73721ef056a595b603b018ef [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"
Mathieu Chartier0795f232016-09-27 18:43:30 -070021#include "scoped_thread_state_change-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000022
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);
Anton Kirilove14dc862016-05-13 17:56:15 +010057 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
58 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
59
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000060 void VisitShift(HBinaryOperation* shift);
61
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000062 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010063 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
64 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010065 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
66 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000068 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000069 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080070 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000071 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000072 void VisitAdd(HAdd* instruction) OVERRIDE;
73 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040074 void VisitCondition(HCondition* instruction) OVERRIDE;
75 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
76 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
77 void VisitLessThan(HLessThan* condition) OVERRIDE;
78 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060079 void VisitBelow(HBelow* condition) OVERRIDE;
80 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
81 void VisitAbove(HAbove* condition) OVERRIDE;
82 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000083 void VisitDiv(HDiv* instruction) OVERRIDE;
84 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010085 void VisitNeg(HNeg* instruction) OVERRIDE;
86 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000087 void VisitOr(HOr* instruction) OVERRIDE;
88 void VisitShl(HShl* instruction) OVERRIDE;
89 void VisitShr(HShr* instruction) OVERRIDE;
90 void VisitSub(HSub* instruction) OVERRIDE;
91 void VisitUShr(HUShr* instruction) OVERRIDE;
92 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000093 void VisitSelect(HSelect* select) OVERRIDE;
94 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010095 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010096 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070097 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010098
99 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000100
Roland Levillain22c49222016-03-18 14:04:28 +0000101 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100102 void SimplifySystemArrayCopy(HInvoke* invoke);
103 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000104 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800105 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800106 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100107 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100108 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800109 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik11932592016-03-08 12:42:25 -0800110 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100111
Calin Juravleacf735c2015-02-12 15:25:22 +0000112 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100113 bool simplification_occurred_ = false;
114 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700115 // We ensure we do not loop infinitely. The value should not be too high, since that
116 // would allow looping around the same basic block too many times. The value should
117 // not be too low either, however, since we want to allow revisiting a basic block
118 // with many statements and simplifications at least once.
119 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000120};
121
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100122void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000123 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100124 visitor.Run();
125}
126
127void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100128 // Iterate in reverse post order to open up more simplifications to users
129 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100130 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100131 // The simplification of an instruction to another instruction may yield
132 // possibilities for other simplifications. So although we perform a reverse
133 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100134 do {
135 simplification_occurred_ = false;
136 VisitBasicBlock(block);
137 } while (simplification_occurred_ &&
138 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100139 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100140 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100141}
142
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000143namespace {
144
145bool AreAllBitsSet(HConstant* constant) {
146 return Int64FromConstant(constant) == -1;
147}
148
149} // namespace
150
Alexandre Rames188d4312015-04-09 18:30:21 +0100151// Returns true if the code was simplified to use only one negation operation
152// after the binary operation instead of one on each of the inputs.
153bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
154 DCHECK(binop->IsAdd() || binop->IsSub());
155 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
156 HNeg* left_neg = binop->GetLeft()->AsNeg();
157 HNeg* right_neg = binop->GetRight()->AsNeg();
158 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
159 !right_neg->HasOnlyOneNonEnvironmentUse()) {
160 return false;
161 }
162 // Replace code looking like
163 // NEG tmp1, a
164 // NEG tmp2, b
165 // ADD dst, tmp1, tmp2
166 // with
167 // ADD tmp, a, b
168 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600169 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
170 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
171 // while the later yields `-0.0`.
172 if (!Primitive::IsIntegralType(binop->GetType())) {
173 return false;
174 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100175 binop->ReplaceInput(left_neg->GetInput(), 0);
176 binop->ReplaceInput(right_neg->GetInput(), 1);
177 left_neg->GetBlock()->RemoveInstruction(left_neg);
178 right_neg->GetBlock()->RemoveInstruction(right_neg);
179 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
180 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
181 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
182 RecordSimplification();
183 return true;
184}
185
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000186bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
187 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
188 Primitive::Type type = op->GetType();
189 HInstruction* left = op->GetLeft();
190 HInstruction* right = op->GetRight();
191
192 // We can apply De Morgan's laws if both inputs are Not's and are only used
193 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000194 if (((left->IsNot() && right->IsNot()) ||
195 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000196 left->HasOnlyOneNonEnvironmentUse() &&
197 right->HasOnlyOneNonEnvironmentUse()) {
198 // Replace code looking like
199 // NOT nota, a
200 // NOT notb, b
201 // AND dst, nota, notb (respectively OR)
202 // with
203 // OR or, a, b (respectively AND)
204 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000205 HInstruction* src_left = left->InputAt(0);
206 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000207 uint32_t dex_pc = op->GetDexPc();
208
209 // Remove the negations on the inputs.
210 left->ReplaceWith(src_left);
211 right->ReplaceWith(src_right);
212 left->GetBlock()->RemoveInstruction(left);
213 right->GetBlock()->RemoveInstruction(right);
214
215 // Replace the `HAnd` or `HOr`.
216 HBinaryOperation* hbin;
217 if (op->IsAnd()) {
218 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
219 } else {
220 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
221 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000222 HInstruction* hnot;
223 if (left->IsBooleanNot()) {
224 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
225 } else {
226 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
227 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000228
229 op->GetBlock()->InsertInstructionBefore(hbin, op);
230 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
231
232 RecordSimplification();
233 return true;
234 }
235
236 return false;
237}
238
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000239void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
240 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100241 HInstruction* shift_amount = instruction->GetRight();
242 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000243
Alexandre Rames50518442016-06-27 11:39:19 +0100244 int64_t implicit_mask = (value->GetType() == Primitive::kPrimLong)
245 ? kMaxLongShiftDistance
246 : kMaxIntShiftDistance;
247
248 if (shift_amount->IsConstant()) {
249 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
250 if ((cst & implicit_mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400251 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100252 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400253 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100254 // value
255 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400256 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100257 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100258 return;
259 }
260 }
261
262 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
263 // unnecessary explicit masking operations on the shift amount.
264 // Replace code looking like
265 // AND masked_shift, shift, <superset of implicit mask>
266 // SHL dst, value, masked_shift
267 // with
268 // SHL dst, value, shift
269 if (shift_amount->IsAnd()) {
270 HAnd* and_insn = shift_amount->AsAnd();
271 HConstant* mask = and_insn->GetConstantRight();
272 if ((mask != nullptr) && ((Int64FromConstant(mask) & implicit_mask) == implicit_mask)) {
273 instruction->ReplaceInput(and_insn->GetLeastConstantLeft(), 1);
274 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400275 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000276 }
277}
278
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000279static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
280 return (sub->GetRight() == other &&
281 sub->GetLeft()->IsConstant() &&
282 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
283}
284
285bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
286 HUShr* ushr,
287 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000288 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
289 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000290 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
291 if (!ushr->HasUses()) {
292 ushr->GetBlock()->RemoveInstruction(ushr);
293 }
294 if (!ushr->GetRight()->HasUses()) {
295 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
296 }
297 if (!shl->HasUses()) {
298 shl->GetBlock()->RemoveInstruction(shl);
299 }
300 if (!shl->GetRight()->HasUses()) {
301 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
302 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100303 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000304 return true;
305}
306
307// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
308bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000309 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
310 HInstruction* left = op->GetLeft();
311 HInstruction* right = op->GetRight();
312 // If we have an UShr and a Shl (in either order).
313 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
314 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
315 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
316 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
317 if (ushr->GetType() == shl->GetType() &&
318 ushr->GetLeft() == shl->GetLeft()) {
319 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
320 // Shift distances are both constant, try replacing with Ror if they
321 // add up to the register size.
322 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
323 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
324 // Shift distances are potentially of the form x and (reg_size - x).
325 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
326 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
327 // Shift distances are potentially of the form d and -d.
328 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
329 }
330 }
331 }
332 return false;
333}
334
335// Try replacing code looking like (x >>> #rdist OP x << #ldist):
336// UShr dst, x, #rdist
337// Shl tmp, x, #ldist
338// OP dst, dst, tmp
339// or like (x >>> #rdist OP x << #-ldist):
340// UShr dst, x, #rdist
341// Shl tmp, x, #-ldist
342// OP dst, dst, tmp
343// with
344// Ror dst, x, #rdist
345bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
346 HUShr* ushr,
347 HShl* shl) {
348 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
349 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
350 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
351 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
352 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
353 ReplaceRotateWithRor(op, ushr, shl);
354 return true;
355 }
356 return false;
357}
358
359// Replace code looking like (x >>> -d OP x << d):
360// Neg neg, d
361// UShr dst, x, neg
362// Shl tmp, x, d
363// OP dst, dst, tmp
364// with
365// Neg neg, d
366// Ror dst, x, neg
367// *** OR ***
368// Replace code looking like (x >>> d OP x << -d):
369// UShr dst, x, d
370// Neg neg, d
371// Shl tmp, x, neg
372// OP dst, dst, tmp
373// with
374// Ror dst, x, d
375bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
376 HUShr* ushr,
377 HShl* shl) {
378 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
379 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
380 bool neg_is_left = shl->GetRight()->IsNeg();
381 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
382 // And the shift distance being negated is the distance being shifted the other way.
383 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
384 ReplaceRotateWithRor(op, ushr, shl);
385 }
386 return false;
387}
388
389// Try replacing code looking like (x >>> d OP x << (#bits - d)):
390// UShr dst, x, d
391// Sub ld, #bits, d
392// Shl tmp, x, ld
393// OP dst, dst, tmp
394// with
395// Ror dst, x, d
396// *** OR ***
397// Replace code looking like (x >>> (#bits - d) OP x << d):
398// Sub rd, #bits, d
399// UShr dst, x, rd
400// Shl tmp, x, d
401// OP dst, dst, tmp
402// with
403// Neg neg, d
404// Ror dst, x, neg
405bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
406 HUShr* ushr,
407 HShl* shl) {
408 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
409 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
410 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
411 HInstruction* shl_shift = shl->GetRight();
412 HInstruction* ushr_shift = ushr->GetRight();
413 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
414 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
415 return ReplaceRotateWithRor(op, ushr, shl);
416 }
417 return false;
418}
419
Calin Juravle10e244f2015-01-26 18:54:32 +0000420void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
421 HInstruction* obj = null_check->InputAt(0);
422 if (!obj->CanBeNull()) {
423 null_check->ReplaceWith(obj);
424 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000425 if (stats_ != nullptr) {
426 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
427 }
428 }
429}
430
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100431bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
432 if (!input->CanBeNull()) {
433 return true;
434 }
435
Vladimir Marko46817b82016-03-29 12:21:58 +0100436 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
437 HInstruction* user = use.GetUser();
438 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100439 return true;
440 }
441 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100442
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100443 return false;
444}
445
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100446// Returns whether doing a type test between the class of `object` against `klass` has
447// a statically known outcome. The result of the test is stored in `outcome`.
448static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000449 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
450 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
451 ScopedObjectAccess soa(Thread::Current());
452 if (!obj_rti.IsValid()) {
453 // We run the simplifier before the reference type propagation so type info might not be
454 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100455 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000456 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100457
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100458 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100459 if (!class_rti.IsValid()) {
460 // Happens when the loaded class is unresolved.
461 return false;
462 }
463 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000464 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100465 *outcome = true;
466 return true;
467 } else if (obj_rti.IsExact()) {
468 // The test failed at compile time so will also fail at runtime.
469 *outcome = false;
470 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100471 } else if (!class_rti.IsInterface()
472 && !obj_rti.IsInterface()
473 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100474 // Different type hierarchy. The test will fail.
475 *outcome = false;
476 return true;
477 }
478 return false;
479}
480
481void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
482 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100483 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
484 if (load_class->NeedsAccessCheck()) {
485 // If we need to perform an access check we cannot remove the instruction.
486 return;
487 }
488
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100489 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100490 check_cast->ClearMustDoNullCheck();
491 }
492
493 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000494 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000495 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100496 return;
497 }
498
Vladimir Markoa65ed302016-03-14 21:21:29 +0000499 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
500 // the return value check with the `outcome` check, b/27651442 .
501 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700502 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100503 if (outcome) {
504 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000505 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700506 if (!load_class->HasUses()) {
507 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
508 // However, here we know that it cannot because the checkcast was successfull, hence
509 // the class was already loaded.
510 load_class->GetBlock()->RemoveInstruction(load_class);
511 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100512 } else {
513 // Don't do anything for exceptional cases for now. Ideally we should remove
514 // all instructions and blocks this instruction dominates.
515 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000516 }
517}
518
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100519void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100520 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100521 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
522 if (load_class->NeedsAccessCheck()) {
523 // If we need to perform an access check we cannot remove the instruction.
524 return;
525 }
526
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100527 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100528 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100529 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100530 instruction->ClearMustDoNullCheck();
531 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100532
533 HGraph* graph = GetGraph();
534 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000535 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100536 instruction->ReplaceWith(graph->GetIntConstant(0));
537 instruction->GetBlock()->RemoveInstruction(instruction);
538 RecordSimplification();
539 return;
540 }
541
Vladimir Marko24bd8952016-03-15 10:40:33 +0000542 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
543 // the return value check with the `outcome` check, b/27651442 .
544 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700545 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000546 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100547 if (outcome && can_be_null) {
548 // Type test will succeed, we just need a null test.
549 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
550 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
551 instruction->ReplaceWith(test);
552 } else {
553 // We've statically determined the result of the instanceof.
554 instruction->ReplaceWith(graph->GetIntConstant(outcome));
555 }
556 RecordSimplification();
557 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700558 if (outcome && !load_class->HasUses()) {
559 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
560 // However, here we know that it cannot because the instanceof check was successfull, hence
561 // the class was already loaded.
562 load_class->GetBlock()->RemoveInstruction(load_class);
563 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100564 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100565}
566
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100567void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
568 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100569 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100570 instruction->ClearValueCanBeNull();
571 }
572}
573
574void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
575 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100576 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100577 instruction->ClearValueCanBeNull();
578 }
579}
580
Anton Shaminbdd79352016-02-15 12:48:36 +0600581static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
582 HInstruction *lhs = cond->InputAt(0);
583 HInstruction *rhs = cond->InputAt(1);
584 switch (cond->GetKind()) {
585 case HInstruction::kEqual:
586 return new (arena) HEqual(rhs, lhs);
587 case HInstruction::kNotEqual:
588 return new (arena) HNotEqual(rhs, lhs);
589 case HInstruction::kLessThan:
590 return new (arena) HGreaterThan(rhs, lhs);
591 case HInstruction::kLessThanOrEqual:
592 return new (arena) HGreaterThanOrEqual(rhs, lhs);
593 case HInstruction::kGreaterThan:
594 return new (arena) HLessThan(rhs, lhs);
595 case HInstruction::kGreaterThanOrEqual:
596 return new (arena) HLessThanOrEqual(rhs, lhs);
597 case HInstruction::kBelow:
598 return new (arena) HAbove(rhs, lhs);
599 case HInstruction::kBelowOrEqual:
600 return new (arena) HAboveOrEqual(rhs, lhs);
601 case HInstruction::kAbove:
602 return new (arena) HBelow(rhs, lhs);
603 case HInstruction::kAboveOrEqual:
604 return new (arena) HBelowOrEqual(rhs, lhs);
605 default:
606 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
607 }
608 return nullptr;
609}
610
Aart Bik2767f4b2016-10-28 15:03:53 -0700611static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
612 if (input->GetType() == Primitive::kPrimBoolean) {
613 return true; // input has direct boolean type
614 } else if (cmp->GetUses().HasExactlyOneElement()) {
615 // Comparison also has boolean type if both its input and the instruction
616 // itself feed into the same phi node.
617 HInstruction* user = cmp->GetUses().front().GetUser();
618 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
619 }
620 return false;
621}
622
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000623void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100624 HInstruction* input_const = equal->GetConstantRight();
625 if (input_const != nullptr) {
626 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700627 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100628 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100629 // We are comparing the boolean to a constant which is of type int and can
630 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000631 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100632 // Replace (bool_value == true) with bool_value
633 equal->ReplaceWith(input_value);
634 block->RemoveInstruction(equal);
635 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000636 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700637 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500638 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
639 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100640 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100641 } else {
642 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
643 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
644 block->RemoveInstruction(equal);
645 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100646 }
Mark Mendellc4701932015-04-10 13:18:51 -0400647 } else {
648 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100649 }
Mark Mendellc4701932015-04-10 13:18:51 -0400650 } else {
651 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100652 }
653}
654
David Brazdil0d13fee2015-04-17 14:52:19 +0100655void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
656 HInstruction* input_const = not_equal->GetConstantRight();
657 if (input_const != nullptr) {
658 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700659 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100660 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100661 // We are comparing the boolean to a constant which is of type int and can
662 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000663 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700664 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500665 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
666 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100667 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000668 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100669 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100670 not_equal->ReplaceWith(input_value);
671 block->RemoveInstruction(not_equal);
672 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100673 } else {
674 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
675 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
676 block->RemoveInstruction(not_equal);
677 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100678 }
Mark Mendellc4701932015-04-10 13:18:51 -0400679 } else {
680 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100681 }
Mark Mendellc4701932015-04-10 13:18:51 -0400682 } else {
683 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100684 }
685}
686
687void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000688 HInstruction* input = bool_not->InputAt(0);
689 HInstruction* replace_with = nullptr;
690
691 if (input->IsIntConstant()) {
692 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000693 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000694 replace_with = GetGraph()->GetIntConstant(0);
695 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000696 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000697 replace_with = GetGraph()->GetIntConstant(1);
698 }
699 } else if (input->IsBooleanNot()) {
700 // Replace (!(!bool_value)) with bool_value.
701 replace_with = input->InputAt(0);
702 } else if (input->IsCondition() &&
703 // Don't change FP compares. The definition of compares involving
704 // NaNs forces the compares to be done as written by the user.
705 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
706 // Replace condition with its opposite.
707 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
708 }
709
710 if (replace_with != nullptr) {
711 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100712 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000713 RecordSimplification();
714 }
715}
716
717void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
718 HInstruction* replace_with = nullptr;
719 HInstruction* condition = select->GetCondition();
720 HInstruction* true_value = select->GetTrueValue();
721 HInstruction* false_value = select->GetFalseValue();
722
723 if (condition->IsBooleanNot()) {
724 // Change ((!cond) ? x : y) to (cond ? y : x).
725 condition = condition->InputAt(0);
726 std::swap(true_value, false_value);
727 select->ReplaceInput(false_value, 0);
728 select->ReplaceInput(true_value, 1);
729 select->ReplaceInput(condition, 2);
730 RecordSimplification();
731 }
732
733 if (true_value == false_value) {
734 // Replace (cond ? x : x) with (x).
735 replace_with = true_value;
736 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000737 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000738 // Replace (true ? x : y) with (x).
739 replace_with = true_value;
740 } else {
741 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000742 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000743 replace_with = false_value;
744 }
745 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000746 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000747 // Replace (cond ? true : false) with (cond).
748 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000749 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000750 // Replace (cond ? false : true) with (!cond).
751 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
752 }
753 }
754
755 if (replace_with != nullptr) {
756 select->ReplaceWith(replace_with);
757 select->GetBlock()->RemoveInstruction(select);
758 RecordSimplification();
759 }
760}
761
762void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
763 HInstruction* condition = instruction->InputAt(0);
764 if (condition->IsBooleanNot()) {
765 // Swap successors if input is negated.
766 instruction->ReplaceInput(condition->InputAt(0), 0);
767 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100768 RecordSimplification();
769 }
770}
771
Mingyao Yang0304e182015-01-30 16:41:29 -0800772void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
773 HInstruction* input = instruction->InputAt(0);
774 // If the array is a NewArray with constant size, replace the array length
775 // with the constant instruction. This helps the bounds check elimination phase.
776 if (input->IsNewArray()) {
777 input = input->InputAt(0);
778 if (input->IsIntConstant()) {
779 instruction->ReplaceWith(input);
780 }
781 }
782}
783
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000784void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000785 HInstruction* value = instruction->GetValue();
786 if (value->GetType() != Primitive::kPrimNot) return;
787
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100788 if (CanEnsureNotNullAt(value, instruction)) {
789 instruction->ClearValueCanBeNull();
790 }
791
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000792 if (value->IsArrayGet()) {
793 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
794 // If the code is just swapping elements in the array, no need for a type check.
795 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100796 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000797 }
798 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100799
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100800 if (value->IsNullConstant()) {
801 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100802 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100803 }
804
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100805 ScopedObjectAccess soa(Thread::Current());
806 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
807 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
808 if (!array_rti.IsValid()) {
809 return;
810 }
811
812 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
813 instruction->ClearNeedsTypeCheck();
814 return;
815 }
816
817 if (array_rti.IsObjectArray()) {
818 if (array_rti.IsExact()) {
819 instruction->ClearNeedsTypeCheck();
820 return;
821 }
822 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100823 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000824}
825
Vladimir Markob52bbde2016-02-12 12:06:05 +0000826static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100827 // Invariant: We should never generate a conversion to a Boolean value.
828 DCHECK_NE(Primitive::kPrimBoolean, result_type);
829
Vladimir Markob52bbde2016-02-12 12:06:05 +0000830 // Besides conversion to the same type, widening integral conversions are implicit,
831 // excluding conversions to long and the byte->char conversion where we need to
832 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
833 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100834 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
835 input_type == Primitive::kPrimByte ||
836 input_type == Primitive::kPrimShort ||
837 input_type == Primitive::kPrimChar)) ||
838 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
839 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
840 input_type == Primitive::kPrimByte)) ||
841 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000842}
843
844static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
845 // The conversion to a larger type is loss-less with the exception of two cases,
846 // - conversion to char, the only unsigned type, where we may lose some bits, and
847 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
848 // For integral to FP conversions this holds because the FP mantissa is large enough.
849 DCHECK_NE(input_type, result_type);
850 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
851 result_type != Primitive::kPrimChar &&
852 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
853}
854
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000855void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000856 HInstruction* input = instruction->GetInput();
857 Primitive::Type input_type = input->GetType();
858 Primitive::Type result_type = instruction->GetResultType();
859 if (IsTypeConversionImplicit(input_type, result_type)) {
860 // Remove the implicit conversion; this includes conversion to the same type.
861 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000862 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000863 RecordSimplification();
864 return;
865 }
866
867 if (input->IsTypeConversion()) {
868 HTypeConversion* input_conversion = input->AsTypeConversion();
869 HInstruction* original_input = input_conversion->GetInput();
870 Primitive::Type original_type = original_input->GetType();
871
872 // When the first conversion is lossless, a direct conversion from the original type
873 // to the final type yields the same result, even for a lossy second conversion, for
874 // example float->double->int or int->double->float.
875 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
876
877 // For integral conversions, see if the first conversion loses only bits that the second
878 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
879 // conversion yields the same result, for example long->int->short or int->char->short.
880 bool integral_conversions_with_non_widening_second =
881 Primitive::IsIntegralType(input_type) &&
882 Primitive::IsIntegralType(original_type) &&
883 Primitive::IsIntegralType(result_type) &&
884 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
885
886 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
887 // If the merged conversion is implicit, do the simplification unconditionally.
888 if (IsTypeConversionImplicit(original_type, result_type)) {
889 instruction->ReplaceWith(original_input);
890 instruction->GetBlock()->RemoveInstruction(instruction);
891 if (!input_conversion->HasUses()) {
892 // Don't wait for DCE.
893 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
894 }
895 RecordSimplification();
896 return;
897 }
898 // Otherwise simplify only if the first conversion has no other use.
899 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
900 input_conversion->ReplaceWith(original_input);
901 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
902 RecordSimplification();
903 return;
904 }
905 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000906 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000907 DCHECK(Primitive::IsIntegralType(input_type));
908 HAnd* input_and = input->AsAnd();
909 HConstant* constant = input_and->GetConstantRight();
910 if (constant != nullptr) {
911 int64_t value = Int64FromConstant(constant);
912 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
913 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
914 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
915 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000916 HInstruction* original_input = input_and->GetLeastConstantLeft();
917 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
918 instruction->ReplaceWith(original_input);
919 instruction->GetBlock()->RemoveInstruction(instruction);
920 RecordSimplification();
921 return;
922 } else if (input->HasOnlyOneNonEnvironmentUse()) {
923 input_and->ReplaceWith(original_input);
924 input_and->GetBlock()->RemoveInstruction(input_and);
925 RecordSimplification();
926 return;
927 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000928 }
929 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000930 }
931}
932
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000933void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
934 HConstant* input_cst = instruction->GetConstantRight();
935 HInstruction* input_other = instruction->GetLeastConstantLeft();
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600936 bool integral_type = Primitive::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +0000937 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000938 // Replace code looking like
939 // ADD dst, src, 0
940 // with
941 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600942 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
943 // `x` is `-0.0`, the former expression yields `0.0`, while the later
944 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600945 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +0600946 instruction->ReplaceWith(input_other);
947 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100948 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600949 return;
950 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100951 }
952
953 HInstruction* left = instruction->GetLeft();
954 HInstruction* right = instruction->GetRight();
955 bool left_is_neg = left->IsNeg();
956 bool right_is_neg = right->IsNeg();
957
958 if (left_is_neg && right_is_neg) {
959 if (TryMoveNegOnInputsAfterBinop(instruction)) {
960 return;
961 }
962 }
963
964 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
965 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
966 // Replace code looking like
967 // NEG tmp, b
968 // ADD dst, a, tmp
969 // with
970 // SUB dst, a, b
971 // We do not perform the optimization if the input negation has environment
972 // uses or multiple non-environment uses as it could lead to worse code. In
973 // particular, we do not want the live range of `b` to be extended if we are
974 // not sure the initial 'NEG' instruction can be removed.
975 HInstruction* other = left_is_neg ? right : left;
976 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
977 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
978 RecordSimplification();
979 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000980 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000981 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000982
Anton Kirilove14dc862016-05-13 17:56:15 +0100983 if (TryReplaceWithRotate(instruction)) {
984 return;
985 }
986
987 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
988 // so no need to return.
989 TryHandleAssociativeAndCommutativeOperation(instruction);
990
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600991 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +0100992 TrySubtractionChainSimplification(instruction)) {
993 return;
994 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +0600995
996 if (integral_type) {
997 // Replace code patterns looking like
998 // SUB dst1, x, y SUB dst1, x, y
999 // ADD dst2, dst1, y ADD dst2, y, dst1
1000 // with
1001 // SUB dst1, x, y
1002 // ADD instruction is not needed in this case, we may use
1003 // one of inputs of SUB instead.
1004 if (left->IsSub() && left->InputAt(1) == right) {
1005 instruction->ReplaceWith(left->InputAt(0));
1006 RecordSimplification();
1007 instruction->GetBlock()->RemoveInstruction(instruction);
1008 return;
1009 } else if (right->IsSub() && right->InputAt(1) == left) {
1010 instruction->ReplaceWith(right->InputAt(0));
1011 RecordSimplification();
1012 instruction->GetBlock()->RemoveInstruction(instruction);
1013 return;
1014 }
1015 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001016}
1017
1018void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1019 HConstant* input_cst = instruction->GetConstantRight();
1020 HInstruction* input_other = instruction->GetLeastConstantLeft();
1021
Vladimir Marko452c1b62015-09-25 14:44:17 +01001022 if (input_cst != nullptr) {
1023 int64_t value = Int64FromConstant(input_cst);
1024 if (value == -1) {
1025 // Replace code looking like
1026 // AND dst, src, 0xFFF...FF
1027 // with
1028 // src
1029 instruction->ReplaceWith(input_other);
1030 instruction->GetBlock()->RemoveInstruction(instruction);
1031 RecordSimplification();
1032 return;
1033 }
1034 // Eliminate And from UShr+And if the And-mask contains all the bits that
1035 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1036 // precisely clears the shifted-in sign bits.
1037 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
1038 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
1039 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1040 size_t num_tail_bits_set = CTZ(value + 1);
1041 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1042 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1043 instruction->ReplaceWith(input_other);
1044 instruction->GetBlock()->RemoveInstruction(instruction);
1045 RecordSimplification();
1046 return;
1047 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1048 input_other->HasOnlyOneNonEnvironmentUse()) {
1049 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1050 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1051 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1052 input_other->InputAt(0),
1053 input_other->InputAt(1),
1054 input_other->GetDexPc());
1055 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1056 input_other->GetBlock()->RemoveInstruction(input_other);
1057 RecordSimplification();
1058 return;
1059 }
1060 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001061 }
1062
1063 // We assume that GVN has run before, so we only perform a pointer comparison.
1064 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001065 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001066 if (instruction->GetLeft() == instruction->GetRight()) {
1067 // Replace code looking like
1068 // AND dst, src, src
1069 // with
1070 // src
1071 instruction->ReplaceWith(instruction->GetLeft());
1072 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001073 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001074 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001075 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001076
Anton Kirilove14dc862016-05-13 17:56:15 +01001077 if (TryDeMorganNegationFactoring(instruction)) {
1078 return;
1079 }
1080
1081 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1082 // so no need to return.
1083 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001084}
1085
Mark Mendellc4701932015-04-10 13:18:51 -04001086void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1087 VisitCondition(condition);
1088}
1089
1090void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1091 VisitCondition(condition);
1092}
1093
1094void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1095 VisitCondition(condition);
1096}
1097
1098void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1099 VisitCondition(condition);
1100}
1101
Anton Shaminbdd79352016-02-15 12:48:36 +06001102void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1103 VisitCondition(condition);
1104}
1105
1106void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1107 VisitCondition(condition);
1108}
1109
1110void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1111 VisitCondition(condition);
1112}
1113
1114void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1115 VisitCondition(condition);
1116}
Aart Bike9f37602015-10-09 11:15:55 -07001117
Mark Mendellc4701932015-04-10 13:18:51 -04001118void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001119 // Reverse condition if left is constant. Our code generators prefer constant
1120 // on the right hand side.
1121 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1122 HBasicBlock* block = condition->GetBlock();
1123 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1124 // If it is a fp we must set the opposite bias.
1125 if (replacement != nullptr) {
1126 if (condition->IsLtBias()) {
1127 replacement->SetBias(ComparisonBias::kGtBias);
1128 } else if (condition->IsGtBias()) {
1129 replacement->SetBias(ComparisonBias::kLtBias);
1130 }
1131 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1132 RecordSimplification();
1133
1134 condition = replacement;
1135 }
1136 }
Mark Mendellc4701932015-04-10 13:18:51 -04001137
Mark Mendellc4701932015-04-10 13:18:51 -04001138 HInstruction* left = condition->GetLeft();
1139 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001140
1141 // Try to fold an HCompare into this HCondition.
1142
Mark Mendellc4701932015-04-10 13:18:51 -04001143 // We can only replace an HCondition which compares a Compare to 0.
1144 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1145 // condition with a long, float or double comparison as input.
1146 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1147 // Conversion is not possible.
1148 return;
1149 }
1150
1151 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001152 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001153 // Someone else also wants the result of the compare.
1154 return;
1155 }
1156
Vladimir Marko46817b82016-03-29 12:21:58 +01001157 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001158 // There is a reference to the compare result in an environment. Do we really need it?
1159 if (GetGraph()->IsDebuggable()) {
1160 return;
1161 }
1162
1163 // We have to ensure that there are no deopt points in the sequence.
1164 if (left->HasAnyEnvironmentUseBefore(condition)) {
1165 return;
1166 }
1167 }
1168
1169 // Clean up any environment uses from the HCompare, if any.
1170 left->RemoveEnvironmentUsers();
1171
1172 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1173 condition->SetBias(left->AsCompare()->GetBias());
1174
1175 // Replace the operands of the HCondition.
1176 condition->ReplaceInput(left->InputAt(0), 0);
1177 condition->ReplaceInput(left->InputAt(1), 1);
1178
1179 // Remove the HCompare.
1180 left->GetBlock()->RemoveInstruction(left);
1181
1182 RecordSimplification();
1183}
1184
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001185void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1186 HConstant* input_cst = instruction->GetConstantRight();
1187 HInstruction* input_other = instruction->GetLeastConstantLeft();
1188 Primitive::Type type = instruction->GetType();
1189
1190 if ((input_cst != nullptr) && input_cst->IsOne()) {
1191 // Replace code looking like
1192 // DIV dst, src, 1
1193 // with
1194 // src
1195 instruction->ReplaceWith(input_other);
1196 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001197 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001198 return;
1199 }
1200
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001201 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001202 // Replace code looking like
1203 // DIV dst, src, -1
1204 // with
1205 // NEG dst, src
1206 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001207 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001208 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001209 return;
1210 }
1211
1212 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1213 // Try replacing code looking like
1214 // DIV dst, src, constant
1215 // with
1216 // MUL dst, src, 1 / constant
1217 HConstant* reciprocal = nullptr;
1218 if (type == Primitive::Primitive::kPrimDouble) {
1219 double value = input_cst->AsDoubleConstant()->GetValue();
1220 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1221 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1222 }
1223 } else {
1224 DCHECK_EQ(type, Primitive::kPrimFloat);
1225 float value = input_cst->AsFloatConstant()->GetValue();
1226 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1227 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1228 }
1229 }
1230
1231 if (reciprocal != nullptr) {
1232 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1233 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1234 RecordSimplification();
1235 return;
1236 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001237 }
1238}
1239
1240void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1241 HConstant* input_cst = instruction->GetConstantRight();
1242 HInstruction* input_other = instruction->GetLeastConstantLeft();
1243 Primitive::Type type = instruction->GetType();
1244 HBasicBlock* block = instruction->GetBlock();
1245 ArenaAllocator* allocator = GetGraph()->GetArena();
1246
1247 if (input_cst == nullptr) {
1248 return;
1249 }
1250
1251 if (input_cst->IsOne()) {
1252 // Replace code looking like
1253 // MUL dst, src, 1
1254 // with
1255 // src
1256 instruction->ReplaceWith(input_other);
1257 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001258 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001259 return;
1260 }
1261
1262 if (input_cst->IsMinusOne() &&
1263 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1264 // Replace code looking like
1265 // MUL dst, src, -1
1266 // with
1267 // NEG dst, src
1268 HNeg* neg = new (allocator) HNeg(type, input_other);
1269 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001270 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001271 return;
1272 }
1273
1274 if (Primitive::IsFloatingPointType(type) &&
1275 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1276 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1277 // Replace code looking like
1278 // FP_MUL dst, src, 2.0
1279 // with
1280 // FP_ADD dst, src, src
1281 // The 'int' and 'long' cases are handled below.
1282 block->ReplaceAndRemoveInstructionWith(instruction,
1283 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001284 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001285 return;
1286 }
1287
1288 if (Primitive::IsIntOrLongType(type)) {
1289 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001290 // Even though constant propagation also takes care of the zero case, other
1291 // optimizations can lead to having a zero multiplication.
1292 if (factor == 0) {
1293 // Replace code looking like
1294 // MUL dst, src, 0
1295 // with
1296 // 0
1297 instruction->ReplaceWith(input_cst);
1298 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001299 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001300 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001301 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001302 // Replace code looking like
1303 // MUL dst, src, pow_of_2
1304 // with
1305 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001306 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001307 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001308 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001309 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001310 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001311 } else if (IsPowerOfTwo(factor - 1)) {
1312 // Transform code looking like
1313 // MUL dst, src, (2^n + 1)
1314 // into
1315 // SHL tmp, src, n
1316 // ADD dst, src, tmp
1317 HShl* shl = new (allocator) HShl(type,
1318 input_other,
1319 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1320 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1321
1322 block->InsertInstructionBefore(shl, instruction);
1323 block->ReplaceAndRemoveInstructionWith(instruction, add);
1324 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001325 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001326 } else if (IsPowerOfTwo(factor + 1)) {
1327 // Transform code looking like
1328 // MUL dst, src, (2^n - 1)
1329 // into
1330 // SHL tmp, src, n
1331 // SUB dst, tmp, src
1332 HShl* shl = new (allocator) HShl(type,
1333 input_other,
1334 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1335 HSub* sub = new (allocator) HSub(type, shl, input_other);
1336
1337 block->InsertInstructionBefore(shl, instruction);
1338 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1339 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001340 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001341 }
1342 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001343
1344 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1345 // so no need to return.
1346 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001347}
1348
Alexandre Rames188d4312015-04-09 18:30:21 +01001349void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1350 HInstruction* input = instruction->GetInput();
1351 if (input->IsNeg()) {
1352 // Replace code looking like
1353 // NEG tmp, src
1354 // NEG dst, tmp
1355 // with
1356 // src
1357 HNeg* previous_neg = input->AsNeg();
1358 instruction->ReplaceWith(previous_neg->GetInput());
1359 instruction->GetBlock()->RemoveInstruction(instruction);
1360 // We perform the optimization even if the input negation has environment
1361 // uses since it allows removing the current instruction. But we only delete
1362 // the input negation only if it is does not have any uses left.
1363 if (!previous_neg->HasUses()) {
1364 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1365 }
1366 RecordSimplification();
1367 return;
1368 }
1369
Serguei Katkov339dfc22015-04-20 12:29:32 +06001370 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1371 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001372 // Replace code looking like
1373 // SUB tmp, a, b
1374 // NEG dst, tmp
1375 // with
1376 // SUB dst, b, a
1377 // We do not perform the optimization if the input subtraction has
1378 // environment uses or multiple non-environment uses as it could lead to
1379 // worse code. In particular, we do not want the live ranges of `a` and `b`
1380 // to be extended if we are not sure the initial 'SUB' instruction can be
1381 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001382 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001383 HSub* sub = input->AsSub();
1384 HSub* new_sub =
1385 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1386 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1387 if (!sub->HasUses()) {
1388 sub->GetBlock()->RemoveInstruction(sub);
1389 }
1390 RecordSimplification();
1391 }
1392}
1393
1394void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1395 HInstruction* input = instruction->GetInput();
1396 if (input->IsNot()) {
1397 // Replace code looking like
1398 // NOT tmp, src
1399 // NOT dst, tmp
1400 // with
1401 // src
1402 // We perform the optimization even if the input negation has environment
1403 // uses since it allows removing the current instruction. But we only delete
1404 // the input negation only if it is does not have any uses left.
1405 HNot* previous_not = input->AsNot();
1406 instruction->ReplaceWith(previous_not->GetInput());
1407 instruction->GetBlock()->RemoveInstruction(instruction);
1408 if (!previous_not->HasUses()) {
1409 previous_not->GetBlock()->RemoveInstruction(previous_not);
1410 }
1411 RecordSimplification();
1412 }
1413}
1414
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001415void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1416 HConstant* input_cst = instruction->GetConstantRight();
1417 HInstruction* input_other = instruction->GetLeastConstantLeft();
1418
Roland Levillain1a653882016-03-18 18:05:57 +00001419 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001420 // Replace code looking like
1421 // OR dst, src, 0
1422 // with
1423 // src
1424 instruction->ReplaceWith(input_other);
1425 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001426 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001427 return;
1428 }
1429
1430 // We assume that GVN has run before, so we only perform a pointer comparison.
1431 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001432 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001433 if (instruction->GetLeft() == instruction->GetRight()) {
1434 // Replace code looking like
1435 // OR dst, src, src
1436 // with
1437 // src
1438 instruction->ReplaceWith(instruction->GetLeft());
1439 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001440 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001441 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001442 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001443
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001444 if (TryDeMorganNegationFactoring(instruction)) return;
1445
Anton Kirilove14dc862016-05-13 17:56:15 +01001446 if (TryReplaceWithRotate(instruction)) {
1447 return;
1448 }
1449
1450 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1451 // so no need to return.
1452 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001453}
1454
1455void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1456 VisitShift(instruction);
1457}
1458
1459void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1460 VisitShift(instruction);
1461}
1462
1463void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1464 HConstant* input_cst = instruction->GetConstantRight();
1465 HInstruction* input_other = instruction->GetLeastConstantLeft();
1466
Serguei Katkov115b53f2015-08-05 17:03:30 +06001467 Primitive::Type type = instruction->GetType();
1468 if (Primitive::IsFloatingPointType(type)) {
1469 return;
1470 }
1471
Roland Levillain1a653882016-03-18 18:05:57 +00001472 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001473 // Replace code looking like
1474 // SUB dst, src, 0
1475 // with
1476 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001477 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1478 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1479 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001480 instruction->ReplaceWith(input_other);
1481 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001482 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001483 return;
1484 }
1485
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001486 HBasicBlock* block = instruction->GetBlock();
1487 ArenaAllocator* allocator = GetGraph()->GetArena();
1488
Alexandre Rames188d4312015-04-09 18:30:21 +01001489 HInstruction* left = instruction->GetLeft();
1490 HInstruction* right = instruction->GetRight();
1491 if (left->IsConstant()) {
1492 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001493 // Replace code looking like
1494 // SUB dst, 0, src
1495 // with
1496 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001497 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001498 // `x` is `0.0`, the former expression yields `0.0`, while the later
1499 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001500 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001501 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001502 RecordSimplification();
1503 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001504 }
1505 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001506
1507 if (left->IsNeg() && right->IsNeg()) {
1508 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1509 return;
1510 }
1511 }
1512
1513 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1514 // Replace code looking like
1515 // NEG tmp, b
1516 // SUB dst, a, tmp
1517 // with
1518 // ADD dst, a, b
1519 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1520 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1521 RecordSimplification();
1522 right->GetBlock()->RemoveInstruction(right);
1523 return;
1524 }
1525
1526 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1527 // Replace code looking like
1528 // NEG tmp, a
1529 // SUB dst, tmp, b
1530 // with
1531 // ADD tmp, a, b
1532 // NEG dst, tmp
1533 // The second version is not intrinsically better, but enables more
1534 // transformations.
1535 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1536 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1537 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1538 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1539 instruction->ReplaceWith(neg);
1540 instruction->GetBlock()->RemoveInstruction(instruction);
1541 RecordSimplification();
1542 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001543 return;
1544 }
1545
1546 if (TrySubtractionChainSimplification(instruction)) {
1547 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001548 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001549
1550 if (left->IsAdd()) {
1551 // Replace code patterns looking like
1552 // ADD dst1, x, y ADD dst1, x, y
1553 // SUB dst2, dst1, y SUB dst2, dst1, x
1554 // with
1555 // ADD dst1, x, y
1556 // SUB instruction is not needed in this case, we may use
1557 // one of inputs of ADD instead.
1558 // It is applicable to integral types only.
1559 DCHECK(Primitive::IsIntegralType(type));
1560 if (left->InputAt(1) == right) {
1561 instruction->ReplaceWith(left->InputAt(0));
1562 RecordSimplification();
1563 instruction->GetBlock()->RemoveInstruction(instruction);
1564 return;
1565 } else if (left->InputAt(0) == right) {
1566 instruction->ReplaceWith(left->InputAt(1));
1567 RecordSimplification();
1568 instruction->GetBlock()->RemoveInstruction(instruction);
1569 return;
1570 }
1571 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001572}
1573
1574void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1575 VisitShift(instruction);
1576}
1577
1578void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1579 HConstant* input_cst = instruction->GetConstantRight();
1580 HInstruction* input_other = instruction->GetLeastConstantLeft();
1581
Roland Levillain1a653882016-03-18 18:05:57 +00001582 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001583 // Replace code looking like
1584 // XOR dst, src, 0
1585 // with
1586 // src
1587 instruction->ReplaceWith(input_other);
1588 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001589 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001590 return;
1591 }
1592
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001593 if ((input_cst != nullptr) && input_cst->IsOne()
1594 && input_other->GetType() == Primitive::kPrimBoolean) {
1595 // Replace code looking like
1596 // XOR dst, src, 1
1597 // with
1598 // BOOLEAN_NOT dst, src
1599 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1600 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1601 RecordSimplification();
1602 return;
1603 }
1604
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001605 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1606 // Replace code looking like
1607 // XOR dst, src, 0xFFF...FF
1608 // with
1609 // NOT dst, src
1610 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1611 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001612 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001613 return;
1614 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001615
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001616 HInstruction* left = instruction->GetLeft();
1617 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001618 if (((left->IsNot() && right->IsNot()) ||
1619 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001620 left->HasOnlyOneNonEnvironmentUse() &&
1621 right->HasOnlyOneNonEnvironmentUse()) {
1622 // Replace code looking like
1623 // NOT nota, a
1624 // NOT notb, b
1625 // XOR dst, nota, notb
1626 // with
1627 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001628 instruction->ReplaceInput(left->InputAt(0), 0);
1629 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001630 left->GetBlock()->RemoveInstruction(left);
1631 right->GetBlock()->RemoveInstruction(right);
1632 RecordSimplification();
1633 return;
1634 }
1635
Anton Kirilove14dc862016-05-13 17:56:15 +01001636 if (TryReplaceWithRotate(instruction)) {
1637 return;
1638 }
1639
1640 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1641 // so no need to return.
1642 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001643}
1644
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001645void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1646 HInstruction* argument = instruction->InputAt(1);
1647 HInstruction* receiver = instruction->InputAt(0);
1648 if (receiver == argument) {
1649 // Because String.equals is an instance call, the receiver is
1650 // a null check if we don't know it's null. The argument however, will
1651 // be the actual object. So we cannot end up in a situation where both
1652 // are equal but could be null.
1653 DCHECK(CanEnsureNotNullAt(argument, instruction));
1654 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1655 instruction->GetBlock()->RemoveInstruction(instruction);
1656 } else {
1657 StringEqualsOptimizations optimizations(instruction);
1658 if (CanEnsureNotNullAt(argument, instruction)) {
1659 optimizations.SetArgumentNotNull();
1660 }
1661 ScopedObjectAccess soa(Thread::Current());
1662 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1663 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1664 optimizations.SetArgumentIsString();
1665 }
1666 }
1667}
1668
Roland Levillain22c49222016-03-18 14:04:28 +00001669void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1670 bool is_left,
1671 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001672 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001673 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001674 HInstruction* value = invoke->InputAt(0);
1675 HInstruction* distance = invoke->InputAt(1);
1676 // Replace the invoke with an HRor.
1677 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001678 // Unconditionally set the type of the negated distance to `int`,
1679 // as shift and rotate operations expect a 32-bit (or narrower)
1680 // value for their distance input.
1681 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001682 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1683 }
Roland Levillain22c49222016-03-18 14:04:28 +00001684 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001685 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1686 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001687 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001688 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1689 clinit->GetBlock()->RemoveInstruction(clinit);
1690 HInstruction* ldclass = clinit->InputAt(0);
1691 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1692 ldclass->GetBlock()->RemoveInstruction(ldclass);
1693 }
1694 }
1695}
1696
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001697static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1698 if (potential_length->IsArrayLength()) {
1699 return potential_length->InputAt(0) == potential_array;
1700 }
1701
1702 if (potential_array->IsNewArray()) {
1703 return potential_array->InputAt(0) == potential_length;
1704 }
1705
1706 return false;
1707}
1708
1709void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1710 HInstruction* source = instruction->InputAt(0);
1711 HInstruction* destination = instruction->InputAt(2);
1712 HInstruction* count = instruction->InputAt(4);
1713 SystemArrayCopyOptimizations optimizations(instruction);
1714 if (CanEnsureNotNullAt(source, instruction)) {
1715 optimizations.SetSourceIsNotNull();
1716 }
1717 if (CanEnsureNotNullAt(destination, instruction)) {
1718 optimizations.SetDestinationIsNotNull();
1719 }
1720 if (destination == source) {
1721 optimizations.SetDestinationIsSource();
1722 }
1723
1724 if (IsArrayLengthOf(count, source)) {
1725 optimizations.SetCountIsSourceLength();
1726 }
1727
1728 if (IsArrayLengthOf(count, destination)) {
1729 optimizations.SetCountIsDestinationLength();
1730 }
1731
1732 {
1733 ScopedObjectAccess soa(Thread::Current());
1734 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1735 if (destination_rti.IsValid()) {
1736 if (destination_rti.IsObjectArray()) {
1737 if (destination_rti.IsExact()) {
1738 optimizations.SetDoesNotNeedTypeCheck();
1739 }
1740 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001741 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001742 if (destination_rti.IsPrimitiveArrayClass()) {
1743 optimizations.SetDestinationIsPrimitiveArray();
1744 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1745 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001746 }
1747 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001748 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1749 if (source_rti.IsValid()) {
1750 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1751 optimizations.SetDoesNotNeedTypeCheck();
1752 }
1753 if (source_rti.IsPrimitiveArrayClass()) {
1754 optimizations.SetSourceIsPrimitiveArray();
1755 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1756 optimizations.SetSourceIsNonPrimitiveArray();
1757 }
1758 }
1759 }
1760}
1761
Roland Levillaina5c4a402016-03-15 15:02:50 +00001762void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1763 bool is_signum,
1764 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001765 DCHECK(invoke->IsInvokeStaticOrDirect());
1766 uint32_t dex_pc = invoke->GetDexPc();
1767 HInstruction* left = invoke->InputAt(0);
1768 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001769 if (!is_signum) {
1770 right = invoke->InputAt(1);
1771 } else if (type == Primitive::kPrimLong) {
1772 right = GetGraph()->GetLongConstant(0);
1773 } else {
1774 right = GetGraph()->GetIntConstant(0);
1775 }
1776 HCompare* compare = new (GetGraph()->GetArena())
1777 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1778 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1779}
1780
Aart Bik75a38b22016-02-17 10:41:50 -08001781void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1782 DCHECK(invoke->IsInvokeStaticOrDirect());
1783 uint32_t dex_pc = invoke->GetDexPc();
1784 // IsNaN(x) is the same as x != x.
1785 HInstruction* x = invoke->InputAt(0);
1786 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001787 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001788 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1789}
1790
Aart Bik2a6aad92016-02-25 11:32:32 -08001791void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1792 DCHECK(invoke->IsInvokeStaticOrDirect());
1793 uint32_t dex_pc = invoke->GetDexPc();
1794 HInstruction* x = invoke->InputAt(0);
1795 Primitive::Type type = x->GetType();
1796 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1797 HInstruction* nan;
1798 if (type == Primitive::kPrimDouble) {
1799 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1800 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1801 kNeedsEnvironmentOrCache,
1802 kNoSideEffects,
1803 kNoThrow);
1804 } else {
1805 DCHECK_EQ(type, Primitive::kPrimFloat);
1806 nan = GetGraph()->GetIntConstant(0x7fc00000);
1807 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1808 kNeedsEnvironmentOrCache,
1809 kNoSideEffects,
1810 kNoThrow);
1811 }
1812 // Test IsNaN(x), which is the same as x != x.
1813 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1814 condition->SetBias(ComparisonBias::kLtBias);
1815 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1816 // Select between the two.
1817 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1818 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1819 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1820}
1821
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001822void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
1823 HInstruction* str = invoke->InputAt(0);
1824 HInstruction* index = invoke->InputAt(1);
1825 uint32_t dex_pc = invoke->GetDexPc();
1826 ArenaAllocator* arena = GetGraph()->GetArena();
1827 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1828 // so create the HArrayLength, HBoundsCheck and HArrayGet.
1829 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
1830 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1831 HBoundsCheck* bounds_check =
1832 new (arena) HBoundsCheck(index, length, dex_pc, invoke->GetDexMethodIndex());
1833 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
1834 HArrayGet* array_get =
1835 new (arena) HArrayGet(str, index, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
1836 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
1837 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
1838 GetGraph()->SetHasBoundsChecks(true);
1839}
1840
Vladimir Markodce016e2016-04-28 13:10:02 +01001841void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1842 HInstruction* str = invoke->InputAt(0);
1843 uint32_t dex_pc = invoke->GetDexPc();
1844 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1845 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001846 HArrayLength* length =
1847 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01001848 HInstruction* replacement;
1849 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1850 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1851 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1852 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1853 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1854 replacement = equal;
1855 } else {
1856 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1857 replacement = length;
1858 }
1859 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1860}
1861
Aart Bikff7d89c2016-11-07 08:49:28 -08001862// This method should only be used on intrinsics whose sole way of throwing an
1863// exception is raising a NPE when the nth argument is null. If that argument
1864// is provably non-null, we can clear the flag.
1865void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
1866 HInstruction* arg = invoke->InputAt(n);
1867 if (!arg->CanBeNull()) {
1868 invoke->SetCanThrow(false);
1869 }
1870}
1871
Aart Bik11932592016-03-08 12:42:25 -08001872void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1873 uint32_t dex_pc = invoke->GetDexPc();
1874 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1875 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1876}
1877
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001878void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001879 switch (instruction->GetIntrinsic()) {
1880 case Intrinsics::kStringEquals:
1881 SimplifyStringEquals(instruction);
1882 break;
1883 case Intrinsics::kSystemArrayCopy:
1884 SimplifySystemArrayCopy(instruction);
1885 break;
1886 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001887 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
1888 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001889 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001890 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001891 break;
1892 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001893 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
1894 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001895 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001896 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001897 break;
1898 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001899 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
1900 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001901 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001902 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001903 break;
1904 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001905 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
1906 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001907 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001908 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001909 break;
1910 case Intrinsics::kFloatIsNaN:
1911 case Intrinsics::kDoubleIsNaN:
1912 SimplifyIsNaN(instruction);
1913 break;
1914 case Intrinsics::kFloatFloatToIntBits:
1915 case Intrinsics::kDoubleDoubleToLongBits:
1916 SimplifyFP2Int(instruction);
1917 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001918 case Intrinsics::kStringCharAt:
1919 SimplifyStringCharAt(instruction);
1920 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01001921 case Intrinsics::kStringIsEmpty:
1922 case Intrinsics::kStringLength:
1923 SimplifyStringIsEmptyOrLength(instruction);
1924 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08001925 case Intrinsics::kStringStringIndexOf:
1926 case Intrinsics::kStringStringIndexOfAfter:
1927 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
1928 break;
Aart Bik11932592016-03-08 12:42:25 -08001929 case Intrinsics::kUnsafeLoadFence:
1930 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1931 break;
1932 case Intrinsics::kUnsafeStoreFence:
1933 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1934 break;
1935 case Intrinsics::kUnsafeFullFence:
1936 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1937 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001938 default:
1939 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001940 }
1941}
1942
Aart Bikbb245d12015-10-19 11:05:03 -07001943void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1944 HInstruction* cond = deoptimize->InputAt(0);
1945 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001946 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07001947 // Never deopt: instruction can be removed.
1948 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1949 } else {
1950 // Always deopt.
1951 }
1952 }
1953}
1954
Anton Kirilove14dc862016-05-13 17:56:15 +01001955// Replace code looking like
1956// OP y, x, const1
1957// OP z, y, const2
1958// with
1959// OP z, x, const3
1960// where OP is both an associative and a commutative operation.
1961bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
1962 HBinaryOperation* instruction) {
1963 DCHECK(instruction->IsCommutative());
1964
1965 if (!Primitive::IsIntegralType(instruction->GetType())) {
1966 return false;
1967 }
1968
1969 HInstruction* left = instruction->GetLeft();
1970 HInstruction* right = instruction->GetRight();
1971 // Variable names as described above.
1972 HConstant* const2;
1973 HBinaryOperation* y;
1974
1975 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
1976 const2 = right->AsConstant();
1977 y = left->AsBinaryOperation();
1978 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
1979 const2 = left->AsConstant();
1980 y = right->AsBinaryOperation();
1981 } else {
1982 // The node does not match the pattern.
1983 return false;
1984 }
1985
1986 // If `y` has more than one use, we do not perform the optimization
1987 // because it might increase code size (e.g. if the new constant is
1988 // no longer encodable as an immediate operand in the target ISA).
1989 if (!y->HasOnlyOneNonEnvironmentUse()) {
1990 return false;
1991 }
1992
1993 // GetConstantRight() can return both left and right constants
1994 // for commutative operations.
1995 HConstant* const1 = y->GetConstantRight();
1996 if (const1 == nullptr) {
1997 return false;
1998 }
1999
2000 instruction->ReplaceInput(const1, 0);
2001 instruction->ReplaceInput(const2, 1);
2002 HConstant* const3 = instruction->TryStaticEvaluation();
2003 DCHECK(const3 != nullptr);
2004 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2005 instruction->ReplaceInput(const3, 1);
2006 RecordSimplification();
2007 return true;
2008}
2009
2010static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2011 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2012}
2013
2014// Helper function that performs addition statically, considering the result type.
2015static int64_t ComputeAddition(Primitive::Type type, int64_t x, int64_t y) {
2016 // Use the Compute() method for consistency with TryStaticEvaluation().
2017 if (type == Primitive::kPrimInt) {
2018 return HAdd::Compute<int32_t>(x, y);
2019 } else {
2020 DCHECK_EQ(type, Primitive::kPrimLong);
2021 return HAdd::Compute<int64_t>(x, y);
2022 }
2023}
2024
2025// Helper function that handles the child classes of HConstant
2026// and returns an integer with the appropriate sign.
2027static int64_t GetValue(HConstant* constant, bool is_negated) {
2028 int64_t ret = Int64FromConstant(constant);
2029 return is_negated ? -ret : ret;
2030}
2031
2032// Replace code looking like
2033// OP1 y, x, const1
2034// OP2 z, y, const2
2035// with
2036// OP3 z, x, const3
2037// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2038bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2039 HBinaryOperation* instruction) {
2040 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2041
2042 Primitive::Type type = instruction->GetType();
2043 if (!Primitive::IsIntegralType(type)) {
2044 return false;
2045 }
2046
2047 HInstruction* left = instruction->GetLeft();
2048 HInstruction* right = instruction->GetRight();
2049 // Variable names as described above.
2050 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2051 if (const2 == nullptr) {
2052 return false;
2053 }
2054
2055 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2056 ? left->AsBinaryOperation()
2057 : AsAddOrSub(right);
2058 // If y has more than one use, we do not perform the optimization because
2059 // it might increase code size (e.g. if the new constant is no longer
2060 // encodable as an immediate operand in the target ISA).
2061 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2062 return false;
2063 }
2064
2065 left = y->GetLeft();
2066 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2067 if (const1 == nullptr) {
2068 return false;
2069 }
2070
2071 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2072 // If both inputs are constants, let the constant folding pass deal with it.
2073 if (x->IsConstant()) {
2074 return false;
2075 }
2076
2077 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2078 int64_t const2_val = GetValue(const2, is_const2_negated);
2079 bool is_y_negated = (y == right) && instruction->IsSub();
2080 right = y->GetRight();
2081 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2082 int64_t const1_val = GetValue(const1, is_const1_negated);
2083 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2084 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2085 HBasicBlock* block = instruction->GetBlock();
2086 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2087 ArenaAllocator* arena = instruction->GetArena();
2088 HInstruction* z;
2089
2090 if (is_x_negated) {
2091 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2092 } else {
2093 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2094 }
2095
2096 block->ReplaceAndRemoveInstructionWith(instruction, z);
2097 RecordSimplification();
2098 return true;
2099}
2100
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002101} // namespace art