blob: 049901b8825b420c5e8d6c192bad3140609436ec [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;
Anton Shaminbdd79352016-02-15 12:48:36 +060073 void VisitBelow(HBelow* condition) OVERRIDE;
74 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
75 void VisitAbove(HAbove* condition) OVERRIDE;
76 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitDiv(HDiv* instruction) OVERRIDE;
78 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010079 void VisitNeg(HNeg* instruction) OVERRIDE;
80 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000081 void VisitOr(HOr* instruction) OVERRIDE;
82 void VisitShl(HShl* instruction) OVERRIDE;
83 void VisitShr(HShr* instruction) OVERRIDE;
84 void VisitSub(HSub* instruction) OVERRIDE;
85 void VisitUShr(HUShr* instruction) OVERRIDE;
86 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000087 void VisitSelect(HSelect* select) OVERRIDE;
88 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010089 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010090 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070091 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010092
93 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000094
Scott Wakeling40a04bf2015-12-11 09:50:36 +000095 void SimplifyRotate(HInvoke* invoke, bool is_left);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010096 void SimplifySystemArrayCopy(HInvoke* invoke);
97 void SimplifyStringEquals(HInvoke* invoke);
Aart Bika19616e2016-02-01 18:57:58 -080098 void SimplifyCompare(HInvoke* invoke, bool has_zero_op);
Aart Bik75a38b22016-02-17 10:41:50 -080099 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800100 void SimplifyFP2Int(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800101 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100102
Calin Juravleacf735c2015-02-12 15:25:22 +0000103 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100104 bool simplification_occurred_ = false;
105 int simplifications_at_current_position_ = 0;
106 // We ensure we do not loop infinitely. The value is a finger in the air guess
107 // that should allow enough simplification.
108 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000109};
110
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100111void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000112 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100113 visitor.Run();
114}
115
116void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100117 // Iterate in reverse post order to open up more simplifications to users
118 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100119 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
120 // The simplification of an instruction to another instruction may yield
121 // possibilities for other simplifications. So although we perform a reverse
122 // post order visit, we sometimes need to revisit an instruction index.
123 simplification_occurred_ = false;
124 VisitBasicBlock(it.Current());
125 if (simplification_occurred_ &&
126 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
127 // New simplifications may be applicable to the instruction at the
128 // current index, so don't advance the iterator.
129 continue;
130 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100131 simplifications_at_current_position_ = 0;
132 it.Advance();
133 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100134}
135
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000136namespace {
137
138bool AreAllBitsSet(HConstant* constant) {
139 return Int64FromConstant(constant) == -1;
140}
141
142} // namespace
143
Alexandre Rames188d4312015-04-09 18:30:21 +0100144// Returns true if the code was simplified to use only one negation operation
145// after the binary operation instead of one on each of the inputs.
146bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
147 DCHECK(binop->IsAdd() || binop->IsSub());
148 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
149 HNeg* left_neg = binop->GetLeft()->AsNeg();
150 HNeg* right_neg = binop->GetRight()->AsNeg();
151 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
152 !right_neg->HasOnlyOneNonEnvironmentUse()) {
153 return false;
154 }
155 // Replace code looking like
156 // NEG tmp1, a
157 // NEG tmp2, b
158 // ADD dst, tmp1, tmp2
159 // with
160 // ADD tmp, a, b
161 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600162 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
163 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
164 // while the later yields `-0.0`.
165 if (!Primitive::IsIntegralType(binop->GetType())) {
166 return false;
167 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100168 binop->ReplaceInput(left_neg->GetInput(), 0);
169 binop->ReplaceInput(right_neg->GetInput(), 1);
170 left_neg->GetBlock()->RemoveInstruction(left_neg);
171 right_neg->GetBlock()->RemoveInstruction(right_neg);
172 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
173 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
174 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
175 RecordSimplification();
176 return true;
177}
178
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000179bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
180 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
181 Primitive::Type type = op->GetType();
182 HInstruction* left = op->GetLeft();
183 HInstruction* right = op->GetRight();
184
185 // We can apply De Morgan's laws if both inputs are Not's and are only used
186 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000187 if (((left->IsNot() && right->IsNot()) ||
188 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000189 left->HasOnlyOneNonEnvironmentUse() &&
190 right->HasOnlyOneNonEnvironmentUse()) {
191 // Replace code looking like
192 // NOT nota, a
193 // NOT notb, b
194 // AND dst, nota, notb (respectively OR)
195 // with
196 // OR or, a, b (respectively AND)
197 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000198 HInstruction* src_left = left->InputAt(0);
199 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000200 uint32_t dex_pc = op->GetDexPc();
201
202 // Remove the negations on the inputs.
203 left->ReplaceWith(src_left);
204 right->ReplaceWith(src_right);
205 left->GetBlock()->RemoveInstruction(left);
206 right->GetBlock()->RemoveInstruction(right);
207
208 // Replace the `HAnd` or `HOr`.
209 HBinaryOperation* hbin;
210 if (op->IsAnd()) {
211 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
212 } else {
213 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
214 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000215 HInstruction* hnot;
216 if (left->IsBooleanNot()) {
217 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
218 } else {
219 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
220 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000221
222 op->GetBlock()->InsertInstructionBefore(hbin, op);
223 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
224
225 RecordSimplification();
226 return true;
227 }
228
229 return false;
230}
231
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000232void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
233 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
234 HConstant* input_cst = instruction->GetConstantRight();
235 HInstruction* input_other = instruction->GetLeastConstantLeft();
236
Mark Mendellba56d062015-05-05 21:34:03 -0400237 if (input_cst != nullptr) {
238 if (input_cst->IsZero()) {
239 // Replace code looking like
240 // SHL dst, src, 0
241 // with
242 // src
243 instruction->ReplaceWith(input_other);
244 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400245 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000246 }
247}
248
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000249static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
250 return (sub->GetRight() == other &&
251 sub->GetLeft()->IsConstant() &&
252 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
253}
254
255bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
256 HUShr* ushr,
257 HShl* shl) {
258 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
259 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
260 ushr->GetLeft(),
261 ushr->GetRight());
262 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
263 if (!ushr->HasUses()) {
264 ushr->GetBlock()->RemoveInstruction(ushr);
265 }
266 if (!ushr->GetRight()->HasUses()) {
267 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
268 }
269 if (!shl->HasUses()) {
270 shl->GetBlock()->RemoveInstruction(shl);
271 }
272 if (!shl->GetRight()->HasUses()) {
273 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
274 }
275 return true;
276}
277
278// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
279bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000280 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
281 HInstruction* left = op->GetLeft();
282 HInstruction* right = op->GetRight();
283 // If we have an UShr and a Shl (in either order).
284 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
285 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
286 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
287 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
288 if (ushr->GetType() == shl->GetType() &&
289 ushr->GetLeft() == shl->GetLeft()) {
290 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
291 // Shift distances are both constant, try replacing with Ror if they
292 // add up to the register size.
293 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
294 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
295 // Shift distances are potentially of the form x and (reg_size - x).
296 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
297 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
298 // Shift distances are potentially of the form d and -d.
299 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
300 }
301 }
302 }
303 return false;
304}
305
306// Try replacing code looking like (x >>> #rdist OP x << #ldist):
307// UShr dst, x, #rdist
308// Shl tmp, x, #ldist
309// OP dst, dst, tmp
310// or like (x >>> #rdist OP x << #-ldist):
311// UShr dst, x, #rdist
312// Shl tmp, x, #-ldist
313// OP dst, dst, tmp
314// with
315// Ror dst, x, #rdist
316bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
317 HUShr* ushr,
318 HShl* shl) {
319 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
320 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
321 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
322 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
323 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
324 ReplaceRotateWithRor(op, ushr, shl);
325 return true;
326 }
327 return false;
328}
329
330// Replace code looking like (x >>> -d OP x << d):
331// Neg neg, d
332// UShr dst, x, neg
333// Shl tmp, x, d
334// OP dst, dst, tmp
335// with
336// Neg neg, d
337// Ror dst, x, neg
338// *** OR ***
339// Replace code looking like (x >>> d OP x << -d):
340// UShr dst, x, d
341// Neg neg, d
342// Shl tmp, x, neg
343// OP dst, dst, tmp
344// with
345// Ror dst, x, d
346bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
347 HUShr* ushr,
348 HShl* shl) {
349 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
350 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
351 bool neg_is_left = shl->GetRight()->IsNeg();
352 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
353 // And the shift distance being negated is the distance being shifted the other way.
354 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
355 ReplaceRotateWithRor(op, ushr, shl);
356 }
357 return false;
358}
359
360// Try replacing code looking like (x >>> d OP x << (#bits - d)):
361// UShr dst, x, d
362// Sub ld, #bits, d
363// Shl tmp, x, ld
364// OP dst, dst, tmp
365// with
366// Ror dst, x, d
367// *** OR ***
368// Replace code looking like (x >>> (#bits - d) OP x << d):
369// Sub rd, #bits, d
370// UShr dst, x, rd
371// Shl tmp, x, d
372// OP dst, dst, tmp
373// with
374// Neg neg, d
375// Ror dst, x, neg
376bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
377 HUShr* ushr,
378 HShl* shl) {
379 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
380 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
381 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
382 HInstruction* shl_shift = shl->GetRight();
383 HInstruction* ushr_shift = ushr->GetRight();
384 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
385 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
386 return ReplaceRotateWithRor(op, ushr, shl);
387 }
388 return false;
389}
390
Calin Juravle10e244f2015-01-26 18:54:32 +0000391void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
392 HInstruction* obj = null_check->InputAt(0);
393 if (!obj->CanBeNull()) {
394 null_check->ReplaceWith(obj);
395 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000396 if (stats_ != nullptr) {
397 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
398 }
399 }
400}
401
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100402bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
403 if (!input->CanBeNull()) {
404 return true;
405 }
406
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100407 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
408 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100409 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100410 return true;
411 }
412 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100413
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100414 return false;
415}
416
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100417// Returns whether doing a type test between the class of `object` against `klass` has
418// a statically known outcome. The result of the test is stored in `outcome`.
419static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000420 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
421 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
422 ScopedObjectAccess soa(Thread::Current());
423 if (!obj_rti.IsValid()) {
424 // We run the simplifier before the reference type propagation so type info might not be
425 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100426 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000427 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100428
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100429 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100430 if (!class_rti.IsValid()) {
431 // Happens when the loaded class is unresolved.
432 return false;
433 }
434 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000435 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100436 *outcome = true;
437 return true;
438 } else if (obj_rti.IsExact()) {
439 // The test failed at compile time so will also fail at runtime.
440 *outcome = false;
441 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100442 } else if (!class_rti.IsInterface()
443 && !obj_rti.IsInterface()
444 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100445 // Different type hierarchy. The test will fail.
446 *outcome = false;
447 return true;
448 }
449 return false;
450}
451
452void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
453 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100454 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
455 if (load_class->NeedsAccessCheck()) {
456 // If we need to perform an access check we cannot remove the instruction.
457 return;
458 }
459
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100460 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100461 check_cast->ClearMustDoNullCheck();
462 }
463
464 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000465 check_cast->GetBlock()->RemoveInstruction(check_cast);
466 if (stats_ != nullptr) {
467 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
468 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100469 return;
470 }
471
472 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700473 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100474 if (outcome) {
475 check_cast->GetBlock()->RemoveInstruction(check_cast);
476 if (stats_ != nullptr) {
477 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
478 }
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()) {
508 instruction->ReplaceWith(graph->GetIntConstant(0));
509 instruction->GetBlock()->RemoveInstruction(instruction);
510 RecordSimplification();
511 return;
512 }
513
514 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700515 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100516 if (outcome && can_be_null) {
517 // Type test will succeed, we just need a null test.
518 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
519 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
520 instruction->ReplaceWith(test);
521 } else {
522 // We've statically determined the result of the instanceof.
523 instruction->ReplaceWith(graph->GetIntConstant(outcome));
524 }
525 RecordSimplification();
526 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700527 if (outcome && !load_class->HasUses()) {
528 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
529 // However, here we know that it cannot because the instanceof check was successfull, hence
530 // the class was already loaded.
531 load_class->GetBlock()->RemoveInstruction(load_class);
532 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100533 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100534}
535
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100536void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* 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
543void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
544 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100545 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100546 instruction->ClearValueCanBeNull();
547 }
548}
549
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000550void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100551 HBasicBlock* block = check->GetBlock();
552 // Currently always keep the suspend check at entry.
553 if (block->IsEntryBlock()) return;
554
555 // Currently always keep suspend checks at loop entry.
556 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
557 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
558 return;
559 }
560
561 // Remove the suspend check that was added at build time for the baseline
562 // compiler.
563 block->RemoveInstruction(check);
564}
565
Anton Shaminbdd79352016-02-15 12:48:36 +0600566static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
567 HInstruction *lhs = cond->InputAt(0);
568 HInstruction *rhs = cond->InputAt(1);
569 switch (cond->GetKind()) {
570 case HInstruction::kEqual:
571 return new (arena) HEqual(rhs, lhs);
572 case HInstruction::kNotEqual:
573 return new (arena) HNotEqual(rhs, lhs);
574 case HInstruction::kLessThan:
575 return new (arena) HGreaterThan(rhs, lhs);
576 case HInstruction::kLessThanOrEqual:
577 return new (arena) HGreaterThanOrEqual(rhs, lhs);
578 case HInstruction::kGreaterThan:
579 return new (arena) HLessThan(rhs, lhs);
580 case HInstruction::kGreaterThanOrEqual:
581 return new (arena) HLessThanOrEqual(rhs, lhs);
582 case HInstruction::kBelow:
583 return new (arena) HAbove(rhs, lhs);
584 case HInstruction::kBelowOrEqual:
585 return new (arena) HAboveOrEqual(rhs, lhs);
586 case HInstruction::kAbove:
587 return new (arena) HBelow(rhs, lhs);
588 case HInstruction::kAboveOrEqual:
589 return new (arena) HBelowOrEqual(rhs, lhs);
590 default:
591 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
592 }
593 return nullptr;
594}
595
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000596void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100597 HInstruction* input_const = equal->GetConstantRight();
598 if (input_const != nullptr) {
599 HInstruction* input_value = equal->GetLeastConstantLeft();
600 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
601 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100602 // We are comparing the boolean to a constant which is of type int and can
603 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100604 if (input_const->AsIntConstant()->IsOne()) {
605 // Replace (bool_value == true) with bool_value
606 equal->ReplaceWith(input_value);
607 block->RemoveInstruction(equal);
608 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100609 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500610 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
611 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100612 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100613 } else {
614 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
615 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
616 block->RemoveInstruction(equal);
617 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100618 }
Mark Mendellc4701932015-04-10 13:18:51 -0400619 } else {
620 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100621 }
Mark Mendellc4701932015-04-10 13:18:51 -0400622 } else {
623 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100624 }
625}
626
David Brazdil0d13fee2015-04-17 14:52:19 +0100627void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
628 HInstruction* input_const = not_equal->GetConstantRight();
629 if (input_const != nullptr) {
630 HInstruction* input_value = not_equal->GetLeastConstantLeft();
631 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
632 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100633 // We are comparing the boolean to a constant which is of type int and can
634 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100635 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500636 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
637 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100638 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100639 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100640 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100641 not_equal->ReplaceWith(input_value);
642 block->RemoveInstruction(not_equal);
643 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100644 } else {
645 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
646 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
647 block->RemoveInstruction(not_equal);
648 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100649 }
Mark Mendellc4701932015-04-10 13:18:51 -0400650 } else {
651 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100652 }
Mark Mendellc4701932015-04-10 13:18:51 -0400653 } else {
654 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100655 }
656}
657
658void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000659 HInstruction* input = bool_not->InputAt(0);
660 HInstruction* replace_with = nullptr;
661
662 if (input->IsIntConstant()) {
663 // Replace !(true/false) with false/true.
664 if (input->AsIntConstant()->IsOne()) {
665 replace_with = GetGraph()->GetIntConstant(0);
666 } else {
667 DCHECK(input->AsIntConstant()->IsZero());
668 replace_with = GetGraph()->GetIntConstant(1);
669 }
670 } else if (input->IsBooleanNot()) {
671 // Replace (!(!bool_value)) with bool_value.
672 replace_with = input->InputAt(0);
673 } else if (input->IsCondition() &&
674 // Don't change FP compares. The definition of compares involving
675 // NaNs forces the compares to be done as written by the user.
676 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
677 // Replace condition with its opposite.
678 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
679 }
680
681 if (replace_with != nullptr) {
682 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100683 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000684 RecordSimplification();
685 }
686}
687
688void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
689 HInstruction* replace_with = nullptr;
690 HInstruction* condition = select->GetCondition();
691 HInstruction* true_value = select->GetTrueValue();
692 HInstruction* false_value = select->GetFalseValue();
693
694 if (condition->IsBooleanNot()) {
695 // Change ((!cond) ? x : y) to (cond ? y : x).
696 condition = condition->InputAt(0);
697 std::swap(true_value, false_value);
698 select->ReplaceInput(false_value, 0);
699 select->ReplaceInput(true_value, 1);
700 select->ReplaceInput(condition, 2);
701 RecordSimplification();
702 }
703
704 if (true_value == false_value) {
705 // Replace (cond ? x : x) with (x).
706 replace_with = true_value;
707 } else if (condition->IsIntConstant()) {
708 if (condition->AsIntConstant()->IsOne()) {
709 // Replace (true ? x : y) with (x).
710 replace_with = true_value;
711 } else {
712 // Replace (false ? x : y) with (y).
713 DCHECK(condition->AsIntConstant()->IsZero());
714 replace_with = false_value;
715 }
716 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
717 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
718 // Replace (cond ? true : false) with (cond).
719 replace_with = condition;
720 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
721 // Replace (cond ? false : true) with (!cond).
722 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
723 }
724 }
725
726 if (replace_with != nullptr) {
727 select->ReplaceWith(replace_with);
728 select->GetBlock()->RemoveInstruction(select);
729 RecordSimplification();
730 }
731}
732
733void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
734 HInstruction* condition = instruction->InputAt(0);
735 if (condition->IsBooleanNot()) {
736 // Swap successors if input is negated.
737 instruction->ReplaceInput(condition->InputAt(0), 0);
738 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100739 RecordSimplification();
740 }
741}
742
Mingyao Yang0304e182015-01-30 16:41:29 -0800743void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
744 HInstruction* input = instruction->InputAt(0);
745 // If the array is a NewArray with constant size, replace the array length
746 // with the constant instruction. This helps the bounds check elimination phase.
747 if (input->IsNewArray()) {
748 input = input->InputAt(0);
749 if (input->IsIntConstant()) {
750 instruction->ReplaceWith(input);
751 }
752 }
753}
754
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000755void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000756 HInstruction* value = instruction->GetValue();
757 if (value->GetType() != Primitive::kPrimNot) return;
758
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100759 if (CanEnsureNotNullAt(value, instruction)) {
760 instruction->ClearValueCanBeNull();
761 }
762
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000763 if (value->IsArrayGet()) {
764 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
765 // If the code is just swapping elements in the array, no need for a type check.
766 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100767 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000768 }
769 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100770
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100771 if (value->IsNullConstant()) {
772 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100773 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100774 }
775
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100776 ScopedObjectAccess soa(Thread::Current());
777 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
778 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
779 if (!array_rti.IsValid()) {
780 return;
781 }
782
783 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
784 instruction->ClearNeedsTypeCheck();
785 return;
786 }
787
788 if (array_rti.IsObjectArray()) {
789 if (array_rti.IsExact()) {
790 instruction->ClearNeedsTypeCheck();
791 return;
792 }
793 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100794 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000795}
796
Vladimir Markob52bbde2016-02-12 12:06:05 +0000797static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
798 // Besides conversion to the same type, widening integral conversions are implicit,
799 // excluding conversions to long and the byte->char conversion where we need to
800 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
801 return result_type == input_type ||
802 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
803 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
804 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
805 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
806}
807
808static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
809 // The conversion to a larger type is loss-less with the exception of two cases,
810 // - conversion to char, the only unsigned type, where we may lose some bits, and
811 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
812 // For integral to FP conversions this holds because the FP mantissa is large enough.
813 DCHECK_NE(input_type, result_type);
814 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
815 result_type != Primitive::kPrimChar &&
816 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
817}
818
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000819void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000820 HInstruction* input = instruction->GetInput();
821 Primitive::Type input_type = input->GetType();
822 Primitive::Type result_type = instruction->GetResultType();
823 if (IsTypeConversionImplicit(input_type, result_type)) {
824 // Remove the implicit conversion; this includes conversion to the same type.
825 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000826 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000827 RecordSimplification();
828 return;
829 }
830
831 if (input->IsTypeConversion()) {
832 HTypeConversion* input_conversion = input->AsTypeConversion();
833 HInstruction* original_input = input_conversion->GetInput();
834 Primitive::Type original_type = original_input->GetType();
835
836 // When the first conversion is lossless, a direct conversion from the original type
837 // to the final type yields the same result, even for a lossy second conversion, for
838 // example float->double->int or int->double->float.
839 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
840
841 // For integral conversions, see if the first conversion loses only bits that the second
842 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
843 // conversion yields the same result, for example long->int->short or int->char->short.
844 bool integral_conversions_with_non_widening_second =
845 Primitive::IsIntegralType(input_type) &&
846 Primitive::IsIntegralType(original_type) &&
847 Primitive::IsIntegralType(result_type) &&
848 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
849
850 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
851 // If the merged conversion is implicit, do the simplification unconditionally.
852 if (IsTypeConversionImplicit(original_type, result_type)) {
853 instruction->ReplaceWith(original_input);
854 instruction->GetBlock()->RemoveInstruction(instruction);
855 if (!input_conversion->HasUses()) {
856 // Don't wait for DCE.
857 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
858 }
859 RecordSimplification();
860 return;
861 }
862 // Otherwise simplify only if the first conversion has no other use.
863 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
864 input_conversion->ReplaceWith(original_input);
865 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
866 RecordSimplification();
867 return;
868 }
869 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000870 } else if (input->IsAnd() &&
871 Primitive::IsIntegralType(result_type) &&
872 input->HasOnlyOneNonEnvironmentUse()) {
873 DCHECK(Primitive::IsIntegralType(input_type));
874 HAnd* input_and = input->AsAnd();
875 HConstant* constant = input_and->GetConstantRight();
876 if (constant != nullptr) {
877 int64_t value = Int64FromConstant(constant);
878 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
879 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
880 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
881 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
882 input_and->ReplaceWith(input_and->GetLeastConstantLeft());
883 input_and->GetBlock()->RemoveInstruction(input_and);
884 RecordSimplification();
885 return;
886 }
887 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000888 }
889}
890
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000891void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
892 HConstant* input_cst = instruction->GetConstantRight();
893 HInstruction* input_other = instruction->GetLeastConstantLeft();
894 if ((input_cst != nullptr) && input_cst->IsZero()) {
895 // Replace code looking like
896 // ADD dst, src, 0
897 // with
898 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600899 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
900 // `x` is `-0.0`, the former expression yields `0.0`, while the later
901 // yields `-0.0`.
902 if (Primitive::IsIntegralType(instruction->GetType())) {
903 instruction->ReplaceWith(input_other);
904 instruction->GetBlock()->RemoveInstruction(instruction);
905 return;
906 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100907 }
908
909 HInstruction* left = instruction->GetLeft();
910 HInstruction* right = instruction->GetRight();
911 bool left_is_neg = left->IsNeg();
912 bool right_is_neg = right->IsNeg();
913
914 if (left_is_neg && right_is_neg) {
915 if (TryMoveNegOnInputsAfterBinop(instruction)) {
916 return;
917 }
918 }
919
920 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
921 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
922 // Replace code looking like
923 // NEG tmp, b
924 // ADD dst, a, tmp
925 // with
926 // SUB dst, a, b
927 // We do not perform the optimization if the input negation has environment
928 // uses or multiple non-environment uses as it could lead to worse code. In
929 // particular, we do not want the live range of `b` to be extended if we are
930 // not sure the initial 'NEG' instruction can be removed.
931 HInstruction* other = left_is_neg ? right : left;
932 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
933 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
934 RecordSimplification();
935 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000936 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000937 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000938
939 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000940}
941
942void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
943 HConstant* input_cst = instruction->GetConstantRight();
944 HInstruction* input_other = instruction->GetLeastConstantLeft();
945
Vladimir Marko452c1b62015-09-25 14:44:17 +0100946 if (input_cst != nullptr) {
947 int64_t value = Int64FromConstant(input_cst);
948 if (value == -1) {
949 // Replace code looking like
950 // AND dst, src, 0xFFF...FF
951 // with
952 // src
953 instruction->ReplaceWith(input_other);
954 instruction->GetBlock()->RemoveInstruction(instruction);
955 RecordSimplification();
956 return;
957 }
958 // Eliminate And from UShr+And if the And-mask contains all the bits that
959 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
960 // precisely clears the shifted-in sign bits.
961 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
962 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
963 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
964 size_t num_tail_bits_set = CTZ(value + 1);
965 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
966 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
967 instruction->ReplaceWith(input_other);
968 instruction->GetBlock()->RemoveInstruction(instruction);
969 RecordSimplification();
970 return;
971 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
972 input_other->HasOnlyOneNonEnvironmentUse()) {
973 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
974 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
975 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
976 input_other->InputAt(0),
977 input_other->InputAt(1),
978 input_other->GetDexPc());
979 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
980 input_other->GetBlock()->RemoveInstruction(input_other);
981 RecordSimplification();
982 return;
983 }
984 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000985 }
986
987 // We assume that GVN has run before, so we only perform a pointer comparison.
988 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100989 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000990 if (instruction->GetLeft() == instruction->GetRight()) {
991 // Replace code looking like
992 // AND dst, src, src
993 // with
994 // src
995 instruction->ReplaceWith(instruction->GetLeft());
996 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000997 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000998 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000999
1000 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001001}
1002
Mark Mendellc4701932015-04-10 13:18:51 -04001003void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1004 VisitCondition(condition);
1005}
1006
1007void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1008 VisitCondition(condition);
1009}
1010
1011void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1012 VisitCondition(condition);
1013}
1014
1015void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1016 VisitCondition(condition);
1017}
1018
Anton Shaminbdd79352016-02-15 12:48:36 +06001019void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1020 VisitCondition(condition);
1021}
1022
1023void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1024 VisitCondition(condition);
1025}
1026
1027void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1028 VisitCondition(condition);
1029}
1030
1031void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1032 VisitCondition(condition);
1033}
Aart Bike9f37602015-10-09 11:15:55 -07001034
Mark Mendellc4701932015-04-10 13:18:51 -04001035void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001036 // Reverse condition if left is constant. Our code generators prefer constant
1037 // on the right hand side.
1038 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1039 HBasicBlock* block = condition->GetBlock();
1040 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1041 // If it is a fp we must set the opposite bias.
1042 if (replacement != nullptr) {
1043 if (condition->IsLtBias()) {
1044 replacement->SetBias(ComparisonBias::kGtBias);
1045 } else if (condition->IsGtBias()) {
1046 replacement->SetBias(ComparisonBias::kLtBias);
1047 }
1048 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1049 RecordSimplification();
1050
1051 condition = replacement;
1052 }
1053 }
Mark Mendellc4701932015-04-10 13:18:51 -04001054
Mark Mendellc4701932015-04-10 13:18:51 -04001055 HInstruction* left = condition->GetLeft();
1056 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001057
1058 // Try to fold an HCompare into this HCondition.
1059
Mark Mendellc4701932015-04-10 13:18:51 -04001060 // We can only replace an HCondition which compares a Compare to 0.
1061 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1062 // condition with a long, float or double comparison as input.
1063 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1064 // Conversion is not possible.
1065 return;
1066 }
1067
1068 // Is the Compare only used for this purpose?
1069 if (!left->GetUses().HasOnlyOneUse()) {
1070 // Someone else also wants the result of the compare.
1071 return;
1072 }
1073
1074 if (!left->GetEnvUses().IsEmpty()) {
1075 // There is a reference to the compare result in an environment. Do we really need it?
1076 if (GetGraph()->IsDebuggable()) {
1077 return;
1078 }
1079
1080 // We have to ensure that there are no deopt points in the sequence.
1081 if (left->HasAnyEnvironmentUseBefore(condition)) {
1082 return;
1083 }
1084 }
1085
1086 // Clean up any environment uses from the HCompare, if any.
1087 left->RemoveEnvironmentUsers();
1088
1089 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1090 condition->SetBias(left->AsCompare()->GetBias());
1091
1092 // Replace the operands of the HCondition.
1093 condition->ReplaceInput(left->InputAt(0), 0);
1094 condition->ReplaceInput(left->InputAt(1), 1);
1095
1096 // Remove the HCompare.
1097 left->GetBlock()->RemoveInstruction(left);
1098
1099 RecordSimplification();
1100}
1101
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001102void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1103 HConstant* input_cst = instruction->GetConstantRight();
1104 HInstruction* input_other = instruction->GetLeastConstantLeft();
1105 Primitive::Type type = instruction->GetType();
1106
1107 if ((input_cst != nullptr) && input_cst->IsOne()) {
1108 // Replace code looking like
1109 // DIV dst, src, 1
1110 // with
1111 // src
1112 instruction->ReplaceWith(input_other);
1113 instruction->GetBlock()->RemoveInstruction(instruction);
1114 return;
1115 }
1116
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001117 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001118 // Replace code looking like
1119 // DIV dst, src, -1
1120 // with
1121 // NEG dst, src
1122 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001123 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001124 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001125 return;
1126 }
1127
1128 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1129 // Try replacing code looking like
1130 // DIV dst, src, constant
1131 // with
1132 // MUL dst, src, 1 / constant
1133 HConstant* reciprocal = nullptr;
1134 if (type == Primitive::Primitive::kPrimDouble) {
1135 double value = input_cst->AsDoubleConstant()->GetValue();
1136 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1137 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1138 }
1139 } else {
1140 DCHECK_EQ(type, Primitive::kPrimFloat);
1141 float value = input_cst->AsFloatConstant()->GetValue();
1142 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1143 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1144 }
1145 }
1146
1147 if (reciprocal != nullptr) {
1148 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1149 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1150 RecordSimplification();
1151 return;
1152 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001153 }
1154}
1155
1156void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1157 HConstant* input_cst = instruction->GetConstantRight();
1158 HInstruction* input_other = instruction->GetLeastConstantLeft();
1159 Primitive::Type type = instruction->GetType();
1160 HBasicBlock* block = instruction->GetBlock();
1161 ArenaAllocator* allocator = GetGraph()->GetArena();
1162
1163 if (input_cst == nullptr) {
1164 return;
1165 }
1166
1167 if (input_cst->IsOne()) {
1168 // Replace code looking like
1169 // MUL dst, src, 1
1170 // with
1171 // src
1172 instruction->ReplaceWith(input_other);
1173 instruction->GetBlock()->RemoveInstruction(instruction);
1174 return;
1175 }
1176
1177 if (input_cst->IsMinusOne() &&
1178 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1179 // Replace code looking like
1180 // MUL dst, src, -1
1181 // with
1182 // NEG dst, src
1183 HNeg* neg = new (allocator) HNeg(type, input_other);
1184 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001185 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001186 return;
1187 }
1188
1189 if (Primitive::IsFloatingPointType(type) &&
1190 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1191 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1192 // Replace code looking like
1193 // FP_MUL dst, src, 2.0
1194 // with
1195 // FP_ADD dst, src, src
1196 // The 'int' and 'long' cases are handled below.
1197 block->ReplaceAndRemoveInstructionWith(instruction,
1198 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001199 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001200 return;
1201 }
1202
1203 if (Primitive::IsIntOrLongType(type)) {
1204 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001205 // Even though constant propagation also takes care of the zero case, other
1206 // optimizations can lead to having a zero multiplication.
1207 if (factor == 0) {
1208 // Replace code looking like
1209 // MUL dst, src, 0
1210 // with
1211 // 0
1212 instruction->ReplaceWith(input_cst);
1213 instruction->GetBlock()->RemoveInstruction(instruction);
1214 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001215 // Replace code looking like
1216 // MUL dst, src, pow_of_2
1217 // with
1218 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001219 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001220 HShl* shl = new(allocator) HShl(type, input_other, shift);
1221 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001222 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001223 } else if (IsPowerOfTwo(factor - 1)) {
1224 // Transform code looking like
1225 // MUL dst, src, (2^n + 1)
1226 // into
1227 // SHL tmp, src, n
1228 // ADD dst, src, tmp
1229 HShl* shl = new (allocator) HShl(type,
1230 input_other,
1231 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1232 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1233
1234 block->InsertInstructionBefore(shl, instruction);
1235 block->ReplaceAndRemoveInstructionWith(instruction, add);
1236 RecordSimplification();
1237 } else if (IsPowerOfTwo(factor + 1)) {
1238 // Transform code looking like
1239 // MUL dst, src, (2^n - 1)
1240 // into
1241 // SHL tmp, src, n
1242 // SUB dst, tmp, src
1243 HShl* shl = new (allocator) HShl(type,
1244 input_other,
1245 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1246 HSub* sub = new (allocator) HSub(type, shl, input_other);
1247
1248 block->InsertInstructionBefore(shl, instruction);
1249 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1250 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001251 }
1252 }
1253}
1254
Alexandre Rames188d4312015-04-09 18:30:21 +01001255void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1256 HInstruction* input = instruction->GetInput();
1257 if (input->IsNeg()) {
1258 // Replace code looking like
1259 // NEG tmp, src
1260 // NEG dst, tmp
1261 // with
1262 // src
1263 HNeg* previous_neg = input->AsNeg();
1264 instruction->ReplaceWith(previous_neg->GetInput());
1265 instruction->GetBlock()->RemoveInstruction(instruction);
1266 // We perform the optimization even if the input negation has environment
1267 // uses since it allows removing the current instruction. But we only delete
1268 // the input negation only if it is does not have any uses left.
1269 if (!previous_neg->HasUses()) {
1270 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1271 }
1272 RecordSimplification();
1273 return;
1274 }
1275
Serguei Katkov339dfc22015-04-20 12:29:32 +06001276 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1277 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001278 // Replace code looking like
1279 // SUB tmp, a, b
1280 // NEG dst, tmp
1281 // with
1282 // SUB dst, b, a
1283 // We do not perform the optimization if the input subtraction has
1284 // environment uses or multiple non-environment uses as it could lead to
1285 // worse code. In particular, we do not want the live ranges of `a` and `b`
1286 // to be extended if we are not sure the initial 'SUB' instruction can be
1287 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001288 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001289 HSub* sub = input->AsSub();
1290 HSub* new_sub =
1291 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1292 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1293 if (!sub->HasUses()) {
1294 sub->GetBlock()->RemoveInstruction(sub);
1295 }
1296 RecordSimplification();
1297 }
1298}
1299
1300void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1301 HInstruction* input = instruction->GetInput();
1302 if (input->IsNot()) {
1303 // Replace code looking like
1304 // NOT tmp, src
1305 // NOT dst, tmp
1306 // with
1307 // src
1308 // We perform the optimization even if the input negation has environment
1309 // uses since it allows removing the current instruction. But we only delete
1310 // the input negation only if it is does not have any uses left.
1311 HNot* previous_not = input->AsNot();
1312 instruction->ReplaceWith(previous_not->GetInput());
1313 instruction->GetBlock()->RemoveInstruction(instruction);
1314 if (!previous_not->HasUses()) {
1315 previous_not->GetBlock()->RemoveInstruction(previous_not);
1316 }
1317 RecordSimplification();
1318 }
1319}
1320
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001321void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1322 HConstant* input_cst = instruction->GetConstantRight();
1323 HInstruction* input_other = instruction->GetLeastConstantLeft();
1324
1325 if ((input_cst != nullptr) && input_cst->IsZero()) {
1326 // Replace code looking like
1327 // OR dst, src, 0
1328 // with
1329 // src
1330 instruction->ReplaceWith(input_other);
1331 instruction->GetBlock()->RemoveInstruction(instruction);
1332 return;
1333 }
1334
1335 // We assume that GVN has run before, so we only perform a pointer comparison.
1336 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001337 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001338 if (instruction->GetLeft() == instruction->GetRight()) {
1339 // Replace code looking like
1340 // OR dst, src, src
1341 // with
1342 // src
1343 instruction->ReplaceWith(instruction->GetLeft());
1344 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001345 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001346 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001347
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001348 if (TryDeMorganNegationFactoring(instruction)) return;
1349
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001350 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001351}
1352
1353void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1354 VisitShift(instruction);
1355}
1356
1357void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1358 VisitShift(instruction);
1359}
1360
1361void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1362 HConstant* input_cst = instruction->GetConstantRight();
1363 HInstruction* input_other = instruction->GetLeastConstantLeft();
1364
Serguei Katkov115b53f2015-08-05 17:03:30 +06001365 Primitive::Type type = instruction->GetType();
1366 if (Primitive::IsFloatingPointType(type)) {
1367 return;
1368 }
1369
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001370 if ((input_cst != nullptr) && input_cst->IsZero()) {
1371 // Replace code looking like
1372 // SUB dst, src, 0
1373 // with
1374 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001375 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1376 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1377 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001378 instruction->ReplaceWith(input_other);
1379 instruction->GetBlock()->RemoveInstruction(instruction);
1380 return;
1381 }
1382
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001383 HBasicBlock* block = instruction->GetBlock();
1384 ArenaAllocator* allocator = GetGraph()->GetArena();
1385
Alexandre Rames188d4312015-04-09 18:30:21 +01001386 HInstruction* left = instruction->GetLeft();
1387 HInstruction* right = instruction->GetRight();
1388 if (left->IsConstant()) {
1389 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001390 // Replace code looking like
1391 // SUB dst, 0, src
1392 // with
1393 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001394 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001395 // `x` is `0.0`, the former expression yields `0.0`, while the later
1396 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001397 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001398 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001399 RecordSimplification();
1400 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001401 }
1402 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001403
1404 if (left->IsNeg() && right->IsNeg()) {
1405 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1406 return;
1407 }
1408 }
1409
1410 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1411 // Replace code looking like
1412 // NEG tmp, b
1413 // SUB dst, a, tmp
1414 // with
1415 // ADD dst, a, b
1416 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1417 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1418 RecordSimplification();
1419 right->GetBlock()->RemoveInstruction(right);
1420 return;
1421 }
1422
1423 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1424 // Replace code looking like
1425 // NEG tmp, a
1426 // SUB dst, tmp, b
1427 // with
1428 // ADD tmp, a, b
1429 // NEG dst, tmp
1430 // The second version is not intrinsically better, but enables more
1431 // transformations.
1432 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1433 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1434 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1435 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1436 instruction->ReplaceWith(neg);
1437 instruction->GetBlock()->RemoveInstruction(instruction);
1438 RecordSimplification();
1439 left->GetBlock()->RemoveInstruction(left);
1440 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001441}
1442
1443void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1444 VisitShift(instruction);
1445}
1446
1447void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1448 HConstant* input_cst = instruction->GetConstantRight();
1449 HInstruction* input_other = instruction->GetLeastConstantLeft();
1450
1451 if ((input_cst != nullptr) && input_cst->IsZero()) {
1452 // Replace code looking like
1453 // XOR dst, src, 0
1454 // with
1455 // src
1456 instruction->ReplaceWith(input_other);
1457 instruction->GetBlock()->RemoveInstruction(instruction);
1458 return;
1459 }
1460
1461 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1462 // Replace code looking like
1463 // XOR dst, src, 0xFFF...FF
1464 // with
1465 // NOT dst, src
1466 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1467 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001468 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001469 return;
1470 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001471
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001472 HInstruction* left = instruction->GetLeft();
1473 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001474 if (((left->IsNot() && right->IsNot()) ||
1475 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001476 left->HasOnlyOneNonEnvironmentUse() &&
1477 right->HasOnlyOneNonEnvironmentUse()) {
1478 // Replace code looking like
1479 // NOT nota, a
1480 // NOT notb, b
1481 // XOR dst, nota, notb
1482 // with
1483 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001484 instruction->ReplaceInput(left->InputAt(0), 0);
1485 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001486 left->GetBlock()->RemoveInstruction(left);
1487 right->GetBlock()->RemoveInstruction(right);
1488 RecordSimplification();
1489 return;
1490 }
1491
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001492 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001493}
1494
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001495void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1496 HInstruction* argument = instruction->InputAt(1);
1497 HInstruction* receiver = instruction->InputAt(0);
1498 if (receiver == argument) {
1499 // Because String.equals is an instance call, the receiver is
1500 // a null check if we don't know it's null. The argument however, will
1501 // be the actual object. So we cannot end up in a situation where both
1502 // are equal but could be null.
1503 DCHECK(CanEnsureNotNullAt(argument, instruction));
1504 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1505 instruction->GetBlock()->RemoveInstruction(instruction);
1506 } else {
1507 StringEqualsOptimizations optimizations(instruction);
1508 if (CanEnsureNotNullAt(argument, instruction)) {
1509 optimizations.SetArgumentNotNull();
1510 }
1511 ScopedObjectAccess soa(Thread::Current());
1512 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1513 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1514 optimizations.SetArgumentIsString();
1515 }
1516 }
1517}
1518
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001519void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1520 DCHECK(invoke->IsInvokeStaticOrDirect());
1521 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001522 HInstruction* value = invoke->InputAt(0);
1523 HInstruction* distance = invoke->InputAt(1);
1524 // Replace the invoke with an HRor.
1525 if (is_left) {
1526 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1527 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1528 }
1529 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1530 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1531 // Remove ClinitCheck and LoadClass, if possible.
1532 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1533 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1534 clinit->GetBlock()->RemoveInstruction(clinit);
1535 HInstruction* ldclass = clinit->InputAt(0);
1536 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1537 ldclass->GetBlock()->RemoveInstruction(ldclass);
1538 }
1539 }
1540}
1541
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001542static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1543 if (potential_length->IsArrayLength()) {
1544 return potential_length->InputAt(0) == potential_array;
1545 }
1546
1547 if (potential_array->IsNewArray()) {
1548 return potential_array->InputAt(0) == potential_length;
1549 }
1550
1551 return false;
1552}
1553
1554void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1555 HInstruction* source = instruction->InputAt(0);
1556 HInstruction* destination = instruction->InputAt(2);
1557 HInstruction* count = instruction->InputAt(4);
1558 SystemArrayCopyOptimizations optimizations(instruction);
1559 if (CanEnsureNotNullAt(source, instruction)) {
1560 optimizations.SetSourceIsNotNull();
1561 }
1562 if (CanEnsureNotNullAt(destination, instruction)) {
1563 optimizations.SetDestinationIsNotNull();
1564 }
1565 if (destination == source) {
1566 optimizations.SetDestinationIsSource();
1567 }
1568
1569 if (IsArrayLengthOf(count, source)) {
1570 optimizations.SetCountIsSourceLength();
1571 }
1572
1573 if (IsArrayLengthOf(count, destination)) {
1574 optimizations.SetCountIsDestinationLength();
1575 }
1576
1577 {
1578 ScopedObjectAccess soa(Thread::Current());
1579 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1580 if (destination_rti.IsValid()) {
1581 if (destination_rti.IsObjectArray()) {
1582 if (destination_rti.IsExact()) {
1583 optimizations.SetDoesNotNeedTypeCheck();
1584 }
1585 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001586 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001587 if (destination_rti.IsPrimitiveArrayClass()) {
1588 optimizations.SetDestinationIsPrimitiveArray();
1589 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1590 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001591 }
1592 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001593 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1594 if (source_rti.IsValid()) {
1595 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1596 optimizations.SetDoesNotNeedTypeCheck();
1597 }
1598 if (source_rti.IsPrimitiveArrayClass()) {
1599 optimizations.SetSourceIsPrimitiveArray();
1600 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1601 optimizations.SetSourceIsNonPrimitiveArray();
1602 }
1603 }
1604 }
1605}
1606
Aart Bika19616e2016-02-01 18:57:58 -08001607void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1608 DCHECK(invoke->IsInvokeStaticOrDirect());
1609 uint32_t dex_pc = invoke->GetDexPc();
1610 HInstruction* left = invoke->InputAt(0);
1611 HInstruction* right;
1612 Primitive::Type type = left->GetType();
1613 if (!is_signum) {
1614 right = invoke->InputAt(1);
1615 } else if (type == Primitive::kPrimLong) {
1616 right = GetGraph()->GetLongConstant(0);
1617 } else {
1618 right = GetGraph()->GetIntConstant(0);
1619 }
1620 HCompare* compare = new (GetGraph()->GetArena())
1621 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1622 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1623}
1624
Aart Bik75a38b22016-02-17 10:41:50 -08001625void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1626 DCHECK(invoke->IsInvokeStaticOrDirect());
1627 uint32_t dex_pc = invoke->GetDexPc();
1628 // IsNaN(x) is the same as x != x.
1629 HInstruction* x = invoke->InputAt(0);
1630 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001631 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001632 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1633}
1634
Aart Bik2a6aad92016-02-25 11:32:32 -08001635void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1636 DCHECK(invoke->IsInvokeStaticOrDirect());
1637 uint32_t dex_pc = invoke->GetDexPc();
1638 HInstruction* x = invoke->InputAt(0);
1639 Primitive::Type type = x->GetType();
1640 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1641 HInstruction* nan;
1642 if (type == Primitive::kPrimDouble) {
1643 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1644 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1645 kNeedsEnvironmentOrCache,
1646 kNoSideEffects,
1647 kNoThrow);
1648 } else {
1649 DCHECK_EQ(type, Primitive::kPrimFloat);
1650 nan = GetGraph()->GetIntConstant(0x7fc00000);
1651 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1652 kNeedsEnvironmentOrCache,
1653 kNoSideEffects,
1654 kNoThrow);
1655 }
1656 // Test IsNaN(x), which is the same as x != x.
1657 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1658 condition->SetBias(ComparisonBias::kLtBias);
1659 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1660 // Select between the two.
1661 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1662 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1663 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1664}
1665
Aart Bik11932592016-03-08 12:42:25 -08001666void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1667 uint32_t dex_pc = invoke->GetDexPc();
1668 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1669 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1670}
1671
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001672void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001673 switch (instruction->GetIntrinsic()) {
1674 case Intrinsics::kStringEquals:
1675 SimplifyStringEquals(instruction);
1676 break;
1677 case Intrinsics::kSystemArrayCopy:
1678 SimplifySystemArrayCopy(instruction);
1679 break;
1680 case Intrinsics::kIntegerRotateRight:
1681 case Intrinsics::kLongRotateRight:
1682 SimplifyRotate(instruction, false);
1683 break;
1684 case Intrinsics::kIntegerRotateLeft:
1685 case Intrinsics::kLongRotateLeft:
1686 SimplifyRotate(instruction, true);
1687 break;
1688 case Intrinsics::kIntegerCompare:
1689 case Intrinsics::kLongCompare:
1690 SimplifyCompare(instruction, /* is_signum */ false);
1691 break;
1692 case Intrinsics::kIntegerSignum:
1693 case Intrinsics::kLongSignum:
1694 SimplifyCompare(instruction, /* is_signum */ true);
1695 break;
1696 case Intrinsics::kFloatIsNaN:
1697 case Intrinsics::kDoubleIsNaN:
1698 SimplifyIsNaN(instruction);
1699 break;
1700 case Intrinsics::kFloatFloatToIntBits:
1701 case Intrinsics::kDoubleDoubleToLongBits:
1702 SimplifyFP2Int(instruction);
1703 break;
Aart Bik11932592016-03-08 12:42:25 -08001704 case Intrinsics::kUnsafeLoadFence:
1705 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1706 break;
1707 case Intrinsics::kUnsafeStoreFence:
1708 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1709 break;
1710 case Intrinsics::kUnsafeFullFence:
1711 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1712 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001713 default:
1714 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001715 }
1716}
1717
Aart Bikbb245d12015-10-19 11:05:03 -07001718void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1719 HInstruction* cond = deoptimize->InputAt(0);
1720 if (cond->IsConstant()) {
1721 if (cond->AsIntConstant()->IsZero()) {
1722 // Never deopt: instruction can be removed.
1723 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1724 } else {
1725 // Always deopt.
1726 }
1727 }
1728}
1729
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001730} // namespace art