blob: 0029cc365060eb7f8bb3e5e4f77581bd4ac05fe1 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
37 if (stats_) {
38 stats_->RecordStat(kInstructionSimplifications);
39 }
40 }
41
Scott Wakeling40a04bf2015-12-11 09:50:36 +000042 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
43 bool TryReplaceWithRotate(HBinaryOperation* instruction);
44 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
45 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
46 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
47
Alexandre Rames188d4312015-04-09 18:30:21 +010048 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000049 // `op` should be either HOr or HAnd.
50 // De Morgan's laws:
51 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
52 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000053 void VisitShift(HBinaryOperation* shift);
54
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000055 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
56 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010057 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
58 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010059 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
60 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000061 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000062 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000063 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080064 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000065 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000066 void VisitAdd(HAdd* instruction) OVERRIDE;
67 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040068 void VisitCondition(HCondition* instruction) OVERRIDE;
69 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
70 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
71 void VisitLessThan(HLessThan* condition) OVERRIDE;
72 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000073 void VisitDiv(HDiv* instruction) OVERRIDE;
74 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010075 void VisitNeg(HNeg* instruction) OVERRIDE;
76 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitOr(HOr* instruction) OVERRIDE;
78 void VisitShl(HShl* instruction) OVERRIDE;
79 void VisitShr(HShr* instruction) OVERRIDE;
80 void VisitSub(HSub* instruction) OVERRIDE;
81 void VisitUShr(HUShr* instruction) OVERRIDE;
82 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000083 void VisitSelect(HSelect* select) OVERRIDE;
84 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010085 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010086 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070087 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010088
89 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000090
Scott Wakeling40a04bf2015-12-11 09:50:36 +000091 void SimplifyRotate(HInvoke* invoke, bool is_left);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010092 void SimplifySystemArrayCopy(HInvoke* invoke);
93 void SimplifyStringEquals(HInvoke* invoke);
Aart Bika19616e2016-02-01 18:57:58 -080094 void SimplifyCompare(HInvoke* invoke, bool has_zero_op);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010095
Calin Juravleacf735c2015-02-12 15:25:22 +000096 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010097 bool simplification_occurred_ = false;
98 int simplifications_at_current_position_ = 0;
99 // We ensure we do not loop infinitely. The value is a finger in the air guess
100 // that should allow enough simplification.
101 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000102};
103
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100104void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000105 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100106 visitor.Run();
107}
108
109void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100110 // Iterate in reverse post order to open up more simplifications to users
111 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100112 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
113 // The simplification of an instruction to another instruction may yield
114 // possibilities for other simplifications. So although we perform a reverse
115 // post order visit, we sometimes need to revisit an instruction index.
116 simplification_occurred_ = false;
117 VisitBasicBlock(it.Current());
118 if (simplification_occurred_ &&
119 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
120 // New simplifications may be applicable to the instruction at the
121 // current index, so don't advance the iterator.
122 continue;
123 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100124 simplifications_at_current_position_ = 0;
125 it.Advance();
126 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100127}
128
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000129namespace {
130
131bool AreAllBitsSet(HConstant* constant) {
132 return Int64FromConstant(constant) == -1;
133}
134
135} // namespace
136
Alexandre Rames188d4312015-04-09 18:30:21 +0100137// Returns true if the code was simplified to use only one negation operation
138// after the binary operation instead of one on each of the inputs.
139bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
140 DCHECK(binop->IsAdd() || binop->IsSub());
141 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
142 HNeg* left_neg = binop->GetLeft()->AsNeg();
143 HNeg* right_neg = binop->GetRight()->AsNeg();
144 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
145 !right_neg->HasOnlyOneNonEnvironmentUse()) {
146 return false;
147 }
148 // Replace code looking like
149 // NEG tmp1, a
150 // NEG tmp2, b
151 // ADD dst, tmp1, tmp2
152 // with
153 // ADD tmp, a, b
154 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600155 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
156 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
157 // while the later yields `-0.0`.
158 if (!Primitive::IsIntegralType(binop->GetType())) {
159 return false;
160 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100161 binop->ReplaceInput(left_neg->GetInput(), 0);
162 binop->ReplaceInput(right_neg->GetInput(), 1);
163 left_neg->GetBlock()->RemoveInstruction(left_neg);
164 right_neg->GetBlock()->RemoveInstruction(right_neg);
165 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
166 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
167 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
168 RecordSimplification();
169 return true;
170}
171
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000172bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
173 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
174 Primitive::Type type = op->GetType();
175 HInstruction* left = op->GetLeft();
176 HInstruction* right = op->GetRight();
177
178 // We can apply De Morgan's laws if both inputs are Not's and are only used
179 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000180 if (((left->IsNot() && right->IsNot()) ||
181 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000182 left->HasOnlyOneNonEnvironmentUse() &&
183 right->HasOnlyOneNonEnvironmentUse()) {
184 // Replace code looking like
185 // NOT nota, a
186 // NOT notb, b
187 // AND dst, nota, notb (respectively OR)
188 // with
189 // OR or, a, b (respectively AND)
190 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000191 HInstruction* src_left = left->InputAt(0);
192 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000193 uint32_t dex_pc = op->GetDexPc();
194
195 // Remove the negations on the inputs.
196 left->ReplaceWith(src_left);
197 right->ReplaceWith(src_right);
198 left->GetBlock()->RemoveInstruction(left);
199 right->GetBlock()->RemoveInstruction(right);
200
201 // Replace the `HAnd` or `HOr`.
202 HBinaryOperation* hbin;
203 if (op->IsAnd()) {
204 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
205 } else {
206 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
207 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000208 HInstruction* hnot;
209 if (left->IsBooleanNot()) {
210 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
211 } else {
212 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
213 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000214
215 op->GetBlock()->InsertInstructionBefore(hbin, op);
216 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
217
218 RecordSimplification();
219 return true;
220 }
221
222 return false;
223}
224
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000225void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
226 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
227 HConstant* input_cst = instruction->GetConstantRight();
228 HInstruction* input_other = instruction->GetLeastConstantLeft();
229
Mark Mendellba56d062015-05-05 21:34:03 -0400230 if (input_cst != nullptr) {
231 if (input_cst->IsZero()) {
232 // Replace code looking like
233 // SHL dst, src, 0
234 // with
235 // src
236 instruction->ReplaceWith(input_other);
237 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400238 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000239 }
240}
241
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000242static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
243 return (sub->GetRight() == other &&
244 sub->GetLeft()->IsConstant() &&
245 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
246}
247
248bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
249 HUShr* ushr,
250 HShl* shl) {
251 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
252 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
253 ushr->GetLeft(),
254 ushr->GetRight());
255 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
256 if (!ushr->HasUses()) {
257 ushr->GetBlock()->RemoveInstruction(ushr);
258 }
259 if (!ushr->GetRight()->HasUses()) {
260 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
261 }
262 if (!shl->HasUses()) {
263 shl->GetBlock()->RemoveInstruction(shl);
264 }
265 if (!shl->GetRight()->HasUses()) {
266 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
267 }
268 return true;
269}
270
271// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
272bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000273 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
274 HInstruction* left = op->GetLeft();
275 HInstruction* right = op->GetRight();
276 // If we have an UShr and a Shl (in either order).
277 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
278 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
279 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
280 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
281 if (ushr->GetType() == shl->GetType() &&
282 ushr->GetLeft() == shl->GetLeft()) {
283 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
284 // Shift distances are both constant, try replacing with Ror if they
285 // add up to the register size.
286 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
287 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
288 // Shift distances are potentially of the form x and (reg_size - x).
289 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
290 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
291 // Shift distances are potentially of the form d and -d.
292 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
293 }
294 }
295 }
296 return false;
297}
298
299// Try replacing code looking like (x >>> #rdist OP x << #ldist):
300// UShr dst, x, #rdist
301// Shl tmp, x, #ldist
302// OP dst, dst, tmp
303// or like (x >>> #rdist OP x << #-ldist):
304// UShr dst, x, #rdist
305// Shl tmp, x, #-ldist
306// OP dst, dst, tmp
307// with
308// Ror dst, x, #rdist
309bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
310 HUShr* ushr,
311 HShl* shl) {
312 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
313 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
314 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
315 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
316 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
317 ReplaceRotateWithRor(op, ushr, shl);
318 return true;
319 }
320 return false;
321}
322
323// Replace code looking like (x >>> -d OP x << d):
324// Neg neg, d
325// UShr dst, x, neg
326// Shl tmp, x, d
327// OP dst, dst, tmp
328// with
329// Neg neg, d
330// Ror dst, x, neg
331// *** OR ***
332// Replace code looking like (x >>> d OP x << -d):
333// UShr dst, x, d
334// Neg neg, d
335// Shl tmp, x, neg
336// OP dst, dst, tmp
337// with
338// Ror dst, x, d
339bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
340 HUShr* ushr,
341 HShl* shl) {
342 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
343 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
344 bool neg_is_left = shl->GetRight()->IsNeg();
345 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
346 // And the shift distance being negated is the distance being shifted the other way.
347 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
348 ReplaceRotateWithRor(op, ushr, shl);
349 }
350 return false;
351}
352
353// Try replacing code looking like (x >>> d OP x << (#bits - d)):
354// UShr dst, x, d
355// Sub ld, #bits, d
356// Shl tmp, x, ld
357// OP dst, dst, tmp
358// with
359// Ror dst, x, d
360// *** OR ***
361// Replace code looking like (x >>> (#bits - d) OP x << d):
362// Sub rd, #bits, d
363// UShr dst, x, rd
364// Shl tmp, x, d
365// OP dst, dst, tmp
366// with
367// Neg neg, d
368// Ror dst, x, neg
369bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
370 HUShr* ushr,
371 HShl* shl) {
372 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
373 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
374 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
375 HInstruction* shl_shift = shl->GetRight();
376 HInstruction* ushr_shift = ushr->GetRight();
377 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
378 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
379 return ReplaceRotateWithRor(op, ushr, shl);
380 }
381 return false;
382}
383
Calin Juravle10e244f2015-01-26 18:54:32 +0000384void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
385 HInstruction* obj = null_check->InputAt(0);
386 if (!obj->CanBeNull()) {
387 null_check->ReplaceWith(obj);
388 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000389 if (stats_ != nullptr) {
390 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
391 }
392 }
393}
394
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100395bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
396 if (!input->CanBeNull()) {
397 return true;
398 }
399
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100400 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
401 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100402 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100403 return true;
404 }
405 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100406
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100407 return false;
408}
409
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100410// Returns whether doing a type test between the class of `object` against `klass` has
411// a statically known outcome. The result of the test is stored in `outcome`.
412static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000413 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
414 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
415 ScopedObjectAccess soa(Thread::Current());
416 if (!obj_rti.IsValid()) {
417 // We run the simplifier before the reference type propagation so type info might not be
418 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100419 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000420 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100421
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100422 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100423 if (!class_rti.IsValid()) {
424 // Happens when the loaded class is unresolved.
425 return false;
426 }
427 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000428 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100429 *outcome = true;
430 return true;
431 } else if (obj_rti.IsExact()) {
432 // The test failed at compile time so will also fail at runtime.
433 *outcome = false;
434 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100435 } else if (!class_rti.IsInterface()
436 && !obj_rti.IsInterface()
437 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100438 // Different type hierarchy. The test will fail.
439 *outcome = false;
440 return true;
441 }
442 return false;
443}
444
445void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
446 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100447 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
448 if (load_class->NeedsAccessCheck()) {
449 // If we need to perform an access check we cannot remove the instruction.
450 return;
451 }
452
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100453 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100454 check_cast->ClearMustDoNullCheck();
455 }
456
457 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000458 check_cast->GetBlock()->RemoveInstruction(check_cast);
459 if (stats_ != nullptr) {
460 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
461 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100462 return;
463 }
464
465 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700466 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100467 if (outcome) {
468 check_cast->GetBlock()->RemoveInstruction(check_cast);
469 if (stats_ != nullptr) {
470 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
471 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700472 if (!load_class->HasUses()) {
473 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
474 // However, here we know that it cannot because the checkcast was successfull, hence
475 // the class was already loaded.
476 load_class->GetBlock()->RemoveInstruction(load_class);
477 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100478 } else {
479 // Don't do anything for exceptional cases for now. Ideally we should remove
480 // all instructions and blocks this instruction dominates.
481 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000482 }
483}
484
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100485void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100486 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100487 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
488 if (load_class->NeedsAccessCheck()) {
489 // If we need to perform an access check we cannot remove the instruction.
490 return;
491 }
492
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100493 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100494 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100495 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100496 instruction->ClearMustDoNullCheck();
497 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100498
499 HGraph* graph = GetGraph();
500 if (object->IsNullConstant()) {
501 instruction->ReplaceWith(graph->GetIntConstant(0));
502 instruction->GetBlock()->RemoveInstruction(instruction);
503 RecordSimplification();
504 return;
505 }
506
507 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700508 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100509 if (outcome && can_be_null) {
510 // Type test will succeed, we just need a null test.
511 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
512 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
513 instruction->ReplaceWith(test);
514 } else {
515 // We've statically determined the result of the instanceof.
516 instruction->ReplaceWith(graph->GetIntConstant(outcome));
517 }
518 RecordSimplification();
519 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700520 if (outcome && !load_class->HasUses()) {
521 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
522 // However, here we know that it cannot because the instanceof check was successfull, hence
523 // the class was already loaded.
524 load_class->GetBlock()->RemoveInstruction(load_class);
525 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100526 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100527}
528
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100529void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
530 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100531 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100532 instruction->ClearValueCanBeNull();
533 }
534}
535
536void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
537 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100538 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100539 instruction->ClearValueCanBeNull();
540 }
541}
542
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000543void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100544 HBasicBlock* block = check->GetBlock();
545 // Currently always keep the suspend check at entry.
546 if (block->IsEntryBlock()) return;
547
548 // Currently always keep suspend checks at loop entry.
549 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
550 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
551 return;
552 }
553
554 // Remove the suspend check that was added at build time for the baseline
555 // compiler.
556 block->RemoveInstruction(check);
557}
558
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000559void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100560 HInstruction* input_const = equal->GetConstantRight();
561 if (input_const != nullptr) {
562 HInstruction* input_value = equal->GetLeastConstantLeft();
563 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
564 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100565 // We are comparing the boolean to a constant which is of type int and can
566 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100567 if (input_const->AsIntConstant()->IsOne()) {
568 // Replace (bool_value == true) with bool_value
569 equal->ReplaceWith(input_value);
570 block->RemoveInstruction(equal);
571 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100572 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500573 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
574 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100575 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100576 } else {
577 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
578 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
579 block->RemoveInstruction(equal);
580 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100581 }
Mark Mendellc4701932015-04-10 13:18:51 -0400582 } else {
583 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100584 }
Mark Mendellc4701932015-04-10 13:18:51 -0400585 } else {
586 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100587 }
588}
589
David Brazdil0d13fee2015-04-17 14:52:19 +0100590void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
591 HInstruction* input_const = not_equal->GetConstantRight();
592 if (input_const != nullptr) {
593 HInstruction* input_value = not_equal->GetLeastConstantLeft();
594 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
595 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100596 // We are comparing the boolean to a constant which is of type int and can
597 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100598 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500599 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
600 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100601 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100602 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100603 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100604 not_equal->ReplaceWith(input_value);
605 block->RemoveInstruction(not_equal);
606 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100607 } else {
608 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
609 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
610 block->RemoveInstruction(not_equal);
611 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100612 }
Mark Mendellc4701932015-04-10 13:18:51 -0400613 } else {
614 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100615 }
Mark Mendellc4701932015-04-10 13:18:51 -0400616 } else {
617 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100618 }
619}
620
621void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000622 HInstruction* input = bool_not->InputAt(0);
623 HInstruction* replace_with = nullptr;
624
625 if (input->IsIntConstant()) {
626 // Replace !(true/false) with false/true.
627 if (input->AsIntConstant()->IsOne()) {
628 replace_with = GetGraph()->GetIntConstant(0);
629 } else {
630 DCHECK(input->AsIntConstant()->IsZero());
631 replace_with = GetGraph()->GetIntConstant(1);
632 }
633 } else if (input->IsBooleanNot()) {
634 // Replace (!(!bool_value)) with bool_value.
635 replace_with = input->InputAt(0);
636 } else if (input->IsCondition() &&
637 // Don't change FP compares. The definition of compares involving
638 // NaNs forces the compares to be done as written by the user.
639 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
640 // Replace condition with its opposite.
641 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
642 }
643
644 if (replace_with != nullptr) {
645 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100646 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000647 RecordSimplification();
648 }
649}
650
651void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
652 HInstruction* replace_with = nullptr;
653 HInstruction* condition = select->GetCondition();
654 HInstruction* true_value = select->GetTrueValue();
655 HInstruction* false_value = select->GetFalseValue();
656
657 if (condition->IsBooleanNot()) {
658 // Change ((!cond) ? x : y) to (cond ? y : x).
659 condition = condition->InputAt(0);
660 std::swap(true_value, false_value);
661 select->ReplaceInput(false_value, 0);
662 select->ReplaceInput(true_value, 1);
663 select->ReplaceInput(condition, 2);
664 RecordSimplification();
665 }
666
667 if (true_value == false_value) {
668 // Replace (cond ? x : x) with (x).
669 replace_with = true_value;
670 } else if (condition->IsIntConstant()) {
671 if (condition->AsIntConstant()->IsOne()) {
672 // Replace (true ? x : y) with (x).
673 replace_with = true_value;
674 } else {
675 // Replace (false ? x : y) with (y).
676 DCHECK(condition->AsIntConstant()->IsZero());
677 replace_with = false_value;
678 }
679 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
680 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
681 // Replace (cond ? true : false) with (cond).
682 replace_with = condition;
683 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
684 // Replace (cond ? false : true) with (!cond).
685 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
686 }
687 }
688
689 if (replace_with != nullptr) {
690 select->ReplaceWith(replace_with);
691 select->GetBlock()->RemoveInstruction(select);
692 RecordSimplification();
693 }
694}
695
696void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
697 HInstruction* condition = instruction->InputAt(0);
698 if (condition->IsBooleanNot()) {
699 // Swap successors if input is negated.
700 instruction->ReplaceInput(condition->InputAt(0), 0);
701 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100702 RecordSimplification();
703 }
704}
705
Mingyao Yang0304e182015-01-30 16:41:29 -0800706void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
707 HInstruction* input = instruction->InputAt(0);
708 // If the array is a NewArray with constant size, replace the array length
709 // with the constant instruction. This helps the bounds check elimination phase.
710 if (input->IsNewArray()) {
711 input = input->InputAt(0);
712 if (input->IsIntConstant()) {
713 instruction->ReplaceWith(input);
714 }
715 }
716}
717
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000718void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000719 HInstruction* value = instruction->GetValue();
720 if (value->GetType() != Primitive::kPrimNot) return;
721
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100722 if (CanEnsureNotNullAt(value, instruction)) {
723 instruction->ClearValueCanBeNull();
724 }
725
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000726 if (value->IsArrayGet()) {
727 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
728 // If the code is just swapping elements in the array, no need for a type check.
729 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100730 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000731 }
732 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100733
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100734 if (value->IsNullConstant()) {
735 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100736 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100737 }
738
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100739 ScopedObjectAccess soa(Thread::Current());
740 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
741 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
742 if (!array_rti.IsValid()) {
743 return;
744 }
745
746 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
747 instruction->ClearNeedsTypeCheck();
748 return;
749 }
750
751 if (array_rti.IsObjectArray()) {
752 if (array_rti.IsExact()) {
753 instruction->ClearNeedsTypeCheck();
754 return;
755 }
756 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100757 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000758}
759
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000760void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
761 if (instruction->GetResultType() == instruction->GetInputType()) {
762 // Remove the instruction if it's converting to the same type.
763 instruction->ReplaceWith(instruction->GetInput());
764 instruction->GetBlock()->RemoveInstruction(instruction);
765 }
766}
767
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000768void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
769 HConstant* input_cst = instruction->GetConstantRight();
770 HInstruction* input_other = instruction->GetLeastConstantLeft();
771 if ((input_cst != nullptr) && input_cst->IsZero()) {
772 // Replace code looking like
773 // ADD dst, src, 0
774 // with
775 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600776 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
777 // `x` is `-0.0`, the former expression yields `0.0`, while the later
778 // yields `-0.0`.
779 if (Primitive::IsIntegralType(instruction->GetType())) {
780 instruction->ReplaceWith(input_other);
781 instruction->GetBlock()->RemoveInstruction(instruction);
782 return;
783 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100784 }
785
786 HInstruction* left = instruction->GetLeft();
787 HInstruction* right = instruction->GetRight();
788 bool left_is_neg = left->IsNeg();
789 bool right_is_neg = right->IsNeg();
790
791 if (left_is_neg && right_is_neg) {
792 if (TryMoveNegOnInputsAfterBinop(instruction)) {
793 return;
794 }
795 }
796
797 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
798 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
799 // Replace code looking like
800 // NEG tmp, b
801 // ADD dst, a, tmp
802 // with
803 // SUB dst, a, b
804 // We do not perform the optimization if the input negation has environment
805 // uses or multiple non-environment uses as it could lead to worse code. In
806 // particular, we do not want the live range of `b` to be extended if we are
807 // not sure the initial 'NEG' instruction can be removed.
808 HInstruction* other = left_is_neg ? right : left;
809 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
810 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
811 RecordSimplification();
812 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000813 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000814 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000815
816 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000817}
818
819void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
820 HConstant* input_cst = instruction->GetConstantRight();
821 HInstruction* input_other = instruction->GetLeastConstantLeft();
822
Vladimir Marko452c1b62015-09-25 14:44:17 +0100823 if (input_cst != nullptr) {
824 int64_t value = Int64FromConstant(input_cst);
825 if (value == -1) {
826 // Replace code looking like
827 // AND dst, src, 0xFFF...FF
828 // with
829 // src
830 instruction->ReplaceWith(input_other);
831 instruction->GetBlock()->RemoveInstruction(instruction);
832 RecordSimplification();
833 return;
834 }
835 // Eliminate And from UShr+And if the And-mask contains all the bits that
836 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
837 // precisely clears the shifted-in sign bits.
838 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
839 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
840 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
841 size_t num_tail_bits_set = CTZ(value + 1);
842 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
843 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
844 instruction->ReplaceWith(input_other);
845 instruction->GetBlock()->RemoveInstruction(instruction);
846 RecordSimplification();
847 return;
848 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
849 input_other->HasOnlyOneNonEnvironmentUse()) {
850 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
851 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
852 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
853 input_other->InputAt(0),
854 input_other->InputAt(1),
855 input_other->GetDexPc());
856 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
857 input_other->GetBlock()->RemoveInstruction(input_other);
858 RecordSimplification();
859 return;
860 }
861 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000862 }
863
864 // We assume that GVN has run before, so we only perform a pointer comparison.
865 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100866 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000867 if (instruction->GetLeft() == instruction->GetRight()) {
868 // Replace code looking like
869 // AND dst, src, src
870 // with
871 // src
872 instruction->ReplaceWith(instruction->GetLeft());
873 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000874 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000875 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000876
877 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000878}
879
Mark Mendellc4701932015-04-10 13:18:51 -0400880void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
881 VisitCondition(condition);
882}
883
884void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
885 VisitCondition(condition);
886}
887
888void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
889 VisitCondition(condition);
890}
891
892void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
893 VisitCondition(condition);
894}
895
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000896// TODO: unsigned comparisons too?
Aart Bike9f37602015-10-09 11:15:55 -0700897
Mark Mendellc4701932015-04-10 13:18:51 -0400898void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayd4aee942016-01-22 12:35:26 +0000899 // Try to fold an HCompare into this HCondition.
Mark Mendellc4701932015-04-10 13:18:51 -0400900
Mark Mendellc4701932015-04-10 13:18:51 -0400901 HInstruction* left = condition->GetLeft();
902 HInstruction* right = condition->GetRight();
903 // We can only replace an HCondition which compares a Compare to 0.
904 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
905 // condition with a long, float or double comparison as input.
906 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
907 // Conversion is not possible.
908 return;
909 }
910
911 // Is the Compare only used for this purpose?
912 if (!left->GetUses().HasOnlyOneUse()) {
913 // Someone else also wants the result of the compare.
914 return;
915 }
916
917 if (!left->GetEnvUses().IsEmpty()) {
918 // There is a reference to the compare result in an environment. Do we really need it?
919 if (GetGraph()->IsDebuggable()) {
920 return;
921 }
922
923 // We have to ensure that there are no deopt points in the sequence.
924 if (left->HasAnyEnvironmentUseBefore(condition)) {
925 return;
926 }
927 }
928
929 // Clean up any environment uses from the HCompare, if any.
930 left->RemoveEnvironmentUsers();
931
932 // We have decided to fold the HCompare into the HCondition. Transfer the information.
933 condition->SetBias(left->AsCompare()->GetBias());
934
935 // Replace the operands of the HCondition.
936 condition->ReplaceInput(left->InputAt(0), 0);
937 condition->ReplaceInput(left->InputAt(1), 1);
938
939 // Remove the HCompare.
940 left->GetBlock()->RemoveInstruction(left);
941
942 RecordSimplification();
943}
944
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000945void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
946 HConstant* input_cst = instruction->GetConstantRight();
947 HInstruction* input_other = instruction->GetLeastConstantLeft();
948 Primitive::Type type = instruction->GetType();
949
950 if ((input_cst != nullptr) && input_cst->IsOne()) {
951 // Replace code looking like
952 // DIV dst, src, 1
953 // with
954 // src
955 instruction->ReplaceWith(input_other);
956 instruction->GetBlock()->RemoveInstruction(instruction);
957 return;
958 }
959
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000960 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000961 // Replace code looking like
962 // DIV dst, src, -1
963 // with
964 // NEG dst, src
965 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000966 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100967 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000968 return;
969 }
970
971 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
972 // Try replacing code looking like
973 // DIV dst, src, constant
974 // with
975 // MUL dst, src, 1 / constant
976 HConstant* reciprocal = nullptr;
977 if (type == Primitive::Primitive::kPrimDouble) {
978 double value = input_cst->AsDoubleConstant()->GetValue();
979 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
980 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
981 }
982 } else {
983 DCHECK_EQ(type, Primitive::kPrimFloat);
984 float value = input_cst->AsFloatConstant()->GetValue();
985 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
986 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
987 }
988 }
989
990 if (reciprocal != nullptr) {
991 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
992 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
993 RecordSimplification();
994 return;
995 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000996 }
997}
998
999void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1000 HConstant* input_cst = instruction->GetConstantRight();
1001 HInstruction* input_other = instruction->GetLeastConstantLeft();
1002 Primitive::Type type = instruction->GetType();
1003 HBasicBlock* block = instruction->GetBlock();
1004 ArenaAllocator* allocator = GetGraph()->GetArena();
1005
1006 if (input_cst == nullptr) {
1007 return;
1008 }
1009
1010 if (input_cst->IsOne()) {
1011 // Replace code looking like
1012 // MUL dst, src, 1
1013 // with
1014 // src
1015 instruction->ReplaceWith(input_other);
1016 instruction->GetBlock()->RemoveInstruction(instruction);
1017 return;
1018 }
1019
1020 if (input_cst->IsMinusOne() &&
1021 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1022 // Replace code looking like
1023 // MUL dst, src, -1
1024 // with
1025 // NEG dst, src
1026 HNeg* neg = new (allocator) HNeg(type, input_other);
1027 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001028 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001029 return;
1030 }
1031
1032 if (Primitive::IsFloatingPointType(type) &&
1033 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1034 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1035 // Replace code looking like
1036 // FP_MUL dst, src, 2.0
1037 // with
1038 // FP_ADD dst, src, src
1039 // The 'int' and 'long' cases are handled below.
1040 block->ReplaceAndRemoveInstructionWith(instruction,
1041 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001042 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001043 return;
1044 }
1045
1046 if (Primitive::IsIntOrLongType(type)) {
1047 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001048 // Even though constant propagation also takes care of the zero case, other
1049 // optimizations can lead to having a zero multiplication.
1050 if (factor == 0) {
1051 // Replace code looking like
1052 // MUL dst, src, 0
1053 // with
1054 // 0
1055 instruction->ReplaceWith(input_cst);
1056 instruction->GetBlock()->RemoveInstruction(instruction);
1057 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001058 // Replace code looking like
1059 // MUL dst, src, pow_of_2
1060 // with
1061 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001062 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001063 HShl* shl = new(allocator) HShl(type, input_other, shift);
1064 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001065 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001066 } else if (IsPowerOfTwo(factor - 1)) {
1067 // Transform code looking like
1068 // MUL dst, src, (2^n + 1)
1069 // into
1070 // SHL tmp, src, n
1071 // ADD dst, src, tmp
1072 HShl* shl = new (allocator) HShl(type,
1073 input_other,
1074 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1075 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1076
1077 block->InsertInstructionBefore(shl, instruction);
1078 block->ReplaceAndRemoveInstructionWith(instruction, add);
1079 RecordSimplification();
1080 } else if (IsPowerOfTwo(factor + 1)) {
1081 // Transform code looking like
1082 // MUL dst, src, (2^n - 1)
1083 // into
1084 // SHL tmp, src, n
1085 // SUB dst, tmp, src
1086 HShl* shl = new (allocator) HShl(type,
1087 input_other,
1088 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1089 HSub* sub = new (allocator) HSub(type, shl, input_other);
1090
1091 block->InsertInstructionBefore(shl, instruction);
1092 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1093 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001094 }
1095 }
1096}
1097
Alexandre Rames188d4312015-04-09 18:30:21 +01001098void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1099 HInstruction* input = instruction->GetInput();
1100 if (input->IsNeg()) {
1101 // Replace code looking like
1102 // NEG tmp, src
1103 // NEG dst, tmp
1104 // with
1105 // src
1106 HNeg* previous_neg = input->AsNeg();
1107 instruction->ReplaceWith(previous_neg->GetInput());
1108 instruction->GetBlock()->RemoveInstruction(instruction);
1109 // We perform the optimization even if the input negation has environment
1110 // uses since it allows removing the current instruction. But we only delete
1111 // the input negation only if it is does not have any uses left.
1112 if (!previous_neg->HasUses()) {
1113 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1114 }
1115 RecordSimplification();
1116 return;
1117 }
1118
Serguei Katkov339dfc22015-04-20 12:29:32 +06001119 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1120 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001121 // Replace code looking like
1122 // SUB tmp, a, b
1123 // NEG dst, tmp
1124 // with
1125 // SUB dst, b, a
1126 // We do not perform the optimization if the input subtraction has
1127 // environment uses or multiple non-environment uses as it could lead to
1128 // worse code. In particular, we do not want the live ranges of `a` and `b`
1129 // to be extended if we are not sure the initial 'SUB' instruction can be
1130 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001131 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001132 HSub* sub = input->AsSub();
1133 HSub* new_sub =
1134 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1135 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1136 if (!sub->HasUses()) {
1137 sub->GetBlock()->RemoveInstruction(sub);
1138 }
1139 RecordSimplification();
1140 }
1141}
1142
1143void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1144 HInstruction* input = instruction->GetInput();
1145 if (input->IsNot()) {
1146 // Replace code looking like
1147 // NOT tmp, src
1148 // NOT dst, tmp
1149 // with
1150 // src
1151 // We perform the optimization even if the input negation has environment
1152 // uses since it allows removing the current instruction. But we only delete
1153 // the input negation only if it is does not have any uses left.
1154 HNot* previous_not = input->AsNot();
1155 instruction->ReplaceWith(previous_not->GetInput());
1156 instruction->GetBlock()->RemoveInstruction(instruction);
1157 if (!previous_not->HasUses()) {
1158 previous_not->GetBlock()->RemoveInstruction(previous_not);
1159 }
1160 RecordSimplification();
1161 }
1162}
1163
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001164void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1165 HConstant* input_cst = instruction->GetConstantRight();
1166 HInstruction* input_other = instruction->GetLeastConstantLeft();
1167
1168 if ((input_cst != nullptr) && input_cst->IsZero()) {
1169 // Replace code looking like
1170 // OR dst, src, 0
1171 // with
1172 // src
1173 instruction->ReplaceWith(input_other);
1174 instruction->GetBlock()->RemoveInstruction(instruction);
1175 return;
1176 }
1177
1178 // We assume that GVN has run before, so we only perform a pointer comparison.
1179 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001180 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001181 if (instruction->GetLeft() == instruction->GetRight()) {
1182 // Replace code looking like
1183 // OR dst, src, src
1184 // with
1185 // src
1186 instruction->ReplaceWith(instruction->GetLeft());
1187 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001188 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001189 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001190
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001191 if (TryDeMorganNegationFactoring(instruction)) return;
1192
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001193 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001194}
1195
1196void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1197 VisitShift(instruction);
1198}
1199
1200void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1201 VisitShift(instruction);
1202}
1203
1204void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1205 HConstant* input_cst = instruction->GetConstantRight();
1206 HInstruction* input_other = instruction->GetLeastConstantLeft();
1207
Serguei Katkov115b53f2015-08-05 17:03:30 +06001208 Primitive::Type type = instruction->GetType();
1209 if (Primitive::IsFloatingPointType(type)) {
1210 return;
1211 }
1212
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001213 if ((input_cst != nullptr) && input_cst->IsZero()) {
1214 // Replace code looking like
1215 // SUB dst, src, 0
1216 // with
1217 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001218 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1219 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1220 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001221 instruction->ReplaceWith(input_other);
1222 instruction->GetBlock()->RemoveInstruction(instruction);
1223 return;
1224 }
1225
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001226 HBasicBlock* block = instruction->GetBlock();
1227 ArenaAllocator* allocator = GetGraph()->GetArena();
1228
Alexandre Rames188d4312015-04-09 18:30:21 +01001229 HInstruction* left = instruction->GetLeft();
1230 HInstruction* right = instruction->GetRight();
1231 if (left->IsConstant()) {
1232 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001233 // Replace code looking like
1234 // SUB dst, 0, src
1235 // with
1236 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001237 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001238 // `x` is `0.0`, the former expression yields `0.0`, while the later
1239 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001240 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001241 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001242 RecordSimplification();
1243 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001244 }
1245 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001246
1247 if (left->IsNeg() && right->IsNeg()) {
1248 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1249 return;
1250 }
1251 }
1252
1253 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1254 // Replace code looking like
1255 // NEG tmp, b
1256 // SUB dst, a, tmp
1257 // with
1258 // ADD dst, a, b
1259 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1260 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1261 RecordSimplification();
1262 right->GetBlock()->RemoveInstruction(right);
1263 return;
1264 }
1265
1266 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1267 // Replace code looking like
1268 // NEG tmp, a
1269 // SUB dst, tmp, b
1270 // with
1271 // ADD tmp, a, b
1272 // NEG dst, tmp
1273 // The second version is not intrinsically better, but enables more
1274 // transformations.
1275 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1276 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1277 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1278 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1279 instruction->ReplaceWith(neg);
1280 instruction->GetBlock()->RemoveInstruction(instruction);
1281 RecordSimplification();
1282 left->GetBlock()->RemoveInstruction(left);
1283 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001284}
1285
1286void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1287 VisitShift(instruction);
1288}
1289
1290void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1291 HConstant* input_cst = instruction->GetConstantRight();
1292 HInstruction* input_other = instruction->GetLeastConstantLeft();
1293
1294 if ((input_cst != nullptr) && input_cst->IsZero()) {
1295 // Replace code looking like
1296 // XOR dst, src, 0
1297 // with
1298 // src
1299 instruction->ReplaceWith(input_other);
1300 instruction->GetBlock()->RemoveInstruction(instruction);
1301 return;
1302 }
1303
1304 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1305 // Replace code looking like
1306 // XOR dst, src, 0xFFF...FF
1307 // with
1308 // NOT dst, src
1309 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1310 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001311 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001312 return;
1313 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001314
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001315 HInstruction* left = instruction->GetLeft();
1316 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001317 if (((left->IsNot() && right->IsNot()) ||
1318 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001319 left->HasOnlyOneNonEnvironmentUse() &&
1320 right->HasOnlyOneNonEnvironmentUse()) {
1321 // Replace code looking like
1322 // NOT nota, a
1323 // NOT notb, b
1324 // XOR dst, nota, notb
1325 // with
1326 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001327 instruction->ReplaceInput(left->InputAt(0), 0);
1328 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001329 left->GetBlock()->RemoveInstruction(left);
1330 right->GetBlock()->RemoveInstruction(right);
1331 RecordSimplification();
1332 return;
1333 }
1334
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001335 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001336}
1337
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001338void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1339 HInstruction* argument = instruction->InputAt(1);
1340 HInstruction* receiver = instruction->InputAt(0);
1341 if (receiver == argument) {
1342 // Because String.equals is an instance call, the receiver is
1343 // a null check if we don't know it's null. The argument however, will
1344 // be the actual object. So we cannot end up in a situation where both
1345 // are equal but could be null.
1346 DCHECK(CanEnsureNotNullAt(argument, instruction));
1347 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1348 instruction->GetBlock()->RemoveInstruction(instruction);
1349 } else {
1350 StringEqualsOptimizations optimizations(instruction);
1351 if (CanEnsureNotNullAt(argument, instruction)) {
1352 optimizations.SetArgumentNotNull();
1353 }
1354 ScopedObjectAccess soa(Thread::Current());
1355 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1356 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1357 optimizations.SetArgumentIsString();
1358 }
1359 }
1360}
1361
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001362void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1363 DCHECK(invoke->IsInvokeStaticOrDirect());
1364 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001365 HInstruction* value = invoke->InputAt(0);
1366 HInstruction* distance = invoke->InputAt(1);
1367 // Replace the invoke with an HRor.
1368 if (is_left) {
1369 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1370 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1371 }
1372 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1373 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1374 // Remove ClinitCheck and LoadClass, if possible.
1375 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1376 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1377 clinit->GetBlock()->RemoveInstruction(clinit);
1378 HInstruction* ldclass = clinit->InputAt(0);
1379 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1380 ldclass->GetBlock()->RemoveInstruction(ldclass);
1381 }
1382 }
1383}
1384
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001385static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1386 if (potential_length->IsArrayLength()) {
1387 return potential_length->InputAt(0) == potential_array;
1388 }
1389
1390 if (potential_array->IsNewArray()) {
1391 return potential_array->InputAt(0) == potential_length;
1392 }
1393
1394 return false;
1395}
1396
1397void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1398 HInstruction* source = instruction->InputAt(0);
1399 HInstruction* destination = instruction->InputAt(2);
1400 HInstruction* count = instruction->InputAt(4);
1401 SystemArrayCopyOptimizations optimizations(instruction);
1402 if (CanEnsureNotNullAt(source, instruction)) {
1403 optimizations.SetSourceIsNotNull();
1404 }
1405 if (CanEnsureNotNullAt(destination, instruction)) {
1406 optimizations.SetDestinationIsNotNull();
1407 }
1408 if (destination == source) {
1409 optimizations.SetDestinationIsSource();
1410 }
1411
1412 if (IsArrayLengthOf(count, source)) {
1413 optimizations.SetCountIsSourceLength();
1414 }
1415
1416 if (IsArrayLengthOf(count, destination)) {
1417 optimizations.SetCountIsDestinationLength();
1418 }
1419
1420 {
1421 ScopedObjectAccess soa(Thread::Current());
1422 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1423 if (destination_rti.IsValid()) {
1424 if (destination_rti.IsObjectArray()) {
1425 if (destination_rti.IsExact()) {
1426 optimizations.SetDoesNotNeedTypeCheck();
1427 }
1428 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001429 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001430 if (destination_rti.IsPrimitiveArrayClass()) {
1431 optimizations.SetDestinationIsPrimitiveArray();
1432 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1433 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001434 }
1435 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001436 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1437 if (source_rti.IsValid()) {
1438 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1439 optimizations.SetDoesNotNeedTypeCheck();
1440 }
1441 if (source_rti.IsPrimitiveArrayClass()) {
1442 optimizations.SetSourceIsPrimitiveArray();
1443 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1444 optimizations.SetSourceIsNonPrimitiveArray();
1445 }
1446 }
1447 }
1448}
1449
Aart Bika19616e2016-02-01 18:57:58 -08001450void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1451 DCHECK(invoke->IsInvokeStaticOrDirect());
1452 uint32_t dex_pc = invoke->GetDexPc();
1453 HInstruction* left = invoke->InputAt(0);
1454 HInstruction* right;
1455 Primitive::Type type = left->GetType();
1456 if (!is_signum) {
1457 right = invoke->InputAt(1);
1458 } else if (type == Primitive::kPrimLong) {
1459 right = GetGraph()->GetLongConstant(0);
1460 } else {
1461 right = GetGraph()->GetIntConstant(0);
1462 }
1463 HCompare* compare = new (GetGraph()->GetArena())
1464 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1465 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1466}
1467
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001468void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1469 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1470 SimplifyStringEquals(instruction);
1471 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1472 SimplifySystemArrayCopy(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001473 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerRotateRight ||
1474 instruction->GetIntrinsic() == Intrinsics::kLongRotateRight) {
1475 SimplifyRotate(instruction, false);
1476 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerRotateLeft ||
1477 instruction->GetIntrinsic() == Intrinsics::kLongRotateLeft) {
1478 SimplifyRotate(instruction, true);
Aart Bika19616e2016-02-01 18:57:58 -08001479 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerCompare ||
1480 instruction->GetIntrinsic() == Intrinsics::kLongCompare) {
1481 SimplifyCompare(instruction, /* is_signum */ false);
1482 } else if (instruction->GetIntrinsic() == Intrinsics::kIntegerSignum ||
1483 instruction->GetIntrinsic() == Intrinsics::kLongSignum) {
1484 SimplifyCompare(instruction, /* is_signum */ true);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001485 }
1486}
1487
Aart Bikbb245d12015-10-19 11:05:03 -07001488void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1489 HInstruction* cond = deoptimize->InputAt(0);
1490 if (cond->IsConstant()) {
1491 if (cond->AsIntConstant()->IsZero()) {
1492 // Never deopt: instruction can be removed.
1493 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1494 } else {
1495 // Always deopt.
1496 }
1497 }
1498}
1499
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001500} // namespace art