blob: 09f841ca009f3f42afcb4d334f0d3fc5f2e2306e [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
Vladimir Markoa65ed302016-03-14 21:21:29 +0000472 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
473 // the return value check with the `outcome` check, b/27651442 .
474 bool outcome = false;
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);
478 if (stats_ != nullptr) {
479 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
480 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700481 if (!load_class->HasUses()) {
482 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
483 // However, here we know that it cannot because the checkcast was successfull, hence
484 // the class was already loaded.
485 load_class->GetBlock()->RemoveInstruction(load_class);
486 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100487 } else {
488 // Don't do anything for exceptional cases for now. Ideally we should remove
489 // all instructions and blocks this instruction dominates.
490 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000491 }
492}
493
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100494void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100495 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100496 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
497 if (load_class->NeedsAccessCheck()) {
498 // If we need to perform an access check we cannot remove the instruction.
499 return;
500 }
501
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100502 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100503 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100504 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100505 instruction->ClearMustDoNullCheck();
506 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100507
508 HGraph* graph = GetGraph();
509 if (object->IsNullConstant()) {
510 instruction->ReplaceWith(graph->GetIntConstant(0));
511 instruction->GetBlock()->RemoveInstruction(instruction);
512 RecordSimplification();
513 return;
514 }
515
Vladimir Marko24bd8952016-03-15 10:40:33 +0000516 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
517 // the return value check with the `outcome` check, b/27651442 .
518 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700519 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100520 if (outcome && can_be_null) {
521 // Type test will succeed, we just need a null test.
522 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
523 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
524 instruction->ReplaceWith(test);
525 } else {
526 // We've statically determined the result of the instanceof.
527 instruction->ReplaceWith(graph->GetIntConstant(outcome));
528 }
529 RecordSimplification();
530 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700531 if (outcome && !load_class->HasUses()) {
532 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
533 // However, here we know that it cannot because the instanceof check was successfull, hence
534 // the class was already loaded.
535 load_class->GetBlock()->RemoveInstruction(load_class);
536 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100537 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100538}
539
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100540void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
541 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100542 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100543 instruction->ClearValueCanBeNull();
544 }
545}
546
547void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
548 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100549 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100550 instruction->ClearValueCanBeNull();
551 }
552}
553
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000554void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100555 HBasicBlock* block = check->GetBlock();
556 // Currently always keep the suspend check at entry.
557 if (block->IsEntryBlock()) return;
558
559 // Currently always keep suspend checks at loop entry.
560 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
561 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
562 return;
563 }
564
565 // Remove the suspend check that was added at build time for the baseline
566 // compiler.
567 block->RemoveInstruction(check);
568}
569
Anton Shaminbdd79352016-02-15 12:48:36 +0600570static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
571 HInstruction *lhs = cond->InputAt(0);
572 HInstruction *rhs = cond->InputAt(1);
573 switch (cond->GetKind()) {
574 case HInstruction::kEqual:
575 return new (arena) HEqual(rhs, lhs);
576 case HInstruction::kNotEqual:
577 return new (arena) HNotEqual(rhs, lhs);
578 case HInstruction::kLessThan:
579 return new (arena) HGreaterThan(rhs, lhs);
580 case HInstruction::kLessThanOrEqual:
581 return new (arena) HGreaterThanOrEqual(rhs, lhs);
582 case HInstruction::kGreaterThan:
583 return new (arena) HLessThan(rhs, lhs);
584 case HInstruction::kGreaterThanOrEqual:
585 return new (arena) HLessThanOrEqual(rhs, lhs);
586 case HInstruction::kBelow:
587 return new (arena) HAbove(rhs, lhs);
588 case HInstruction::kBelowOrEqual:
589 return new (arena) HAboveOrEqual(rhs, lhs);
590 case HInstruction::kAbove:
591 return new (arena) HBelow(rhs, lhs);
592 case HInstruction::kAboveOrEqual:
593 return new (arena) HBelowOrEqual(rhs, lhs);
594 default:
595 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
596 }
597 return nullptr;
598}
599
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000600void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100601 HInstruction* input_const = equal->GetConstantRight();
602 if (input_const != nullptr) {
603 HInstruction* input_value = equal->GetLeastConstantLeft();
604 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
605 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100606 // We are comparing the boolean to a constant which is of type int and can
607 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100608 if (input_const->AsIntConstant()->IsOne()) {
609 // Replace (bool_value == true) with bool_value
610 equal->ReplaceWith(input_value);
611 block->RemoveInstruction(equal);
612 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100613 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500614 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
615 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100616 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100617 } else {
618 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
619 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
620 block->RemoveInstruction(equal);
621 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100622 }
Mark Mendellc4701932015-04-10 13:18:51 -0400623 } else {
624 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100625 }
Mark Mendellc4701932015-04-10 13:18:51 -0400626 } else {
627 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100628 }
629}
630
David Brazdil0d13fee2015-04-17 14:52:19 +0100631void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
632 HInstruction* input_const = not_equal->GetConstantRight();
633 if (input_const != nullptr) {
634 HInstruction* input_value = not_equal->GetLeastConstantLeft();
635 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
636 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100637 // We are comparing the boolean to a constant which is of type int and can
638 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100639 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500640 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
641 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100642 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100643 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100644 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100645 not_equal->ReplaceWith(input_value);
646 block->RemoveInstruction(not_equal);
647 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100648 } else {
649 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
650 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
651 block->RemoveInstruction(not_equal);
652 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100653 }
Mark Mendellc4701932015-04-10 13:18:51 -0400654 } else {
655 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100656 }
Mark Mendellc4701932015-04-10 13:18:51 -0400657 } else {
658 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100659 }
660}
661
662void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000663 HInstruction* input = bool_not->InputAt(0);
664 HInstruction* replace_with = nullptr;
665
666 if (input->IsIntConstant()) {
667 // Replace !(true/false) with false/true.
668 if (input->AsIntConstant()->IsOne()) {
669 replace_with = GetGraph()->GetIntConstant(0);
670 } else {
671 DCHECK(input->AsIntConstant()->IsZero());
672 replace_with = GetGraph()->GetIntConstant(1);
673 }
674 } else if (input->IsBooleanNot()) {
675 // Replace (!(!bool_value)) with bool_value.
676 replace_with = input->InputAt(0);
677 } else if (input->IsCondition() &&
678 // Don't change FP compares. The definition of compares involving
679 // NaNs forces the compares to be done as written by the user.
680 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
681 // Replace condition with its opposite.
682 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
683 }
684
685 if (replace_with != nullptr) {
686 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100687 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000688 RecordSimplification();
689 }
690}
691
692void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
693 HInstruction* replace_with = nullptr;
694 HInstruction* condition = select->GetCondition();
695 HInstruction* true_value = select->GetTrueValue();
696 HInstruction* false_value = select->GetFalseValue();
697
698 if (condition->IsBooleanNot()) {
699 // Change ((!cond) ? x : y) to (cond ? y : x).
700 condition = condition->InputAt(0);
701 std::swap(true_value, false_value);
702 select->ReplaceInput(false_value, 0);
703 select->ReplaceInput(true_value, 1);
704 select->ReplaceInput(condition, 2);
705 RecordSimplification();
706 }
707
708 if (true_value == false_value) {
709 // Replace (cond ? x : x) with (x).
710 replace_with = true_value;
711 } else if (condition->IsIntConstant()) {
712 if (condition->AsIntConstant()->IsOne()) {
713 // Replace (true ? x : y) with (x).
714 replace_with = true_value;
715 } else {
716 // Replace (false ? x : y) with (y).
717 DCHECK(condition->AsIntConstant()->IsZero());
718 replace_with = false_value;
719 }
720 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
721 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
722 // Replace (cond ? true : false) with (cond).
723 replace_with = condition;
724 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
725 // Replace (cond ? false : true) with (!cond).
726 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
727 }
728 }
729
730 if (replace_with != nullptr) {
731 select->ReplaceWith(replace_with);
732 select->GetBlock()->RemoveInstruction(select);
733 RecordSimplification();
734 }
735}
736
737void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
738 HInstruction* condition = instruction->InputAt(0);
739 if (condition->IsBooleanNot()) {
740 // Swap successors if input is negated.
741 instruction->ReplaceInput(condition->InputAt(0), 0);
742 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100743 RecordSimplification();
744 }
745}
746
Mingyao Yang0304e182015-01-30 16:41:29 -0800747void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
748 HInstruction* input = instruction->InputAt(0);
749 // If the array is a NewArray with constant size, replace the array length
750 // with the constant instruction. This helps the bounds check elimination phase.
751 if (input->IsNewArray()) {
752 input = input->InputAt(0);
753 if (input->IsIntConstant()) {
754 instruction->ReplaceWith(input);
755 }
756 }
757}
758
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000759void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000760 HInstruction* value = instruction->GetValue();
761 if (value->GetType() != Primitive::kPrimNot) return;
762
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100763 if (CanEnsureNotNullAt(value, instruction)) {
764 instruction->ClearValueCanBeNull();
765 }
766
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000767 if (value->IsArrayGet()) {
768 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
769 // If the code is just swapping elements in the array, no need for a type check.
770 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100771 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000772 }
773 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100774
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100775 if (value->IsNullConstant()) {
776 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100777 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100778 }
779
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100780 ScopedObjectAccess soa(Thread::Current());
781 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
782 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
783 if (!array_rti.IsValid()) {
784 return;
785 }
786
787 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
788 instruction->ClearNeedsTypeCheck();
789 return;
790 }
791
792 if (array_rti.IsObjectArray()) {
793 if (array_rti.IsExact()) {
794 instruction->ClearNeedsTypeCheck();
795 return;
796 }
797 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100798 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000799}
800
Vladimir Markob52bbde2016-02-12 12:06:05 +0000801static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
802 // Besides conversion to the same type, widening integral conversions are implicit,
803 // excluding conversions to long and the byte->char conversion where we need to
804 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
805 return result_type == input_type ||
806 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
807 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
808 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
809 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
810}
811
812static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
813 // The conversion to a larger type is loss-less with the exception of two cases,
814 // - conversion to char, the only unsigned type, where we may lose some bits, and
815 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
816 // For integral to FP conversions this holds because the FP mantissa is large enough.
817 DCHECK_NE(input_type, result_type);
818 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
819 result_type != Primitive::kPrimChar &&
820 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
821}
822
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000823void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000824 HInstruction* input = instruction->GetInput();
825 Primitive::Type input_type = input->GetType();
826 Primitive::Type result_type = instruction->GetResultType();
827 if (IsTypeConversionImplicit(input_type, result_type)) {
828 // Remove the implicit conversion; this includes conversion to the same type.
829 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000830 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000831 RecordSimplification();
832 return;
833 }
834
835 if (input->IsTypeConversion()) {
836 HTypeConversion* input_conversion = input->AsTypeConversion();
837 HInstruction* original_input = input_conversion->GetInput();
838 Primitive::Type original_type = original_input->GetType();
839
840 // When the first conversion is lossless, a direct conversion from the original type
841 // to the final type yields the same result, even for a lossy second conversion, for
842 // example float->double->int or int->double->float.
843 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
844
845 // For integral conversions, see if the first conversion loses only bits that the second
846 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
847 // conversion yields the same result, for example long->int->short or int->char->short.
848 bool integral_conversions_with_non_widening_second =
849 Primitive::IsIntegralType(input_type) &&
850 Primitive::IsIntegralType(original_type) &&
851 Primitive::IsIntegralType(result_type) &&
852 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
853
854 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
855 // If the merged conversion is implicit, do the simplification unconditionally.
856 if (IsTypeConversionImplicit(original_type, result_type)) {
857 instruction->ReplaceWith(original_input);
858 instruction->GetBlock()->RemoveInstruction(instruction);
859 if (!input_conversion->HasUses()) {
860 // Don't wait for DCE.
861 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
862 }
863 RecordSimplification();
864 return;
865 }
866 // Otherwise simplify only if the first conversion has no other use.
867 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
868 input_conversion->ReplaceWith(original_input);
869 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
870 RecordSimplification();
871 return;
872 }
873 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000874 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000875 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.
Vladimir Marko625090f2016-03-14 18:00:05 +0000884 HInstruction* original_input = input_and->GetLeastConstantLeft();
885 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
886 instruction->ReplaceWith(original_input);
887 instruction->GetBlock()->RemoveInstruction(instruction);
888 RecordSimplification();
889 return;
890 } else if (input->HasOnlyOneNonEnvironmentUse()) {
891 input_and->ReplaceWith(original_input);
892 input_and->GetBlock()->RemoveInstruction(input_and);
893 RecordSimplification();
894 return;
895 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000896 }
897 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000898 }
899}
900
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000901void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
902 HConstant* input_cst = instruction->GetConstantRight();
903 HInstruction* input_other = instruction->GetLeastConstantLeft();
904 if ((input_cst != nullptr) && input_cst->IsZero()) {
905 // Replace code looking like
906 // ADD dst, src, 0
907 // with
908 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600909 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
910 // `x` is `-0.0`, the former expression yields `0.0`, while the later
911 // yields `-0.0`.
912 if (Primitive::IsIntegralType(instruction->GetType())) {
913 instruction->ReplaceWith(input_other);
914 instruction->GetBlock()->RemoveInstruction(instruction);
915 return;
916 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100917 }
918
919 HInstruction* left = instruction->GetLeft();
920 HInstruction* right = instruction->GetRight();
921 bool left_is_neg = left->IsNeg();
922 bool right_is_neg = right->IsNeg();
923
924 if (left_is_neg && right_is_neg) {
925 if (TryMoveNegOnInputsAfterBinop(instruction)) {
926 return;
927 }
928 }
929
930 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
931 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
932 // Replace code looking like
933 // NEG tmp, b
934 // ADD dst, a, tmp
935 // with
936 // SUB dst, a, b
937 // We do not perform the optimization if the input negation has environment
938 // uses or multiple non-environment uses as it could lead to worse code. In
939 // particular, we do not want the live range of `b` to be extended if we are
940 // not sure the initial 'NEG' instruction can be removed.
941 HInstruction* other = left_is_neg ? right : left;
942 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
943 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
944 RecordSimplification();
945 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000946 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000947 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000948
949 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000950}
951
952void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
953 HConstant* input_cst = instruction->GetConstantRight();
954 HInstruction* input_other = instruction->GetLeastConstantLeft();
955
Vladimir Marko452c1b62015-09-25 14:44:17 +0100956 if (input_cst != nullptr) {
957 int64_t value = Int64FromConstant(input_cst);
958 if (value == -1) {
959 // Replace code looking like
960 // AND dst, src, 0xFFF...FF
961 // with
962 // src
963 instruction->ReplaceWith(input_other);
964 instruction->GetBlock()->RemoveInstruction(instruction);
965 RecordSimplification();
966 return;
967 }
968 // Eliminate And from UShr+And if the And-mask contains all the bits that
969 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
970 // precisely clears the shifted-in sign bits.
971 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
972 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
973 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
974 size_t num_tail_bits_set = CTZ(value + 1);
975 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
976 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
977 instruction->ReplaceWith(input_other);
978 instruction->GetBlock()->RemoveInstruction(instruction);
979 RecordSimplification();
980 return;
981 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
982 input_other->HasOnlyOneNonEnvironmentUse()) {
983 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
984 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
985 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
986 input_other->InputAt(0),
987 input_other->InputAt(1),
988 input_other->GetDexPc());
989 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
990 input_other->GetBlock()->RemoveInstruction(input_other);
991 RecordSimplification();
992 return;
993 }
994 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000995 }
996
997 // We assume that GVN has run before, so we only perform a pointer comparison.
998 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100999 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001000 if (instruction->GetLeft() == instruction->GetRight()) {
1001 // Replace code looking like
1002 // AND dst, src, src
1003 // with
1004 // src
1005 instruction->ReplaceWith(instruction->GetLeft());
1006 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001007 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001008 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001009
1010 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001011}
1012
Mark Mendellc4701932015-04-10 13:18:51 -04001013void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1014 VisitCondition(condition);
1015}
1016
1017void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1018 VisitCondition(condition);
1019}
1020
1021void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1022 VisitCondition(condition);
1023}
1024
1025void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1026 VisitCondition(condition);
1027}
1028
Anton Shaminbdd79352016-02-15 12:48:36 +06001029void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1030 VisitCondition(condition);
1031}
1032
1033void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1034 VisitCondition(condition);
1035}
1036
1037void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1038 VisitCondition(condition);
1039}
1040
1041void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1042 VisitCondition(condition);
1043}
Aart Bike9f37602015-10-09 11:15:55 -07001044
Mark Mendellc4701932015-04-10 13:18:51 -04001045void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001046 // Reverse condition if left is constant. Our code generators prefer constant
1047 // on the right hand side.
1048 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1049 HBasicBlock* block = condition->GetBlock();
1050 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1051 // If it is a fp we must set the opposite bias.
1052 if (replacement != nullptr) {
1053 if (condition->IsLtBias()) {
1054 replacement->SetBias(ComparisonBias::kGtBias);
1055 } else if (condition->IsGtBias()) {
1056 replacement->SetBias(ComparisonBias::kLtBias);
1057 }
1058 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1059 RecordSimplification();
1060
1061 condition = replacement;
1062 }
1063 }
Mark Mendellc4701932015-04-10 13:18:51 -04001064
Mark Mendellc4701932015-04-10 13:18:51 -04001065 HInstruction* left = condition->GetLeft();
1066 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001067
1068 // Try to fold an HCompare into this HCondition.
1069
Mark Mendellc4701932015-04-10 13:18:51 -04001070 // We can only replace an HCondition which compares a Compare to 0.
1071 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1072 // condition with a long, float or double comparison as input.
1073 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1074 // Conversion is not possible.
1075 return;
1076 }
1077
1078 // Is the Compare only used for this purpose?
1079 if (!left->GetUses().HasOnlyOneUse()) {
1080 // Someone else also wants the result of the compare.
1081 return;
1082 }
1083
1084 if (!left->GetEnvUses().IsEmpty()) {
1085 // There is a reference to the compare result in an environment. Do we really need it?
1086 if (GetGraph()->IsDebuggable()) {
1087 return;
1088 }
1089
1090 // We have to ensure that there are no deopt points in the sequence.
1091 if (left->HasAnyEnvironmentUseBefore(condition)) {
1092 return;
1093 }
1094 }
1095
1096 // Clean up any environment uses from the HCompare, if any.
1097 left->RemoveEnvironmentUsers();
1098
1099 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1100 condition->SetBias(left->AsCompare()->GetBias());
1101
1102 // Replace the operands of the HCondition.
1103 condition->ReplaceInput(left->InputAt(0), 0);
1104 condition->ReplaceInput(left->InputAt(1), 1);
1105
1106 // Remove the HCompare.
1107 left->GetBlock()->RemoveInstruction(left);
1108
1109 RecordSimplification();
1110}
1111
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001112void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1113 HConstant* input_cst = instruction->GetConstantRight();
1114 HInstruction* input_other = instruction->GetLeastConstantLeft();
1115 Primitive::Type type = instruction->GetType();
1116
1117 if ((input_cst != nullptr) && input_cst->IsOne()) {
1118 // Replace code looking like
1119 // DIV dst, src, 1
1120 // with
1121 // src
1122 instruction->ReplaceWith(input_other);
1123 instruction->GetBlock()->RemoveInstruction(instruction);
1124 return;
1125 }
1126
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001127 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001128 // Replace code looking like
1129 // DIV dst, src, -1
1130 // with
1131 // NEG dst, src
1132 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001133 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001134 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001135 return;
1136 }
1137
1138 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1139 // Try replacing code looking like
1140 // DIV dst, src, constant
1141 // with
1142 // MUL dst, src, 1 / constant
1143 HConstant* reciprocal = nullptr;
1144 if (type == Primitive::Primitive::kPrimDouble) {
1145 double value = input_cst->AsDoubleConstant()->GetValue();
1146 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1147 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1148 }
1149 } else {
1150 DCHECK_EQ(type, Primitive::kPrimFloat);
1151 float value = input_cst->AsFloatConstant()->GetValue();
1152 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1153 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1154 }
1155 }
1156
1157 if (reciprocal != nullptr) {
1158 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1159 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1160 RecordSimplification();
1161 return;
1162 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001163 }
1164}
1165
1166void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1167 HConstant* input_cst = instruction->GetConstantRight();
1168 HInstruction* input_other = instruction->GetLeastConstantLeft();
1169 Primitive::Type type = instruction->GetType();
1170 HBasicBlock* block = instruction->GetBlock();
1171 ArenaAllocator* allocator = GetGraph()->GetArena();
1172
1173 if (input_cst == nullptr) {
1174 return;
1175 }
1176
1177 if (input_cst->IsOne()) {
1178 // Replace code looking like
1179 // MUL dst, src, 1
1180 // with
1181 // src
1182 instruction->ReplaceWith(input_other);
1183 instruction->GetBlock()->RemoveInstruction(instruction);
1184 return;
1185 }
1186
1187 if (input_cst->IsMinusOne() &&
1188 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1189 // Replace code looking like
1190 // MUL dst, src, -1
1191 // with
1192 // NEG dst, src
1193 HNeg* neg = new (allocator) HNeg(type, input_other);
1194 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001195 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001196 return;
1197 }
1198
1199 if (Primitive::IsFloatingPointType(type) &&
1200 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1201 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1202 // Replace code looking like
1203 // FP_MUL dst, src, 2.0
1204 // with
1205 // FP_ADD dst, src, src
1206 // The 'int' and 'long' cases are handled below.
1207 block->ReplaceAndRemoveInstructionWith(instruction,
1208 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001209 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001210 return;
1211 }
1212
1213 if (Primitive::IsIntOrLongType(type)) {
1214 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001215 // Even though constant propagation also takes care of the zero case, other
1216 // optimizations can lead to having a zero multiplication.
1217 if (factor == 0) {
1218 // Replace code looking like
1219 // MUL dst, src, 0
1220 // with
1221 // 0
1222 instruction->ReplaceWith(input_cst);
1223 instruction->GetBlock()->RemoveInstruction(instruction);
1224 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001225 // Replace code looking like
1226 // MUL dst, src, pow_of_2
1227 // with
1228 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001229 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001230 HShl* shl = new(allocator) HShl(type, input_other, shift);
1231 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001232 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001233 } else if (IsPowerOfTwo(factor - 1)) {
1234 // Transform code looking like
1235 // MUL dst, src, (2^n + 1)
1236 // into
1237 // SHL tmp, src, n
1238 // ADD dst, src, tmp
1239 HShl* shl = new (allocator) HShl(type,
1240 input_other,
1241 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1242 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1243
1244 block->InsertInstructionBefore(shl, instruction);
1245 block->ReplaceAndRemoveInstructionWith(instruction, add);
1246 RecordSimplification();
1247 } else if (IsPowerOfTwo(factor + 1)) {
1248 // Transform code looking like
1249 // MUL dst, src, (2^n - 1)
1250 // into
1251 // SHL tmp, src, n
1252 // SUB dst, tmp, src
1253 HShl* shl = new (allocator) HShl(type,
1254 input_other,
1255 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1256 HSub* sub = new (allocator) HSub(type, shl, input_other);
1257
1258 block->InsertInstructionBefore(shl, instruction);
1259 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1260 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001261 }
1262 }
1263}
1264
Alexandre Rames188d4312015-04-09 18:30:21 +01001265void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1266 HInstruction* input = instruction->GetInput();
1267 if (input->IsNeg()) {
1268 // Replace code looking like
1269 // NEG tmp, src
1270 // NEG dst, tmp
1271 // with
1272 // src
1273 HNeg* previous_neg = input->AsNeg();
1274 instruction->ReplaceWith(previous_neg->GetInput());
1275 instruction->GetBlock()->RemoveInstruction(instruction);
1276 // We perform the optimization even if the input negation has environment
1277 // uses since it allows removing the current instruction. But we only delete
1278 // the input negation only if it is does not have any uses left.
1279 if (!previous_neg->HasUses()) {
1280 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1281 }
1282 RecordSimplification();
1283 return;
1284 }
1285
Serguei Katkov339dfc22015-04-20 12:29:32 +06001286 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1287 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001288 // Replace code looking like
1289 // SUB tmp, a, b
1290 // NEG dst, tmp
1291 // with
1292 // SUB dst, b, a
1293 // We do not perform the optimization if the input subtraction has
1294 // environment uses or multiple non-environment uses as it could lead to
1295 // worse code. In particular, we do not want the live ranges of `a` and `b`
1296 // to be extended if we are not sure the initial 'SUB' instruction can be
1297 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001298 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001299 HSub* sub = input->AsSub();
1300 HSub* new_sub =
1301 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1302 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1303 if (!sub->HasUses()) {
1304 sub->GetBlock()->RemoveInstruction(sub);
1305 }
1306 RecordSimplification();
1307 }
1308}
1309
1310void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1311 HInstruction* input = instruction->GetInput();
1312 if (input->IsNot()) {
1313 // Replace code looking like
1314 // NOT tmp, src
1315 // NOT dst, tmp
1316 // with
1317 // src
1318 // We perform the optimization even if the input negation has environment
1319 // uses since it allows removing the current instruction. But we only delete
1320 // the input negation only if it is does not have any uses left.
1321 HNot* previous_not = input->AsNot();
1322 instruction->ReplaceWith(previous_not->GetInput());
1323 instruction->GetBlock()->RemoveInstruction(instruction);
1324 if (!previous_not->HasUses()) {
1325 previous_not->GetBlock()->RemoveInstruction(previous_not);
1326 }
1327 RecordSimplification();
1328 }
1329}
1330
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001331void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1332 HConstant* input_cst = instruction->GetConstantRight();
1333 HInstruction* input_other = instruction->GetLeastConstantLeft();
1334
1335 if ((input_cst != nullptr) && input_cst->IsZero()) {
1336 // Replace code looking like
1337 // OR dst, src, 0
1338 // with
1339 // src
1340 instruction->ReplaceWith(input_other);
1341 instruction->GetBlock()->RemoveInstruction(instruction);
1342 return;
1343 }
1344
1345 // We assume that GVN has run before, so we only perform a pointer comparison.
1346 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001347 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001348 if (instruction->GetLeft() == instruction->GetRight()) {
1349 // Replace code looking like
1350 // OR dst, src, src
1351 // with
1352 // src
1353 instruction->ReplaceWith(instruction->GetLeft());
1354 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001355 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001356 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001357
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001358 if (TryDeMorganNegationFactoring(instruction)) return;
1359
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001360 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001361}
1362
1363void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1364 VisitShift(instruction);
1365}
1366
1367void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1368 VisitShift(instruction);
1369}
1370
1371void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1372 HConstant* input_cst = instruction->GetConstantRight();
1373 HInstruction* input_other = instruction->GetLeastConstantLeft();
1374
Serguei Katkov115b53f2015-08-05 17:03:30 +06001375 Primitive::Type type = instruction->GetType();
1376 if (Primitive::IsFloatingPointType(type)) {
1377 return;
1378 }
1379
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001380 if ((input_cst != nullptr) && input_cst->IsZero()) {
1381 // Replace code looking like
1382 // SUB dst, src, 0
1383 // with
1384 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001385 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1386 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1387 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001388 instruction->ReplaceWith(input_other);
1389 instruction->GetBlock()->RemoveInstruction(instruction);
1390 return;
1391 }
1392
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001393 HBasicBlock* block = instruction->GetBlock();
1394 ArenaAllocator* allocator = GetGraph()->GetArena();
1395
Alexandre Rames188d4312015-04-09 18:30:21 +01001396 HInstruction* left = instruction->GetLeft();
1397 HInstruction* right = instruction->GetRight();
1398 if (left->IsConstant()) {
1399 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001400 // Replace code looking like
1401 // SUB dst, 0, src
1402 // with
1403 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001404 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001405 // `x` is `0.0`, the former expression yields `0.0`, while the later
1406 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001407 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001408 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001409 RecordSimplification();
1410 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001411 }
1412 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001413
1414 if (left->IsNeg() && right->IsNeg()) {
1415 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1416 return;
1417 }
1418 }
1419
1420 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1421 // Replace code looking like
1422 // NEG tmp, b
1423 // SUB dst, a, tmp
1424 // with
1425 // ADD dst, a, b
1426 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1427 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1428 RecordSimplification();
1429 right->GetBlock()->RemoveInstruction(right);
1430 return;
1431 }
1432
1433 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1434 // Replace code looking like
1435 // NEG tmp, a
1436 // SUB dst, tmp, b
1437 // with
1438 // ADD tmp, a, b
1439 // NEG dst, tmp
1440 // The second version is not intrinsically better, but enables more
1441 // transformations.
1442 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1443 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1444 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1445 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1446 instruction->ReplaceWith(neg);
1447 instruction->GetBlock()->RemoveInstruction(instruction);
1448 RecordSimplification();
1449 left->GetBlock()->RemoveInstruction(left);
1450 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001451}
1452
1453void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1454 VisitShift(instruction);
1455}
1456
1457void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1458 HConstant* input_cst = instruction->GetConstantRight();
1459 HInstruction* input_other = instruction->GetLeastConstantLeft();
1460
1461 if ((input_cst != nullptr) && input_cst->IsZero()) {
1462 // Replace code looking like
1463 // XOR dst, src, 0
1464 // with
1465 // src
1466 instruction->ReplaceWith(input_other);
1467 instruction->GetBlock()->RemoveInstruction(instruction);
1468 return;
1469 }
1470
1471 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1472 // Replace code looking like
1473 // XOR dst, src, 0xFFF...FF
1474 // with
1475 // NOT dst, src
1476 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1477 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001478 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001479 return;
1480 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001481
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001482 HInstruction* left = instruction->GetLeft();
1483 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001484 if (((left->IsNot() && right->IsNot()) ||
1485 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001486 left->HasOnlyOneNonEnvironmentUse() &&
1487 right->HasOnlyOneNonEnvironmentUse()) {
1488 // Replace code looking like
1489 // NOT nota, a
1490 // NOT notb, b
1491 // XOR dst, nota, notb
1492 // with
1493 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001494 instruction->ReplaceInput(left->InputAt(0), 0);
1495 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001496 left->GetBlock()->RemoveInstruction(left);
1497 right->GetBlock()->RemoveInstruction(right);
1498 RecordSimplification();
1499 return;
1500 }
1501
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001502 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001503}
1504
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001505void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1506 HInstruction* argument = instruction->InputAt(1);
1507 HInstruction* receiver = instruction->InputAt(0);
1508 if (receiver == argument) {
1509 // Because String.equals is an instance call, the receiver is
1510 // a null check if we don't know it's null. The argument however, will
1511 // be the actual object. So we cannot end up in a situation where both
1512 // are equal but could be null.
1513 DCHECK(CanEnsureNotNullAt(argument, instruction));
1514 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1515 instruction->GetBlock()->RemoveInstruction(instruction);
1516 } else {
1517 StringEqualsOptimizations optimizations(instruction);
1518 if (CanEnsureNotNullAt(argument, instruction)) {
1519 optimizations.SetArgumentNotNull();
1520 }
1521 ScopedObjectAccess soa(Thread::Current());
1522 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1523 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1524 optimizations.SetArgumentIsString();
1525 }
1526 }
1527}
1528
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001529void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1530 DCHECK(invoke->IsInvokeStaticOrDirect());
1531 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001532 HInstruction* value = invoke->InputAt(0);
1533 HInstruction* distance = invoke->InputAt(1);
1534 // Replace the invoke with an HRor.
1535 if (is_left) {
1536 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1537 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1538 }
1539 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1540 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1541 // Remove ClinitCheck and LoadClass, if possible.
1542 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1543 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1544 clinit->GetBlock()->RemoveInstruction(clinit);
1545 HInstruction* ldclass = clinit->InputAt(0);
1546 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1547 ldclass->GetBlock()->RemoveInstruction(ldclass);
1548 }
1549 }
1550}
1551
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001552static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1553 if (potential_length->IsArrayLength()) {
1554 return potential_length->InputAt(0) == potential_array;
1555 }
1556
1557 if (potential_array->IsNewArray()) {
1558 return potential_array->InputAt(0) == potential_length;
1559 }
1560
1561 return false;
1562}
1563
1564void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1565 HInstruction* source = instruction->InputAt(0);
1566 HInstruction* destination = instruction->InputAt(2);
1567 HInstruction* count = instruction->InputAt(4);
1568 SystemArrayCopyOptimizations optimizations(instruction);
1569 if (CanEnsureNotNullAt(source, instruction)) {
1570 optimizations.SetSourceIsNotNull();
1571 }
1572 if (CanEnsureNotNullAt(destination, instruction)) {
1573 optimizations.SetDestinationIsNotNull();
1574 }
1575 if (destination == source) {
1576 optimizations.SetDestinationIsSource();
1577 }
1578
1579 if (IsArrayLengthOf(count, source)) {
1580 optimizations.SetCountIsSourceLength();
1581 }
1582
1583 if (IsArrayLengthOf(count, destination)) {
1584 optimizations.SetCountIsDestinationLength();
1585 }
1586
1587 {
1588 ScopedObjectAccess soa(Thread::Current());
1589 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1590 if (destination_rti.IsValid()) {
1591 if (destination_rti.IsObjectArray()) {
1592 if (destination_rti.IsExact()) {
1593 optimizations.SetDoesNotNeedTypeCheck();
1594 }
1595 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001596 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001597 if (destination_rti.IsPrimitiveArrayClass()) {
1598 optimizations.SetDestinationIsPrimitiveArray();
1599 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1600 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001601 }
1602 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001603 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1604 if (source_rti.IsValid()) {
1605 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1606 optimizations.SetDoesNotNeedTypeCheck();
1607 }
1608 if (source_rti.IsPrimitiveArrayClass()) {
1609 optimizations.SetSourceIsPrimitiveArray();
1610 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1611 optimizations.SetSourceIsNonPrimitiveArray();
1612 }
1613 }
1614 }
1615}
1616
Aart Bika19616e2016-02-01 18:57:58 -08001617void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1618 DCHECK(invoke->IsInvokeStaticOrDirect());
1619 uint32_t dex_pc = invoke->GetDexPc();
1620 HInstruction* left = invoke->InputAt(0);
1621 HInstruction* right;
1622 Primitive::Type type = left->GetType();
1623 if (!is_signum) {
1624 right = invoke->InputAt(1);
1625 } else if (type == Primitive::kPrimLong) {
1626 right = GetGraph()->GetLongConstant(0);
1627 } else {
1628 right = GetGraph()->GetIntConstant(0);
1629 }
1630 HCompare* compare = new (GetGraph()->GetArena())
1631 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1632 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1633}
1634
Aart Bik75a38b22016-02-17 10:41:50 -08001635void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1636 DCHECK(invoke->IsInvokeStaticOrDirect());
1637 uint32_t dex_pc = invoke->GetDexPc();
1638 // IsNaN(x) is the same as x != x.
1639 HInstruction* x = invoke->InputAt(0);
1640 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001641 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001642 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1643}
1644
Aart Bik2a6aad92016-02-25 11:32:32 -08001645void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1646 DCHECK(invoke->IsInvokeStaticOrDirect());
1647 uint32_t dex_pc = invoke->GetDexPc();
1648 HInstruction* x = invoke->InputAt(0);
1649 Primitive::Type type = x->GetType();
1650 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1651 HInstruction* nan;
1652 if (type == Primitive::kPrimDouble) {
1653 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1654 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1655 kNeedsEnvironmentOrCache,
1656 kNoSideEffects,
1657 kNoThrow);
1658 } else {
1659 DCHECK_EQ(type, Primitive::kPrimFloat);
1660 nan = GetGraph()->GetIntConstant(0x7fc00000);
1661 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1662 kNeedsEnvironmentOrCache,
1663 kNoSideEffects,
1664 kNoThrow);
1665 }
1666 // Test IsNaN(x), which is the same as x != x.
1667 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1668 condition->SetBias(ComparisonBias::kLtBias);
1669 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1670 // Select between the two.
1671 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1672 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1673 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1674}
1675
Aart Bik11932592016-03-08 12:42:25 -08001676void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1677 uint32_t dex_pc = invoke->GetDexPc();
1678 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1679 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1680}
1681
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001682void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001683 switch (instruction->GetIntrinsic()) {
1684 case Intrinsics::kStringEquals:
1685 SimplifyStringEquals(instruction);
1686 break;
1687 case Intrinsics::kSystemArrayCopy:
1688 SimplifySystemArrayCopy(instruction);
1689 break;
1690 case Intrinsics::kIntegerRotateRight:
1691 case Intrinsics::kLongRotateRight:
1692 SimplifyRotate(instruction, false);
1693 break;
1694 case Intrinsics::kIntegerRotateLeft:
1695 case Intrinsics::kLongRotateLeft:
1696 SimplifyRotate(instruction, true);
1697 break;
1698 case Intrinsics::kIntegerCompare:
1699 case Intrinsics::kLongCompare:
1700 SimplifyCompare(instruction, /* is_signum */ false);
1701 break;
1702 case Intrinsics::kIntegerSignum:
1703 case Intrinsics::kLongSignum:
1704 SimplifyCompare(instruction, /* is_signum */ true);
1705 break;
1706 case Intrinsics::kFloatIsNaN:
1707 case Intrinsics::kDoubleIsNaN:
1708 SimplifyIsNaN(instruction);
1709 break;
1710 case Intrinsics::kFloatFloatToIntBits:
1711 case Intrinsics::kDoubleDoubleToLongBits:
1712 SimplifyFP2Int(instruction);
1713 break;
Aart Bik11932592016-03-08 12:42:25 -08001714 case Intrinsics::kUnsafeLoadFence:
1715 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1716 break;
1717 case Intrinsics::kUnsafeStoreFence:
1718 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1719 break;
1720 case Intrinsics::kUnsafeFullFence:
1721 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1722 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001723 default:
1724 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001725 }
1726}
1727
Aart Bikbb245d12015-10-19 11:05:03 -07001728void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1729 HInstruction* cond = deoptimize->InputAt(0);
1730 if (cond->IsConstant()) {
1731 if (cond->AsIntConstant()->IsZero()) {
1732 // Never deopt: instruction can be removed.
1733 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1734 } else {
1735 // Always deopt.
1736 }
1737 }
1738}
1739
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001740} // namespace art