blob: 062b5a6b81dc170265d7e18b5d479fddadb5bc29 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
Calin Juravle69158982016-03-16 11:53:41 +000037 MaybeRecordStat(kInstructionSimplifications);
38 }
39
40 void MaybeRecordStat(MethodCompilationStat stat) {
41 if (stats_ != nullptr) {
42 stats_->RecordStat(stat);
Alexandre Rames188d4312015-04-09 18:30:21 +010043 }
44 }
45
Scott Wakeling40a04bf2015-12-11 09:50:36 +000046 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
47 bool TryReplaceWithRotate(HBinaryOperation* instruction);
48 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
49 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
50 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51
Alexandre Rames188d4312015-04-09 18:30:21 +010052 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000053 // `op` should be either HOr or HAnd.
54 // De Morgan's laws:
55 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
56 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000057 void VisitShift(HBinaryOperation* shift);
58
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000059 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
60 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010061 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
62 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010063 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
64 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000065 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000066 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000067 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080068 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000069 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000070 void VisitAdd(HAdd* instruction) OVERRIDE;
71 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040072 void VisitCondition(HCondition* instruction) OVERRIDE;
73 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
74 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
75 void VisitLessThan(HLessThan* condition) OVERRIDE;
76 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060077 void VisitBelow(HBelow* condition) OVERRIDE;
78 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
79 void VisitAbove(HAbove* condition) OVERRIDE;
80 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000081 void VisitDiv(HDiv* instruction) OVERRIDE;
82 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010083 void VisitNeg(HNeg* instruction) OVERRIDE;
84 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000085 void VisitOr(HOr* instruction) OVERRIDE;
86 void VisitShl(HShl* instruction) OVERRIDE;
87 void VisitShr(HShr* instruction) OVERRIDE;
88 void VisitSub(HSub* instruction) OVERRIDE;
89 void VisitUShr(HUShr* instruction) OVERRIDE;
90 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000091 void VisitSelect(HSelect* select) OVERRIDE;
92 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010093 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010094 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070095 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010096
97 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000098
Scott Wakeling40a04bf2015-12-11 09:50:36 +000099 void SimplifyRotate(HInvoke* invoke, bool is_left);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100100 void SimplifySystemArrayCopy(HInvoke* invoke);
101 void SimplifyStringEquals(HInvoke* invoke);
Aart Bika19616e2016-02-01 18:57:58 -0800102 void SimplifyCompare(HInvoke* invoke, bool has_zero_op);
Aart Bik75a38b22016-02-17 10:41:50 -0800103 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800104 void SimplifyFP2Int(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800105 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100106
Calin Juravleacf735c2015-02-12 15:25:22 +0000107 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100108 bool simplification_occurred_ = false;
109 int simplifications_at_current_position_ = 0;
110 // We ensure we do not loop infinitely. The value is a finger in the air guess
111 // that should allow enough simplification.
112 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000113};
114
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100115void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000116 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100117 visitor.Run();
118}
119
120void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100121 // Iterate in reverse post order to open up more simplifications to users
122 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
124 // The simplification of an instruction to another instruction may yield
125 // possibilities for other simplifications. So although we perform a reverse
126 // post order visit, we sometimes need to revisit an instruction index.
127 simplification_occurred_ = false;
128 VisitBasicBlock(it.Current());
129 if (simplification_occurred_ &&
130 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
131 // New simplifications may be applicable to the instruction at the
132 // current index, so don't advance the iterator.
133 continue;
134 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100135 simplifications_at_current_position_ = 0;
136 it.Advance();
137 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100138}
139
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000140namespace {
141
142bool AreAllBitsSet(HConstant* constant) {
143 return Int64FromConstant(constant) == -1;
144}
145
146} // namespace
147
Alexandre Rames188d4312015-04-09 18:30:21 +0100148// Returns true if the code was simplified to use only one negation operation
149// after the binary operation instead of one on each of the inputs.
150bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
151 DCHECK(binop->IsAdd() || binop->IsSub());
152 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
153 HNeg* left_neg = binop->GetLeft()->AsNeg();
154 HNeg* right_neg = binop->GetRight()->AsNeg();
155 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
156 !right_neg->HasOnlyOneNonEnvironmentUse()) {
157 return false;
158 }
159 // Replace code looking like
160 // NEG tmp1, a
161 // NEG tmp2, b
162 // ADD dst, tmp1, tmp2
163 // with
164 // ADD tmp, a, b
165 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600166 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
167 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
168 // while the later yields `-0.0`.
169 if (!Primitive::IsIntegralType(binop->GetType())) {
170 return false;
171 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100172 binop->ReplaceInput(left_neg->GetInput(), 0);
173 binop->ReplaceInput(right_neg->GetInput(), 1);
174 left_neg->GetBlock()->RemoveInstruction(left_neg);
175 right_neg->GetBlock()->RemoveInstruction(right_neg);
176 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
177 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
178 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
179 RecordSimplification();
180 return true;
181}
182
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000183bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
184 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
185 Primitive::Type type = op->GetType();
186 HInstruction* left = op->GetLeft();
187 HInstruction* right = op->GetRight();
188
189 // We can apply De Morgan's laws if both inputs are Not's and are only used
190 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000191 if (((left->IsNot() && right->IsNot()) ||
192 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000193 left->HasOnlyOneNonEnvironmentUse() &&
194 right->HasOnlyOneNonEnvironmentUse()) {
195 // Replace code looking like
196 // NOT nota, a
197 // NOT notb, b
198 // AND dst, nota, notb (respectively OR)
199 // with
200 // OR or, a, b (respectively AND)
201 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000202 HInstruction* src_left = left->InputAt(0);
203 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000204 uint32_t dex_pc = op->GetDexPc();
205
206 // Remove the negations on the inputs.
207 left->ReplaceWith(src_left);
208 right->ReplaceWith(src_right);
209 left->GetBlock()->RemoveInstruction(left);
210 right->GetBlock()->RemoveInstruction(right);
211
212 // Replace the `HAnd` or `HOr`.
213 HBinaryOperation* hbin;
214 if (op->IsAnd()) {
215 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
216 } else {
217 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
218 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000219 HInstruction* hnot;
220 if (left->IsBooleanNot()) {
221 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
222 } else {
223 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
224 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000225
226 op->GetBlock()->InsertInstructionBefore(hbin, op);
227 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
228
229 RecordSimplification();
230 return true;
231 }
232
233 return false;
234}
235
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000236void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
237 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
238 HConstant* input_cst = instruction->GetConstantRight();
239 HInstruction* input_other = instruction->GetLeastConstantLeft();
240
Mark Mendellba56d062015-05-05 21:34:03 -0400241 if (input_cst != nullptr) {
242 if (input_cst->IsZero()) {
243 // Replace code looking like
244 // SHL dst, src, 0
245 // with
246 // src
247 instruction->ReplaceWith(input_other);
248 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400249 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000250 }
251}
252
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000253static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
254 return (sub->GetRight() == other &&
255 sub->GetLeft()->IsConstant() &&
256 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
257}
258
259bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
260 HUShr* ushr,
261 HShl* shl) {
262 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
263 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
264 ushr->GetLeft(),
265 ushr->GetRight());
266 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
267 if (!ushr->HasUses()) {
268 ushr->GetBlock()->RemoveInstruction(ushr);
269 }
270 if (!ushr->GetRight()->HasUses()) {
271 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
272 }
273 if (!shl->HasUses()) {
274 shl->GetBlock()->RemoveInstruction(shl);
275 }
276 if (!shl->GetRight()->HasUses()) {
277 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
278 }
279 return true;
280}
281
282// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
283bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000284 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
285 HInstruction* left = op->GetLeft();
286 HInstruction* right = op->GetRight();
287 // If we have an UShr and a Shl (in either order).
288 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
289 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
290 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
291 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
292 if (ushr->GetType() == shl->GetType() &&
293 ushr->GetLeft() == shl->GetLeft()) {
294 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
295 // Shift distances are both constant, try replacing with Ror if they
296 // add up to the register size.
297 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
298 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
299 // Shift distances are potentially of the form x and (reg_size - x).
300 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
301 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
302 // Shift distances are potentially of the form d and -d.
303 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
304 }
305 }
306 }
307 return false;
308}
309
310// Try replacing code looking like (x >>> #rdist OP x << #ldist):
311// UShr dst, x, #rdist
312// Shl tmp, x, #ldist
313// OP dst, dst, tmp
314// or like (x >>> #rdist OP x << #-ldist):
315// UShr dst, x, #rdist
316// Shl tmp, x, #-ldist
317// OP dst, dst, tmp
318// with
319// Ror dst, x, #rdist
320bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
321 HUShr* ushr,
322 HShl* shl) {
323 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
324 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
325 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
326 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
327 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
328 ReplaceRotateWithRor(op, ushr, shl);
329 return true;
330 }
331 return false;
332}
333
334// Replace code looking like (x >>> -d OP x << d):
335// Neg neg, d
336// UShr dst, x, neg
337// Shl tmp, x, d
338// OP dst, dst, tmp
339// with
340// Neg neg, d
341// Ror dst, x, neg
342// *** OR ***
343// Replace code looking like (x >>> d OP x << -d):
344// UShr dst, x, d
345// Neg neg, d
346// Shl tmp, x, neg
347// OP dst, dst, tmp
348// with
349// Ror dst, x, d
350bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
351 HUShr* ushr,
352 HShl* shl) {
353 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
354 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
355 bool neg_is_left = shl->GetRight()->IsNeg();
356 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
357 // And the shift distance being negated is the distance being shifted the other way.
358 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
359 ReplaceRotateWithRor(op, ushr, shl);
360 }
361 return false;
362}
363
364// Try replacing code looking like (x >>> d OP x << (#bits - d)):
365// UShr dst, x, d
366// Sub ld, #bits, d
367// Shl tmp, x, ld
368// OP dst, dst, tmp
369// with
370// Ror dst, x, d
371// *** OR ***
372// Replace code looking like (x >>> (#bits - d) OP x << d):
373// Sub rd, #bits, d
374// UShr dst, x, rd
375// Shl tmp, x, d
376// OP dst, dst, tmp
377// with
378// Neg neg, d
379// Ror dst, x, neg
380bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
381 HUShr* ushr,
382 HShl* shl) {
383 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
384 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
385 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
386 HInstruction* shl_shift = shl->GetRight();
387 HInstruction* ushr_shift = ushr->GetRight();
388 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
389 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
390 return ReplaceRotateWithRor(op, ushr, shl);
391 }
392 return false;
393}
394
Calin Juravle10e244f2015-01-26 18:54:32 +0000395void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
396 HInstruction* obj = null_check->InputAt(0);
397 if (!obj->CanBeNull()) {
398 null_check->ReplaceWith(obj);
399 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000400 if (stats_ != nullptr) {
401 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
402 }
403 }
404}
405
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100406bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
407 if (!input->CanBeNull()) {
408 return true;
409 }
410
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100411 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
412 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100413 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100414 return true;
415 }
416 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100417
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100418 return false;
419}
420
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100421// Returns whether doing a type test between the class of `object` against `klass` has
422// a statically known outcome. The result of the test is stored in `outcome`.
423static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000424 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
425 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
426 ScopedObjectAccess soa(Thread::Current());
427 if (!obj_rti.IsValid()) {
428 // We run the simplifier before the reference type propagation so type info might not be
429 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100430 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000431 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100432
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100433 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100434 if (!class_rti.IsValid()) {
435 // Happens when the loaded class is unresolved.
436 return false;
437 }
438 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000439 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100440 *outcome = true;
441 return true;
442 } else if (obj_rti.IsExact()) {
443 // The test failed at compile time so will also fail at runtime.
444 *outcome = false;
445 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100446 } else if (!class_rti.IsInterface()
447 && !obj_rti.IsInterface()
448 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100449 // Different type hierarchy. The test will fail.
450 *outcome = false;
451 return true;
452 }
453 return false;
454}
455
456void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
457 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100458 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
459 if (load_class->NeedsAccessCheck()) {
460 // If we need to perform an access check we cannot remove the instruction.
461 return;
462 }
463
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100464 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100465 check_cast->ClearMustDoNullCheck();
466 }
467
468 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000469 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000470 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100471 return;
472 }
473
474 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700475 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100476 if (outcome) {
477 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000478 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700479 if (!load_class->HasUses()) {
480 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
481 // However, here we know that it cannot because the checkcast was successfull, hence
482 // the class was already loaded.
483 load_class->GetBlock()->RemoveInstruction(load_class);
484 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100485 } else {
486 // Don't do anything for exceptional cases for now. Ideally we should remove
487 // all instructions and blocks this instruction dominates.
488 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000489 }
490}
491
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100492void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100493 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100494 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
495 if (load_class->NeedsAccessCheck()) {
496 // If we need to perform an access check we cannot remove the instruction.
497 return;
498 }
499
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100500 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100501 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100502 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100503 instruction->ClearMustDoNullCheck();
504 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100505
506 HGraph* graph = GetGraph();
507 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000508 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100509 instruction->ReplaceWith(graph->GetIntConstant(0));
510 instruction->GetBlock()->RemoveInstruction(instruction);
511 RecordSimplification();
512 return;
513 }
514
515 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700516 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000517 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100518 if (outcome && can_be_null) {
519 // Type test will succeed, we just need a null test.
520 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
521 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
522 instruction->ReplaceWith(test);
523 } else {
524 // We've statically determined the result of the instanceof.
525 instruction->ReplaceWith(graph->GetIntConstant(outcome));
526 }
527 RecordSimplification();
528 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700529 if (outcome && !load_class->HasUses()) {
530 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
531 // However, here we know that it cannot because the instanceof check was successfull, hence
532 // the class was already loaded.
533 load_class->GetBlock()->RemoveInstruction(load_class);
534 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100535 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100536}
537
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100538void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
539 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100540 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100541 instruction->ClearValueCanBeNull();
542 }
543}
544
545void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
546 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100547 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100548 instruction->ClearValueCanBeNull();
549 }
550}
551
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000552void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100553 HBasicBlock* block = check->GetBlock();
554 // Currently always keep the suspend check at entry.
555 if (block->IsEntryBlock()) return;
556
557 // Currently always keep suspend checks at loop entry.
558 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
559 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
560 return;
561 }
562
563 // Remove the suspend check that was added at build time for the baseline
564 // compiler.
565 block->RemoveInstruction(check);
566}
567
Anton Shaminbdd79352016-02-15 12:48:36 +0600568static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
569 HInstruction *lhs = cond->InputAt(0);
570 HInstruction *rhs = cond->InputAt(1);
571 switch (cond->GetKind()) {
572 case HInstruction::kEqual:
573 return new (arena) HEqual(rhs, lhs);
574 case HInstruction::kNotEqual:
575 return new (arena) HNotEqual(rhs, lhs);
576 case HInstruction::kLessThan:
577 return new (arena) HGreaterThan(rhs, lhs);
578 case HInstruction::kLessThanOrEqual:
579 return new (arena) HGreaterThanOrEqual(rhs, lhs);
580 case HInstruction::kGreaterThan:
581 return new (arena) HLessThan(rhs, lhs);
582 case HInstruction::kGreaterThanOrEqual:
583 return new (arena) HLessThanOrEqual(rhs, lhs);
584 case HInstruction::kBelow:
585 return new (arena) HAbove(rhs, lhs);
586 case HInstruction::kBelowOrEqual:
587 return new (arena) HAboveOrEqual(rhs, lhs);
588 case HInstruction::kAbove:
589 return new (arena) HBelow(rhs, lhs);
590 case HInstruction::kAboveOrEqual:
591 return new (arena) HBelowOrEqual(rhs, lhs);
592 default:
593 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
594 }
595 return nullptr;
596}
597
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000598void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100599 HInstruction* input_const = equal->GetConstantRight();
600 if (input_const != nullptr) {
601 HInstruction* input_value = equal->GetLeastConstantLeft();
602 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
603 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100604 // We are comparing the boolean to a constant which is of type int and can
605 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100606 if (input_const->AsIntConstant()->IsOne()) {
607 // Replace (bool_value == true) with bool_value
608 equal->ReplaceWith(input_value);
609 block->RemoveInstruction(equal);
610 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100611 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500612 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
613 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100614 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100615 } else {
616 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
617 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
618 block->RemoveInstruction(equal);
619 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100620 }
Mark Mendellc4701932015-04-10 13:18:51 -0400621 } else {
622 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100623 }
Mark Mendellc4701932015-04-10 13:18:51 -0400624 } else {
625 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100626 }
627}
628
David Brazdil0d13fee2015-04-17 14:52:19 +0100629void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
630 HInstruction* input_const = not_equal->GetConstantRight();
631 if (input_const != nullptr) {
632 HInstruction* input_value = not_equal->GetLeastConstantLeft();
633 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
634 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100635 // We are comparing the boolean to a constant which is of type int and can
636 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100637 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500638 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
639 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100640 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100641 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100642 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100643 not_equal->ReplaceWith(input_value);
644 block->RemoveInstruction(not_equal);
645 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100646 } else {
647 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
648 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
649 block->RemoveInstruction(not_equal);
650 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100651 }
Mark Mendellc4701932015-04-10 13:18:51 -0400652 } else {
653 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100654 }
Mark Mendellc4701932015-04-10 13:18:51 -0400655 } else {
656 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100657 }
658}
659
660void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000661 HInstruction* input = bool_not->InputAt(0);
662 HInstruction* replace_with = nullptr;
663
664 if (input->IsIntConstant()) {
665 // Replace !(true/false) with false/true.
666 if (input->AsIntConstant()->IsOne()) {
667 replace_with = GetGraph()->GetIntConstant(0);
668 } else {
669 DCHECK(input->AsIntConstant()->IsZero());
670 replace_with = GetGraph()->GetIntConstant(1);
671 }
672 } else if (input->IsBooleanNot()) {
673 // Replace (!(!bool_value)) with bool_value.
674 replace_with = input->InputAt(0);
675 } else if (input->IsCondition() &&
676 // Don't change FP compares. The definition of compares involving
677 // NaNs forces the compares to be done as written by the user.
678 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
679 // Replace condition with its opposite.
680 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
681 }
682
683 if (replace_with != nullptr) {
684 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100685 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000686 RecordSimplification();
687 }
688}
689
690void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
691 HInstruction* replace_with = nullptr;
692 HInstruction* condition = select->GetCondition();
693 HInstruction* true_value = select->GetTrueValue();
694 HInstruction* false_value = select->GetFalseValue();
695
696 if (condition->IsBooleanNot()) {
697 // Change ((!cond) ? x : y) to (cond ? y : x).
698 condition = condition->InputAt(0);
699 std::swap(true_value, false_value);
700 select->ReplaceInput(false_value, 0);
701 select->ReplaceInput(true_value, 1);
702 select->ReplaceInput(condition, 2);
703 RecordSimplification();
704 }
705
706 if (true_value == false_value) {
707 // Replace (cond ? x : x) with (x).
708 replace_with = true_value;
709 } else if (condition->IsIntConstant()) {
710 if (condition->AsIntConstant()->IsOne()) {
711 // Replace (true ? x : y) with (x).
712 replace_with = true_value;
713 } else {
714 // Replace (false ? x : y) with (y).
715 DCHECK(condition->AsIntConstant()->IsZero());
716 replace_with = false_value;
717 }
718 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
719 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
720 // Replace (cond ? true : false) with (cond).
721 replace_with = condition;
722 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
723 // Replace (cond ? false : true) with (!cond).
724 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
725 }
726 }
727
728 if (replace_with != nullptr) {
729 select->ReplaceWith(replace_with);
730 select->GetBlock()->RemoveInstruction(select);
731 RecordSimplification();
732 }
733}
734
735void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
736 HInstruction* condition = instruction->InputAt(0);
737 if (condition->IsBooleanNot()) {
738 // Swap successors if input is negated.
739 instruction->ReplaceInput(condition->InputAt(0), 0);
740 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100741 RecordSimplification();
742 }
743}
744
Mingyao Yang0304e182015-01-30 16:41:29 -0800745void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
746 HInstruction* input = instruction->InputAt(0);
747 // If the array is a NewArray with constant size, replace the array length
748 // with the constant instruction. This helps the bounds check elimination phase.
749 if (input->IsNewArray()) {
750 input = input->InputAt(0);
751 if (input->IsIntConstant()) {
752 instruction->ReplaceWith(input);
753 }
754 }
755}
756
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000757void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000758 HInstruction* value = instruction->GetValue();
759 if (value->GetType() != Primitive::kPrimNot) return;
760
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100761 if (CanEnsureNotNullAt(value, instruction)) {
762 instruction->ClearValueCanBeNull();
763 }
764
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000765 if (value->IsArrayGet()) {
766 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
767 // If the code is just swapping elements in the array, no need for a type check.
768 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100769 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000770 }
771 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100772
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100773 if (value->IsNullConstant()) {
774 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100775 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100776 }
777
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100778 ScopedObjectAccess soa(Thread::Current());
779 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
780 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
781 if (!array_rti.IsValid()) {
782 return;
783 }
784
785 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
786 instruction->ClearNeedsTypeCheck();
787 return;
788 }
789
790 if (array_rti.IsObjectArray()) {
791 if (array_rti.IsExact()) {
792 instruction->ClearNeedsTypeCheck();
793 return;
794 }
795 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100796 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000797}
798
Vladimir Markob52bbde2016-02-12 12:06:05 +0000799static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
800 // Besides conversion to the same type, widening integral conversions are implicit,
801 // excluding conversions to long and the byte->char conversion where we need to
802 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
803 return result_type == input_type ||
804 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
805 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
806 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
807 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
808}
809
810static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
811 // The conversion to a larger type is loss-less with the exception of two cases,
812 // - conversion to char, the only unsigned type, where we may lose some bits, and
813 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
814 // For integral to FP conversions this holds because the FP mantissa is large enough.
815 DCHECK_NE(input_type, result_type);
816 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
817 result_type != Primitive::kPrimChar &&
818 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
819}
820
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000821void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000822 HInstruction* input = instruction->GetInput();
823 Primitive::Type input_type = input->GetType();
824 Primitive::Type result_type = instruction->GetResultType();
825 if (IsTypeConversionImplicit(input_type, result_type)) {
826 // Remove the implicit conversion; this includes conversion to the same type.
827 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000828 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000829 RecordSimplification();
830 return;
831 }
832
833 if (input->IsTypeConversion()) {
834 HTypeConversion* input_conversion = input->AsTypeConversion();
835 HInstruction* original_input = input_conversion->GetInput();
836 Primitive::Type original_type = original_input->GetType();
837
838 // When the first conversion is lossless, a direct conversion from the original type
839 // to the final type yields the same result, even for a lossy second conversion, for
840 // example float->double->int or int->double->float.
841 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
842
843 // For integral conversions, see if the first conversion loses only bits that the second
844 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
845 // conversion yields the same result, for example long->int->short or int->char->short.
846 bool integral_conversions_with_non_widening_second =
847 Primitive::IsIntegralType(input_type) &&
848 Primitive::IsIntegralType(original_type) &&
849 Primitive::IsIntegralType(result_type) &&
850 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
851
852 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
853 // If the merged conversion is implicit, do the simplification unconditionally.
854 if (IsTypeConversionImplicit(original_type, result_type)) {
855 instruction->ReplaceWith(original_input);
856 instruction->GetBlock()->RemoveInstruction(instruction);
857 if (!input_conversion->HasUses()) {
858 // Don't wait for DCE.
859 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
860 }
861 RecordSimplification();
862 return;
863 }
864 // Otherwise simplify only if the first conversion has no other use.
865 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
866 input_conversion->ReplaceWith(original_input);
867 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
868 RecordSimplification();
869 return;
870 }
871 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000872 } else if (input->IsAnd() &&
873 Primitive::IsIntegralType(result_type) &&
874 input->HasOnlyOneNonEnvironmentUse()) {
875 DCHECK(Primitive::IsIntegralType(input_type));
876 HAnd* input_and = input->AsAnd();
877 HConstant* constant = input_and->GetConstantRight();
878 if (constant != nullptr) {
879 int64_t value = Int64FromConstant(constant);
880 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
881 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
882 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
883 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
884 input_and->ReplaceWith(input_and->GetLeastConstantLeft());
885 input_and->GetBlock()->RemoveInstruction(input_and);
886 RecordSimplification();
887 return;
888 }
889 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000890 }
891}
892
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000893void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
894 HConstant* input_cst = instruction->GetConstantRight();
895 HInstruction* input_other = instruction->GetLeastConstantLeft();
896 if ((input_cst != nullptr) && input_cst->IsZero()) {
897 // Replace code looking like
898 // ADD dst, src, 0
899 // with
900 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600901 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
902 // `x` is `-0.0`, the former expression yields `0.0`, while the later
903 // yields `-0.0`.
904 if (Primitive::IsIntegralType(instruction->GetType())) {
905 instruction->ReplaceWith(input_other);
906 instruction->GetBlock()->RemoveInstruction(instruction);
907 return;
908 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100909 }
910
911 HInstruction* left = instruction->GetLeft();
912 HInstruction* right = instruction->GetRight();
913 bool left_is_neg = left->IsNeg();
914 bool right_is_neg = right->IsNeg();
915
916 if (left_is_neg && right_is_neg) {
917 if (TryMoveNegOnInputsAfterBinop(instruction)) {
918 return;
919 }
920 }
921
922 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
923 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
924 // Replace code looking like
925 // NEG tmp, b
926 // ADD dst, a, tmp
927 // with
928 // SUB dst, a, b
929 // We do not perform the optimization if the input negation has environment
930 // uses or multiple non-environment uses as it could lead to worse code. In
931 // particular, we do not want the live range of `b` to be extended if we are
932 // not sure the initial 'NEG' instruction can be removed.
933 HInstruction* other = left_is_neg ? right : left;
934 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
935 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
936 RecordSimplification();
937 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000938 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000939 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000940
941 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000942}
943
944void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
945 HConstant* input_cst = instruction->GetConstantRight();
946 HInstruction* input_other = instruction->GetLeastConstantLeft();
947
Vladimir Marko452c1b62015-09-25 14:44:17 +0100948 if (input_cst != nullptr) {
949 int64_t value = Int64FromConstant(input_cst);
950 if (value == -1) {
951 // Replace code looking like
952 // AND dst, src, 0xFFF...FF
953 // with
954 // src
955 instruction->ReplaceWith(input_other);
956 instruction->GetBlock()->RemoveInstruction(instruction);
957 RecordSimplification();
958 return;
959 }
960 // Eliminate And from UShr+And if the And-mask contains all the bits that
961 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
962 // precisely clears the shifted-in sign bits.
963 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
964 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
965 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
966 size_t num_tail_bits_set = CTZ(value + 1);
967 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
968 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
969 instruction->ReplaceWith(input_other);
970 instruction->GetBlock()->RemoveInstruction(instruction);
971 RecordSimplification();
972 return;
973 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
974 input_other->HasOnlyOneNonEnvironmentUse()) {
975 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
976 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
977 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
978 input_other->InputAt(0),
979 input_other->InputAt(1),
980 input_other->GetDexPc());
981 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
982 input_other->GetBlock()->RemoveInstruction(input_other);
983 RecordSimplification();
984 return;
985 }
986 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000987 }
988
989 // We assume that GVN has run before, so we only perform a pointer comparison.
990 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100991 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000992 if (instruction->GetLeft() == instruction->GetRight()) {
993 // Replace code looking like
994 // AND dst, src, src
995 // with
996 // src
997 instruction->ReplaceWith(instruction->GetLeft());
998 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000999 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001000 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001001
1002 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001003}
1004
Mark Mendellc4701932015-04-10 13:18:51 -04001005void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1006 VisitCondition(condition);
1007}
1008
1009void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1010 VisitCondition(condition);
1011}
1012
1013void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1014 VisitCondition(condition);
1015}
1016
1017void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1018 VisitCondition(condition);
1019}
1020
Anton Shaminbdd79352016-02-15 12:48:36 +06001021void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1022 VisitCondition(condition);
1023}
1024
1025void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1026 VisitCondition(condition);
1027}
1028
1029void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1030 VisitCondition(condition);
1031}
1032
1033void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1034 VisitCondition(condition);
1035}
Aart Bike9f37602015-10-09 11:15:55 -07001036
Mark Mendellc4701932015-04-10 13:18:51 -04001037void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001038 // Reverse condition if left is constant. Our code generators prefer constant
1039 // on the right hand side.
1040 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1041 HBasicBlock* block = condition->GetBlock();
1042 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1043 // If it is a fp we must set the opposite bias.
1044 if (replacement != nullptr) {
1045 if (condition->IsLtBias()) {
1046 replacement->SetBias(ComparisonBias::kGtBias);
1047 } else if (condition->IsGtBias()) {
1048 replacement->SetBias(ComparisonBias::kLtBias);
1049 }
1050 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1051 RecordSimplification();
1052
1053 condition = replacement;
1054 }
1055 }
Mark Mendellc4701932015-04-10 13:18:51 -04001056
Mark Mendellc4701932015-04-10 13:18:51 -04001057 HInstruction* left = condition->GetLeft();
1058 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001059
1060 // Try to fold an HCompare into this HCondition.
1061
Mark Mendellc4701932015-04-10 13:18:51 -04001062 // We can only replace an HCondition which compares a Compare to 0.
1063 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1064 // condition with a long, float or double comparison as input.
1065 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1066 // Conversion is not possible.
1067 return;
1068 }
1069
1070 // Is the Compare only used for this purpose?
1071 if (!left->GetUses().HasOnlyOneUse()) {
1072 // Someone else also wants the result of the compare.
1073 return;
1074 }
1075
1076 if (!left->GetEnvUses().IsEmpty()) {
1077 // There is a reference to the compare result in an environment. Do we really need it?
1078 if (GetGraph()->IsDebuggable()) {
1079 return;
1080 }
1081
1082 // We have to ensure that there are no deopt points in the sequence.
1083 if (left->HasAnyEnvironmentUseBefore(condition)) {
1084 return;
1085 }
1086 }
1087
1088 // Clean up any environment uses from the HCompare, if any.
1089 left->RemoveEnvironmentUsers();
1090
1091 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1092 condition->SetBias(left->AsCompare()->GetBias());
1093
1094 // Replace the operands of the HCondition.
1095 condition->ReplaceInput(left->InputAt(0), 0);
1096 condition->ReplaceInput(left->InputAt(1), 1);
1097
1098 // Remove the HCompare.
1099 left->GetBlock()->RemoveInstruction(left);
1100
1101 RecordSimplification();
1102}
1103
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001104void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1105 HConstant* input_cst = instruction->GetConstantRight();
1106 HInstruction* input_other = instruction->GetLeastConstantLeft();
1107 Primitive::Type type = instruction->GetType();
1108
1109 if ((input_cst != nullptr) && input_cst->IsOne()) {
1110 // Replace code looking like
1111 // DIV dst, src, 1
1112 // with
1113 // src
1114 instruction->ReplaceWith(input_other);
1115 instruction->GetBlock()->RemoveInstruction(instruction);
1116 return;
1117 }
1118
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001119 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001120 // Replace code looking like
1121 // DIV dst, src, -1
1122 // with
1123 // NEG dst, src
1124 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001125 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001126 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001127 return;
1128 }
1129
1130 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1131 // Try replacing code looking like
1132 // DIV dst, src, constant
1133 // with
1134 // MUL dst, src, 1 / constant
1135 HConstant* reciprocal = nullptr;
1136 if (type == Primitive::Primitive::kPrimDouble) {
1137 double value = input_cst->AsDoubleConstant()->GetValue();
1138 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1139 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1140 }
1141 } else {
1142 DCHECK_EQ(type, Primitive::kPrimFloat);
1143 float value = input_cst->AsFloatConstant()->GetValue();
1144 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1145 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1146 }
1147 }
1148
1149 if (reciprocal != nullptr) {
1150 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1151 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1152 RecordSimplification();
1153 return;
1154 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001155 }
1156}
1157
1158void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1159 HConstant* input_cst = instruction->GetConstantRight();
1160 HInstruction* input_other = instruction->GetLeastConstantLeft();
1161 Primitive::Type type = instruction->GetType();
1162 HBasicBlock* block = instruction->GetBlock();
1163 ArenaAllocator* allocator = GetGraph()->GetArena();
1164
1165 if (input_cst == nullptr) {
1166 return;
1167 }
1168
1169 if (input_cst->IsOne()) {
1170 // Replace code looking like
1171 // MUL dst, src, 1
1172 // with
1173 // src
1174 instruction->ReplaceWith(input_other);
1175 instruction->GetBlock()->RemoveInstruction(instruction);
1176 return;
1177 }
1178
1179 if (input_cst->IsMinusOne() &&
1180 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1181 // Replace code looking like
1182 // MUL dst, src, -1
1183 // with
1184 // NEG dst, src
1185 HNeg* neg = new (allocator) HNeg(type, input_other);
1186 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001187 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001188 return;
1189 }
1190
1191 if (Primitive::IsFloatingPointType(type) &&
1192 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1193 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1194 // Replace code looking like
1195 // FP_MUL dst, src, 2.0
1196 // with
1197 // FP_ADD dst, src, src
1198 // The 'int' and 'long' cases are handled below.
1199 block->ReplaceAndRemoveInstructionWith(instruction,
1200 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001201 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001202 return;
1203 }
1204
1205 if (Primitive::IsIntOrLongType(type)) {
1206 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001207 // Even though constant propagation also takes care of the zero case, other
1208 // optimizations can lead to having a zero multiplication.
1209 if (factor == 0) {
1210 // Replace code looking like
1211 // MUL dst, src, 0
1212 // with
1213 // 0
1214 instruction->ReplaceWith(input_cst);
1215 instruction->GetBlock()->RemoveInstruction(instruction);
1216 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001217 // Replace code looking like
1218 // MUL dst, src, pow_of_2
1219 // with
1220 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001221 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001222 HShl* shl = new(allocator) HShl(type, input_other, shift);
1223 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001224 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001225 } else if (IsPowerOfTwo(factor - 1)) {
1226 // Transform code looking like
1227 // MUL dst, src, (2^n + 1)
1228 // into
1229 // SHL tmp, src, n
1230 // ADD dst, src, tmp
1231 HShl* shl = new (allocator) HShl(type,
1232 input_other,
1233 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1234 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1235
1236 block->InsertInstructionBefore(shl, instruction);
1237 block->ReplaceAndRemoveInstructionWith(instruction, add);
1238 RecordSimplification();
1239 } else if (IsPowerOfTwo(factor + 1)) {
1240 // Transform code looking like
1241 // MUL dst, src, (2^n - 1)
1242 // into
1243 // SHL tmp, src, n
1244 // SUB dst, tmp, src
1245 HShl* shl = new (allocator) HShl(type,
1246 input_other,
1247 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1248 HSub* sub = new (allocator) HSub(type, shl, input_other);
1249
1250 block->InsertInstructionBefore(shl, instruction);
1251 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1252 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001253 }
1254 }
1255}
1256
Alexandre Rames188d4312015-04-09 18:30:21 +01001257void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1258 HInstruction* input = instruction->GetInput();
1259 if (input->IsNeg()) {
1260 // Replace code looking like
1261 // NEG tmp, src
1262 // NEG dst, tmp
1263 // with
1264 // src
1265 HNeg* previous_neg = input->AsNeg();
1266 instruction->ReplaceWith(previous_neg->GetInput());
1267 instruction->GetBlock()->RemoveInstruction(instruction);
1268 // We perform the optimization even if the input negation has environment
1269 // uses since it allows removing the current instruction. But we only delete
1270 // the input negation only if it is does not have any uses left.
1271 if (!previous_neg->HasUses()) {
1272 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1273 }
1274 RecordSimplification();
1275 return;
1276 }
1277
Serguei Katkov339dfc22015-04-20 12:29:32 +06001278 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1279 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001280 // Replace code looking like
1281 // SUB tmp, a, b
1282 // NEG dst, tmp
1283 // with
1284 // SUB dst, b, a
1285 // We do not perform the optimization if the input subtraction has
1286 // environment uses or multiple non-environment uses as it could lead to
1287 // worse code. In particular, we do not want the live ranges of `a` and `b`
1288 // to be extended if we are not sure the initial 'SUB' instruction can be
1289 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001290 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001291 HSub* sub = input->AsSub();
1292 HSub* new_sub =
1293 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1294 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1295 if (!sub->HasUses()) {
1296 sub->GetBlock()->RemoveInstruction(sub);
1297 }
1298 RecordSimplification();
1299 }
1300}
1301
1302void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1303 HInstruction* input = instruction->GetInput();
1304 if (input->IsNot()) {
1305 // Replace code looking like
1306 // NOT tmp, src
1307 // NOT dst, tmp
1308 // with
1309 // src
1310 // We perform the optimization even if the input negation has environment
1311 // uses since it allows removing the current instruction. But we only delete
1312 // the input negation only if it is does not have any uses left.
1313 HNot* previous_not = input->AsNot();
1314 instruction->ReplaceWith(previous_not->GetInput());
1315 instruction->GetBlock()->RemoveInstruction(instruction);
1316 if (!previous_not->HasUses()) {
1317 previous_not->GetBlock()->RemoveInstruction(previous_not);
1318 }
1319 RecordSimplification();
1320 }
1321}
1322
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001323void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1324 HConstant* input_cst = instruction->GetConstantRight();
1325 HInstruction* input_other = instruction->GetLeastConstantLeft();
1326
1327 if ((input_cst != nullptr) && input_cst->IsZero()) {
1328 // Replace code looking like
1329 // OR dst, src, 0
1330 // with
1331 // src
1332 instruction->ReplaceWith(input_other);
1333 instruction->GetBlock()->RemoveInstruction(instruction);
1334 return;
1335 }
1336
1337 // We assume that GVN has run before, so we only perform a pointer comparison.
1338 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001339 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001340 if (instruction->GetLeft() == instruction->GetRight()) {
1341 // Replace code looking like
1342 // OR dst, src, src
1343 // with
1344 // src
1345 instruction->ReplaceWith(instruction->GetLeft());
1346 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001347 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001348 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001349
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001350 if (TryDeMorganNegationFactoring(instruction)) return;
1351
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001352 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001353}
1354
1355void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1356 VisitShift(instruction);
1357}
1358
1359void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1360 VisitShift(instruction);
1361}
1362
1363void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1364 HConstant* input_cst = instruction->GetConstantRight();
1365 HInstruction* input_other = instruction->GetLeastConstantLeft();
1366
Serguei Katkov115b53f2015-08-05 17:03:30 +06001367 Primitive::Type type = instruction->GetType();
1368 if (Primitive::IsFloatingPointType(type)) {
1369 return;
1370 }
1371
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001372 if ((input_cst != nullptr) && input_cst->IsZero()) {
1373 // Replace code looking like
1374 // SUB dst, src, 0
1375 // with
1376 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001377 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1378 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1379 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001380 instruction->ReplaceWith(input_other);
1381 instruction->GetBlock()->RemoveInstruction(instruction);
1382 return;
1383 }
1384
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001385 HBasicBlock* block = instruction->GetBlock();
1386 ArenaAllocator* allocator = GetGraph()->GetArena();
1387
Alexandre Rames188d4312015-04-09 18:30:21 +01001388 HInstruction* left = instruction->GetLeft();
1389 HInstruction* right = instruction->GetRight();
1390 if (left->IsConstant()) {
1391 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001392 // Replace code looking like
1393 // SUB dst, 0, src
1394 // with
1395 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001396 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001397 // `x` is `0.0`, the former expression yields `0.0`, while the later
1398 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001399 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001400 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001401 RecordSimplification();
1402 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001403 }
1404 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001405
1406 if (left->IsNeg() && right->IsNeg()) {
1407 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1408 return;
1409 }
1410 }
1411
1412 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1413 // Replace code looking like
1414 // NEG tmp, b
1415 // SUB dst, a, tmp
1416 // with
1417 // ADD dst, a, b
1418 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1419 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1420 RecordSimplification();
1421 right->GetBlock()->RemoveInstruction(right);
1422 return;
1423 }
1424
1425 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1426 // Replace code looking like
1427 // NEG tmp, a
1428 // SUB dst, tmp, b
1429 // with
1430 // ADD tmp, a, b
1431 // NEG dst, tmp
1432 // The second version is not intrinsically better, but enables more
1433 // transformations.
1434 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1435 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1436 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1437 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1438 instruction->ReplaceWith(neg);
1439 instruction->GetBlock()->RemoveInstruction(instruction);
1440 RecordSimplification();
1441 left->GetBlock()->RemoveInstruction(left);
1442 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001443}
1444
1445void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1446 VisitShift(instruction);
1447}
1448
1449void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1450 HConstant* input_cst = instruction->GetConstantRight();
1451 HInstruction* input_other = instruction->GetLeastConstantLeft();
1452
1453 if ((input_cst != nullptr) && input_cst->IsZero()) {
1454 // Replace code looking like
1455 // XOR dst, src, 0
1456 // with
1457 // src
1458 instruction->ReplaceWith(input_other);
1459 instruction->GetBlock()->RemoveInstruction(instruction);
1460 return;
1461 }
1462
1463 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1464 // Replace code looking like
1465 // XOR dst, src, 0xFFF...FF
1466 // with
1467 // NOT dst, src
1468 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1469 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001470 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001471 return;
1472 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001473
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001474 HInstruction* left = instruction->GetLeft();
1475 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001476 if (((left->IsNot() && right->IsNot()) ||
1477 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001478 left->HasOnlyOneNonEnvironmentUse() &&
1479 right->HasOnlyOneNonEnvironmentUse()) {
1480 // Replace code looking like
1481 // NOT nota, a
1482 // NOT notb, b
1483 // XOR dst, nota, notb
1484 // with
1485 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001486 instruction->ReplaceInput(left->InputAt(0), 0);
1487 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001488 left->GetBlock()->RemoveInstruction(left);
1489 right->GetBlock()->RemoveInstruction(right);
1490 RecordSimplification();
1491 return;
1492 }
1493
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001494 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001495}
1496
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001497void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1498 HInstruction* argument = instruction->InputAt(1);
1499 HInstruction* receiver = instruction->InputAt(0);
1500 if (receiver == argument) {
1501 // Because String.equals is an instance call, the receiver is
1502 // a null check if we don't know it's null. The argument however, will
1503 // be the actual object. So we cannot end up in a situation where both
1504 // are equal but could be null.
1505 DCHECK(CanEnsureNotNullAt(argument, instruction));
1506 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1507 instruction->GetBlock()->RemoveInstruction(instruction);
1508 } else {
1509 StringEqualsOptimizations optimizations(instruction);
1510 if (CanEnsureNotNullAt(argument, instruction)) {
1511 optimizations.SetArgumentNotNull();
1512 }
1513 ScopedObjectAccess soa(Thread::Current());
1514 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1515 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1516 optimizations.SetArgumentIsString();
1517 }
1518 }
1519}
1520
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001521void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1522 DCHECK(invoke->IsInvokeStaticOrDirect());
1523 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001524 HInstruction* value = invoke->InputAt(0);
1525 HInstruction* distance = invoke->InputAt(1);
1526 // Replace the invoke with an HRor.
1527 if (is_left) {
1528 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1529 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1530 }
1531 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1532 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1533 // Remove ClinitCheck and LoadClass, if possible.
1534 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1535 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1536 clinit->GetBlock()->RemoveInstruction(clinit);
1537 HInstruction* ldclass = clinit->InputAt(0);
1538 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1539 ldclass->GetBlock()->RemoveInstruction(ldclass);
1540 }
1541 }
1542}
1543
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001544static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1545 if (potential_length->IsArrayLength()) {
1546 return potential_length->InputAt(0) == potential_array;
1547 }
1548
1549 if (potential_array->IsNewArray()) {
1550 return potential_array->InputAt(0) == potential_length;
1551 }
1552
1553 return false;
1554}
1555
1556void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1557 HInstruction* source = instruction->InputAt(0);
1558 HInstruction* destination = instruction->InputAt(2);
1559 HInstruction* count = instruction->InputAt(4);
1560 SystemArrayCopyOptimizations optimizations(instruction);
1561 if (CanEnsureNotNullAt(source, instruction)) {
1562 optimizations.SetSourceIsNotNull();
1563 }
1564 if (CanEnsureNotNullAt(destination, instruction)) {
1565 optimizations.SetDestinationIsNotNull();
1566 }
1567 if (destination == source) {
1568 optimizations.SetDestinationIsSource();
1569 }
1570
1571 if (IsArrayLengthOf(count, source)) {
1572 optimizations.SetCountIsSourceLength();
1573 }
1574
1575 if (IsArrayLengthOf(count, destination)) {
1576 optimizations.SetCountIsDestinationLength();
1577 }
1578
1579 {
1580 ScopedObjectAccess soa(Thread::Current());
1581 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1582 if (destination_rti.IsValid()) {
1583 if (destination_rti.IsObjectArray()) {
1584 if (destination_rti.IsExact()) {
1585 optimizations.SetDoesNotNeedTypeCheck();
1586 }
1587 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001588 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001589 if (destination_rti.IsPrimitiveArrayClass()) {
1590 optimizations.SetDestinationIsPrimitiveArray();
1591 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1592 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001593 }
1594 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001595 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1596 if (source_rti.IsValid()) {
1597 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1598 optimizations.SetDoesNotNeedTypeCheck();
1599 }
1600 if (source_rti.IsPrimitiveArrayClass()) {
1601 optimizations.SetSourceIsPrimitiveArray();
1602 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1603 optimizations.SetSourceIsNonPrimitiveArray();
1604 }
1605 }
1606 }
1607}
1608
Aart Bika19616e2016-02-01 18:57:58 -08001609void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1610 DCHECK(invoke->IsInvokeStaticOrDirect());
1611 uint32_t dex_pc = invoke->GetDexPc();
1612 HInstruction* left = invoke->InputAt(0);
1613 HInstruction* right;
1614 Primitive::Type type = left->GetType();
1615 if (!is_signum) {
1616 right = invoke->InputAt(1);
1617 } else if (type == Primitive::kPrimLong) {
1618 right = GetGraph()->GetLongConstant(0);
1619 } else {
1620 right = GetGraph()->GetIntConstant(0);
1621 }
1622 HCompare* compare = new (GetGraph()->GetArena())
1623 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1624 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1625}
1626
Aart Bik75a38b22016-02-17 10:41:50 -08001627void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1628 DCHECK(invoke->IsInvokeStaticOrDirect());
1629 uint32_t dex_pc = invoke->GetDexPc();
1630 // IsNaN(x) is the same as x != x.
1631 HInstruction* x = invoke->InputAt(0);
1632 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001633 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001634 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1635}
1636
Aart Bik2a6aad92016-02-25 11:32:32 -08001637void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1638 DCHECK(invoke->IsInvokeStaticOrDirect());
1639 uint32_t dex_pc = invoke->GetDexPc();
1640 HInstruction* x = invoke->InputAt(0);
1641 Primitive::Type type = x->GetType();
1642 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1643 HInstruction* nan;
1644 if (type == Primitive::kPrimDouble) {
1645 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1646 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1647 kNeedsEnvironmentOrCache,
1648 kNoSideEffects,
1649 kNoThrow);
1650 } else {
1651 DCHECK_EQ(type, Primitive::kPrimFloat);
1652 nan = GetGraph()->GetIntConstant(0x7fc00000);
1653 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1654 kNeedsEnvironmentOrCache,
1655 kNoSideEffects,
1656 kNoThrow);
1657 }
1658 // Test IsNaN(x), which is the same as x != x.
1659 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1660 condition->SetBias(ComparisonBias::kLtBias);
1661 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1662 // Select between the two.
1663 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1664 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1665 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1666}
1667
Aart Bik11932592016-03-08 12:42:25 -08001668void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1669 uint32_t dex_pc = invoke->GetDexPc();
1670 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1671 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1672}
1673
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001674void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001675 switch (instruction->GetIntrinsic()) {
1676 case Intrinsics::kStringEquals:
1677 SimplifyStringEquals(instruction);
1678 break;
1679 case Intrinsics::kSystemArrayCopy:
1680 SimplifySystemArrayCopy(instruction);
1681 break;
1682 case Intrinsics::kIntegerRotateRight:
1683 case Intrinsics::kLongRotateRight:
1684 SimplifyRotate(instruction, false);
1685 break;
1686 case Intrinsics::kIntegerRotateLeft:
1687 case Intrinsics::kLongRotateLeft:
1688 SimplifyRotate(instruction, true);
1689 break;
1690 case Intrinsics::kIntegerCompare:
1691 case Intrinsics::kLongCompare:
1692 SimplifyCompare(instruction, /* is_signum */ false);
1693 break;
1694 case Intrinsics::kIntegerSignum:
1695 case Intrinsics::kLongSignum:
1696 SimplifyCompare(instruction, /* is_signum */ true);
1697 break;
1698 case Intrinsics::kFloatIsNaN:
1699 case Intrinsics::kDoubleIsNaN:
1700 SimplifyIsNaN(instruction);
1701 break;
1702 case Intrinsics::kFloatFloatToIntBits:
1703 case Intrinsics::kDoubleDoubleToLongBits:
1704 SimplifyFP2Int(instruction);
1705 break;
Aart Bik11932592016-03-08 12:42:25 -08001706 case Intrinsics::kUnsafeLoadFence:
1707 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1708 break;
1709 case Intrinsics::kUnsafeStoreFence:
1710 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1711 break;
1712 case Intrinsics::kUnsafeFullFence:
1713 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1714 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001715 default:
1716 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001717 }
1718}
1719
Aart Bikbb245d12015-10-19 11:05:03 -07001720void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1721 HInstruction* cond = deoptimize->InputAt(0);
1722 if (cond->IsConstant()) {
1723 if (cond->AsIntConstant()->IsZero()) {
1724 // Never deopt: instruction can be removed.
1725 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1726 } else {
1727 // Always deopt.
1728 }
1729 }
1730}
1731
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001732} // namespace art