blob: f1f4652dc847ceb64799402c5525156d685a1b4a [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) {
Vladimir Marko164306e2016-03-15 14:57:32 +0000238 int64_t cst = Int64FromConstant(input_cst);
239 int64_t mask =
240 (input_cst->GetType() == Primitive::kPrimLong) ? kMaxLongShiftValue : kMaxIntShiftValue;
241 if ((cst & mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400242 // Replace code looking like
243 // SHL dst, src, 0
244 // with
245 // src
246 instruction->ReplaceWith(input_other);
247 instruction->GetBlock()->RemoveInstruction(instruction);
Mark Mendellba56d062015-05-05 21:34:03 -0400248 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000249 }
250}
251
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000252static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
253 return (sub->GetRight() == other &&
254 sub->GetLeft()->IsConstant() &&
255 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
256}
257
258bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
259 HUShr* ushr,
260 HShl* shl) {
261 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
262 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(),
263 ushr->GetLeft(),
264 ushr->GetRight());
265 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
266 if (!ushr->HasUses()) {
267 ushr->GetBlock()->RemoveInstruction(ushr);
268 }
269 if (!ushr->GetRight()->HasUses()) {
270 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
271 }
272 if (!shl->HasUses()) {
273 shl->GetBlock()->RemoveInstruction(shl);
274 }
275 if (!shl->GetRight()->HasUses()) {
276 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
277 }
278 return true;
279}
280
281// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
282bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000283 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
284 HInstruction* left = op->GetLeft();
285 HInstruction* right = op->GetRight();
286 // If we have an UShr and a Shl (in either order).
287 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
288 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
289 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
290 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
291 if (ushr->GetType() == shl->GetType() &&
292 ushr->GetLeft() == shl->GetLeft()) {
293 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
294 // Shift distances are both constant, try replacing with Ror if they
295 // add up to the register size.
296 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
297 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
298 // Shift distances are potentially of the form x and (reg_size - x).
299 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
300 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
301 // Shift distances are potentially of the form d and -d.
302 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
303 }
304 }
305 }
306 return false;
307}
308
309// Try replacing code looking like (x >>> #rdist OP x << #ldist):
310// UShr dst, x, #rdist
311// Shl tmp, x, #ldist
312// OP dst, dst, tmp
313// or like (x >>> #rdist OP x << #-ldist):
314// UShr dst, x, #rdist
315// Shl tmp, x, #-ldist
316// OP dst, dst, tmp
317// with
318// Ror dst, x, #rdist
319bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
320 HUShr* ushr,
321 HShl* shl) {
322 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
323 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
324 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
325 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
326 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
327 ReplaceRotateWithRor(op, ushr, shl);
328 return true;
329 }
330 return false;
331}
332
333// Replace code looking like (x >>> -d OP x << d):
334// Neg neg, d
335// UShr dst, x, neg
336// Shl tmp, x, d
337// OP dst, dst, tmp
338// with
339// Neg neg, d
340// Ror dst, x, neg
341// *** OR ***
342// Replace code looking like (x >>> d OP x << -d):
343// UShr dst, x, d
344// Neg neg, d
345// Shl tmp, x, neg
346// OP dst, dst, tmp
347// with
348// Ror dst, x, d
349bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
350 HUShr* ushr,
351 HShl* shl) {
352 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
353 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
354 bool neg_is_left = shl->GetRight()->IsNeg();
355 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
356 // And the shift distance being negated is the distance being shifted the other way.
357 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
358 ReplaceRotateWithRor(op, ushr, shl);
359 }
360 return false;
361}
362
363// Try replacing code looking like (x >>> d OP x << (#bits - d)):
364// UShr dst, x, d
365// Sub ld, #bits, d
366// Shl tmp, x, ld
367// OP dst, dst, tmp
368// with
369// Ror dst, x, d
370// *** OR ***
371// Replace code looking like (x >>> (#bits - d) OP x << d):
372// Sub rd, #bits, d
373// UShr dst, x, rd
374// Shl tmp, x, d
375// OP dst, dst, tmp
376// with
377// Neg neg, d
378// Ror dst, x, neg
379bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
380 HUShr* ushr,
381 HShl* shl) {
382 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
383 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
384 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
385 HInstruction* shl_shift = shl->GetRight();
386 HInstruction* ushr_shift = ushr->GetRight();
387 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
388 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
389 return ReplaceRotateWithRor(op, ushr, shl);
390 }
391 return false;
392}
393
Calin Juravle10e244f2015-01-26 18:54:32 +0000394void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
395 HInstruction* obj = null_check->InputAt(0);
396 if (!obj->CanBeNull()) {
397 null_check->ReplaceWith(obj);
398 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000399 if (stats_ != nullptr) {
400 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
401 }
402 }
403}
404
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100405bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
406 if (!input->CanBeNull()) {
407 return true;
408 }
409
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100410 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
411 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100412 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100413 return true;
414 }
415 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100416
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100417 return false;
418}
419
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100420// Returns whether doing a type test between the class of `object` against `klass` has
421// a statically known outcome. The result of the test is stored in `outcome`.
422static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000423 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
424 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
425 ScopedObjectAccess soa(Thread::Current());
426 if (!obj_rti.IsValid()) {
427 // We run the simplifier before the reference type propagation so type info might not be
428 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100429 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000430 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100431
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100432 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100433 if (!class_rti.IsValid()) {
434 // Happens when the loaded class is unresolved.
435 return false;
436 }
437 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000438 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100439 *outcome = true;
440 return true;
441 } else if (obj_rti.IsExact()) {
442 // The test failed at compile time so will also fail at runtime.
443 *outcome = false;
444 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100445 } else if (!class_rti.IsInterface()
446 && !obj_rti.IsInterface()
447 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100448 // Different type hierarchy. The test will fail.
449 *outcome = false;
450 return true;
451 }
452 return false;
453}
454
455void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
456 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100457 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
458 if (load_class->NeedsAccessCheck()) {
459 // If we need to perform an access check we cannot remove the instruction.
460 return;
461 }
462
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100463 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100464 check_cast->ClearMustDoNullCheck();
465 }
466
467 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000468 check_cast->GetBlock()->RemoveInstruction(check_cast);
469 if (stats_ != nullptr) {
470 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
471 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100472 return;
473 }
474
Vladimir Markoa65ed302016-03-14 21:21:29 +0000475 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
476 // the return value check with the `outcome` check, b/27651442 .
477 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700478 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100479 if (outcome) {
480 check_cast->GetBlock()->RemoveInstruction(check_cast);
481 if (stats_ != nullptr) {
482 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
483 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700484 if (!load_class->HasUses()) {
485 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
486 // However, here we know that it cannot because the checkcast was successfull, hence
487 // the class was already loaded.
488 load_class->GetBlock()->RemoveInstruction(load_class);
489 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100490 } else {
491 // Don't do anything for exceptional cases for now. Ideally we should remove
492 // all instructions and blocks this instruction dominates.
493 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000494 }
495}
496
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100497void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100498 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100499 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
500 if (load_class->NeedsAccessCheck()) {
501 // If we need to perform an access check we cannot remove the instruction.
502 return;
503 }
504
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100505 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100506 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100507 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100508 instruction->ClearMustDoNullCheck();
509 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100510
511 HGraph* graph = GetGraph();
512 if (object->IsNullConstant()) {
513 instruction->ReplaceWith(graph->GetIntConstant(0));
514 instruction->GetBlock()->RemoveInstruction(instruction);
515 RecordSimplification();
516 return;
517 }
518
Vladimir Marko24bd8952016-03-15 10:40:33 +0000519 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
520 // the return value check with the `outcome` check, b/27651442 .
521 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700522 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100523 if (outcome && can_be_null) {
524 // Type test will succeed, we just need a null test.
525 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
526 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
527 instruction->ReplaceWith(test);
528 } else {
529 // We've statically determined the result of the instanceof.
530 instruction->ReplaceWith(graph->GetIntConstant(outcome));
531 }
532 RecordSimplification();
533 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700534 if (outcome && !load_class->HasUses()) {
535 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
536 // However, here we know that it cannot because the instanceof check was successfull, hence
537 // the class was already loaded.
538 load_class->GetBlock()->RemoveInstruction(load_class);
539 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100540 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100541}
542
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100543void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* 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
550void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
551 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100552 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100553 instruction->ClearValueCanBeNull();
554 }
555}
556
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000557void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100558 HBasicBlock* block = check->GetBlock();
559 // Currently always keep the suspend check at entry.
560 if (block->IsEntryBlock()) return;
561
562 // Currently always keep suspend checks at loop entry.
563 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
564 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
565 return;
566 }
567
568 // Remove the suspend check that was added at build time for the baseline
569 // compiler.
570 block->RemoveInstruction(check);
571}
572
Anton Shaminbdd79352016-02-15 12:48:36 +0600573static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
574 HInstruction *lhs = cond->InputAt(0);
575 HInstruction *rhs = cond->InputAt(1);
576 switch (cond->GetKind()) {
577 case HInstruction::kEqual:
578 return new (arena) HEqual(rhs, lhs);
579 case HInstruction::kNotEqual:
580 return new (arena) HNotEqual(rhs, lhs);
581 case HInstruction::kLessThan:
582 return new (arena) HGreaterThan(rhs, lhs);
583 case HInstruction::kLessThanOrEqual:
584 return new (arena) HGreaterThanOrEqual(rhs, lhs);
585 case HInstruction::kGreaterThan:
586 return new (arena) HLessThan(rhs, lhs);
587 case HInstruction::kGreaterThanOrEqual:
588 return new (arena) HLessThanOrEqual(rhs, lhs);
589 case HInstruction::kBelow:
590 return new (arena) HAbove(rhs, lhs);
591 case HInstruction::kBelowOrEqual:
592 return new (arena) HAboveOrEqual(rhs, lhs);
593 case HInstruction::kAbove:
594 return new (arena) HBelow(rhs, lhs);
595 case HInstruction::kAboveOrEqual:
596 return new (arena) HBelowOrEqual(rhs, lhs);
597 default:
598 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
599 }
600 return nullptr;
601}
602
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000603void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100604 HInstruction* input_const = equal->GetConstantRight();
605 if (input_const != nullptr) {
606 HInstruction* input_value = equal->GetLeastConstantLeft();
607 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
608 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100609 // We are comparing the boolean to a constant which is of type int and can
610 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100611 if (input_const->AsIntConstant()->IsOne()) {
612 // Replace (bool_value == true) with bool_value
613 equal->ReplaceWith(input_value);
614 block->RemoveInstruction(equal);
615 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100616 } else if (input_const->AsIntConstant()->IsZero()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500617 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
618 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100619 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100620 } else {
621 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
622 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
623 block->RemoveInstruction(equal);
624 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100625 }
Mark Mendellc4701932015-04-10 13:18:51 -0400626 } else {
627 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100628 }
Mark Mendellc4701932015-04-10 13:18:51 -0400629 } else {
630 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100631 }
632}
633
David Brazdil0d13fee2015-04-17 14:52:19 +0100634void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
635 HInstruction* input_const = not_equal->GetConstantRight();
636 if (input_const != nullptr) {
637 HInstruction* input_value = not_equal->GetLeastConstantLeft();
638 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
639 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100640 // We are comparing the boolean to a constant which is of type int and can
641 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100642 if (input_const->AsIntConstant()->IsOne()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500643 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
644 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100645 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100646 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100647 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100648 not_equal->ReplaceWith(input_value);
649 block->RemoveInstruction(not_equal);
650 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100651 } else {
652 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
653 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
654 block->RemoveInstruction(not_equal);
655 RecordSimplification();
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 }
Mark Mendellc4701932015-04-10 13:18:51 -0400660 } else {
661 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100662 }
663}
664
665void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000666 HInstruction* input = bool_not->InputAt(0);
667 HInstruction* replace_with = nullptr;
668
669 if (input->IsIntConstant()) {
670 // Replace !(true/false) with false/true.
671 if (input->AsIntConstant()->IsOne()) {
672 replace_with = GetGraph()->GetIntConstant(0);
673 } else {
674 DCHECK(input->AsIntConstant()->IsZero());
675 replace_with = GetGraph()->GetIntConstant(1);
676 }
677 } else if (input->IsBooleanNot()) {
678 // Replace (!(!bool_value)) with bool_value.
679 replace_with = input->InputAt(0);
680 } else if (input->IsCondition() &&
681 // Don't change FP compares. The definition of compares involving
682 // NaNs forces the compares to be done as written by the user.
683 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
684 // Replace condition with its opposite.
685 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
686 }
687
688 if (replace_with != nullptr) {
689 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100690 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000691 RecordSimplification();
692 }
693}
694
695void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
696 HInstruction* replace_with = nullptr;
697 HInstruction* condition = select->GetCondition();
698 HInstruction* true_value = select->GetTrueValue();
699 HInstruction* false_value = select->GetFalseValue();
700
701 if (condition->IsBooleanNot()) {
702 // Change ((!cond) ? x : y) to (cond ? y : x).
703 condition = condition->InputAt(0);
704 std::swap(true_value, false_value);
705 select->ReplaceInput(false_value, 0);
706 select->ReplaceInput(true_value, 1);
707 select->ReplaceInput(condition, 2);
708 RecordSimplification();
709 }
710
711 if (true_value == false_value) {
712 // Replace (cond ? x : x) with (x).
713 replace_with = true_value;
714 } else if (condition->IsIntConstant()) {
715 if (condition->AsIntConstant()->IsOne()) {
716 // Replace (true ? x : y) with (x).
717 replace_with = true_value;
718 } else {
719 // Replace (false ? x : y) with (y).
720 DCHECK(condition->AsIntConstant()->IsZero());
721 replace_with = false_value;
722 }
723 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
724 if (true_value->AsIntConstant()->IsOne() && false_value->AsIntConstant()->IsZero()) {
725 // Replace (cond ? true : false) with (cond).
726 replace_with = condition;
727 } else if (true_value->AsIntConstant()->IsZero() && false_value->AsIntConstant()->IsOne()) {
728 // Replace (cond ? false : true) with (!cond).
729 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
730 }
731 }
732
733 if (replace_with != nullptr) {
734 select->ReplaceWith(replace_with);
735 select->GetBlock()->RemoveInstruction(select);
736 RecordSimplification();
737 }
738}
739
740void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
741 HInstruction* condition = instruction->InputAt(0);
742 if (condition->IsBooleanNot()) {
743 // Swap successors if input is negated.
744 instruction->ReplaceInput(condition->InputAt(0), 0);
745 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100746 RecordSimplification();
747 }
748}
749
Mingyao Yang0304e182015-01-30 16:41:29 -0800750void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
751 HInstruction* input = instruction->InputAt(0);
752 // If the array is a NewArray with constant size, replace the array length
753 // with the constant instruction. This helps the bounds check elimination phase.
754 if (input->IsNewArray()) {
755 input = input->InputAt(0);
756 if (input->IsIntConstant()) {
757 instruction->ReplaceWith(input);
758 }
759 }
760}
761
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000762void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000763 HInstruction* value = instruction->GetValue();
764 if (value->GetType() != Primitive::kPrimNot) return;
765
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100766 if (CanEnsureNotNullAt(value, instruction)) {
767 instruction->ClearValueCanBeNull();
768 }
769
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000770 if (value->IsArrayGet()) {
771 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
772 // If the code is just swapping elements in the array, no need for a type check.
773 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100774 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000775 }
776 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100777
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100778 if (value->IsNullConstant()) {
779 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100780 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100781 }
782
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100783 ScopedObjectAccess soa(Thread::Current());
784 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
785 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
786 if (!array_rti.IsValid()) {
787 return;
788 }
789
790 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
791 instruction->ClearNeedsTypeCheck();
792 return;
793 }
794
795 if (array_rti.IsObjectArray()) {
796 if (array_rti.IsExact()) {
797 instruction->ClearNeedsTypeCheck();
798 return;
799 }
800 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100801 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000802}
803
Vladimir Markob52bbde2016-02-12 12:06:05 +0000804static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
805 // Besides conversion to the same type, widening integral conversions are implicit,
806 // excluding conversions to long and the byte->char conversion where we need to
807 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
808 return result_type == input_type ||
809 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimByte) ||
810 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimShort) ||
811 (result_type == Primitive::kPrimInt && input_type == Primitive::kPrimChar) ||
812 (result_type == Primitive::kPrimShort && input_type == Primitive::kPrimByte);
813}
814
815static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
816 // The conversion to a larger type is loss-less with the exception of two cases,
817 // - conversion to char, the only unsigned type, where we may lose some bits, and
818 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
819 // For integral to FP conversions this holds because the FP mantissa is large enough.
820 DCHECK_NE(input_type, result_type);
821 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
822 result_type != Primitive::kPrimChar &&
823 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
824}
825
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000826void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000827 HInstruction* input = instruction->GetInput();
828 Primitive::Type input_type = input->GetType();
829 Primitive::Type result_type = instruction->GetResultType();
830 if (IsTypeConversionImplicit(input_type, result_type)) {
831 // Remove the implicit conversion; this includes conversion to the same type.
832 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000833 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000834 RecordSimplification();
835 return;
836 }
837
838 if (input->IsTypeConversion()) {
839 HTypeConversion* input_conversion = input->AsTypeConversion();
840 HInstruction* original_input = input_conversion->GetInput();
841 Primitive::Type original_type = original_input->GetType();
842
843 // When the first conversion is lossless, a direct conversion from the original type
844 // to the final type yields the same result, even for a lossy second conversion, for
845 // example float->double->int or int->double->float.
846 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
847
848 // For integral conversions, see if the first conversion loses only bits that the second
849 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
850 // conversion yields the same result, for example long->int->short or int->char->short.
851 bool integral_conversions_with_non_widening_second =
852 Primitive::IsIntegralType(input_type) &&
853 Primitive::IsIntegralType(original_type) &&
854 Primitive::IsIntegralType(result_type) &&
855 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
856
857 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
858 // If the merged conversion is implicit, do the simplification unconditionally.
859 if (IsTypeConversionImplicit(original_type, result_type)) {
860 instruction->ReplaceWith(original_input);
861 instruction->GetBlock()->RemoveInstruction(instruction);
862 if (!input_conversion->HasUses()) {
863 // Don't wait for DCE.
864 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
865 }
866 RecordSimplification();
867 return;
868 }
869 // Otherwise simplify only if the first conversion has no other use.
870 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
871 input_conversion->ReplaceWith(original_input);
872 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
873 RecordSimplification();
874 return;
875 }
876 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000877 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000878 DCHECK(Primitive::IsIntegralType(input_type));
879 HAnd* input_and = input->AsAnd();
880 HConstant* constant = input_and->GetConstantRight();
881 if (constant != nullptr) {
882 int64_t value = Int64FromConstant(constant);
883 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
884 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
885 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
886 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000887 HInstruction* original_input = input_and->GetLeastConstantLeft();
888 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
889 instruction->ReplaceWith(original_input);
890 instruction->GetBlock()->RemoveInstruction(instruction);
891 RecordSimplification();
892 return;
893 } else if (input->HasOnlyOneNonEnvironmentUse()) {
894 input_and->ReplaceWith(original_input);
895 input_and->GetBlock()->RemoveInstruction(input_and);
896 RecordSimplification();
897 return;
898 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000899 }
900 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000901 }
902}
903
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000904void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
905 HConstant* input_cst = instruction->GetConstantRight();
906 HInstruction* input_other = instruction->GetLeastConstantLeft();
907 if ((input_cst != nullptr) && input_cst->IsZero()) {
908 // Replace code looking like
909 // ADD dst, src, 0
910 // with
911 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600912 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
913 // `x` is `-0.0`, the former expression yields `0.0`, while the later
914 // yields `-0.0`.
915 if (Primitive::IsIntegralType(instruction->GetType())) {
916 instruction->ReplaceWith(input_other);
917 instruction->GetBlock()->RemoveInstruction(instruction);
918 return;
919 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100920 }
921
922 HInstruction* left = instruction->GetLeft();
923 HInstruction* right = instruction->GetRight();
924 bool left_is_neg = left->IsNeg();
925 bool right_is_neg = right->IsNeg();
926
927 if (left_is_neg && right_is_neg) {
928 if (TryMoveNegOnInputsAfterBinop(instruction)) {
929 return;
930 }
931 }
932
933 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
934 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
935 // Replace code looking like
936 // NEG tmp, b
937 // ADD dst, a, tmp
938 // with
939 // SUB dst, a, b
940 // We do not perform the optimization if the input negation has environment
941 // uses or multiple non-environment uses as it could lead to worse code. In
942 // particular, we do not want the live range of `b` to be extended if we are
943 // not sure the initial 'NEG' instruction can be removed.
944 HInstruction* other = left_is_neg ? right : left;
945 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
946 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
947 RecordSimplification();
948 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000949 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000950 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000951
952 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000953}
954
955void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
956 HConstant* input_cst = instruction->GetConstantRight();
957 HInstruction* input_other = instruction->GetLeastConstantLeft();
958
Vladimir Marko452c1b62015-09-25 14:44:17 +0100959 if (input_cst != nullptr) {
960 int64_t value = Int64FromConstant(input_cst);
961 if (value == -1) {
962 // Replace code looking like
963 // AND dst, src, 0xFFF...FF
964 // with
965 // src
966 instruction->ReplaceWith(input_other);
967 instruction->GetBlock()->RemoveInstruction(instruction);
968 RecordSimplification();
969 return;
970 }
971 // Eliminate And from UShr+And if the And-mask contains all the bits that
972 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
973 // precisely clears the shifted-in sign bits.
974 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
975 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
976 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
977 size_t num_tail_bits_set = CTZ(value + 1);
978 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
979 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
980 instruction->ReplaceWith(input_other);
981 instruction->GetBlock()->RemoveInstruction(instruction);
982 RecordSimplification();
983 return;
984 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
985 input_other->HasOnlyOneNonEnvironmentUse()) {
986 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
987 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
988 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
989 input_other->InputAt(0),
990 input_other->InputAt(1),
991 input_other->GetDexPc());
992 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
993 input_other->GetBlock()->RemoveInstruction(input_other);
994 RecordSimplification();
995 return;
996 }
997 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000998 }
999
1000 // We assume that GVN has run before, so we only perform a pointer comparison.
1001 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001002 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001003 if (instruction->GetLeft() == instruction->GetRight()) {
1004 // Replace code looking like
1005 // AND dst, src, src
1006 // with
1007 // src
1008 instruction->ReplaceWith(instruction->GetLeft());
1009 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001010 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001011 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001012
1013 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001014}
1015
Mark Mendellc4701932015-04-10 13:18:51 -04001016void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1017 VisitCondition(condition);
1018}
1019
1020void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1021 VisitCondition(condition);
1022}
1023
1024void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1025 VisitCondition(condition);
1026}
1027
1028void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1029 VisitCondition(condition);
1030}
1031
Anton Shaminbdd79352016-02-15 12:48:36 +06001032void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1033 VisitCondition(condition);
1034}
1035
1036void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1037 VisitCondition(condition);
1038}
1039
1040void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1041 VisitCondition(condition);
1042}
1043
1044void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1045 VisitCondition(condition);
1046}
Aart Bike9f37602015-10-09 11:15:55 -07001047
Mark Mendellc4701932015-04-10 13:18:51 -04001048void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001049 // Reverse condition if left is constant. Our code generators prefer constant
1050 // on the right hand side.
1051 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1052 HBasicBlock* block = condition->GetBlock();
1053 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1054 // If it is a fp we must set the opposite bias.
1055 if (replacement != nullptr) {
1056 if (condition->IsLtBias()) {
1057 replacement->SetBias(ComparisonBias::kGtBias);
1058 } else if (condition->IsGtBias()) {
1059 replacement->SetBias(ComparisonBias::kLtBias);
1060 }
1061 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1062 RecordSimplification();
1063
1064 condition = replacement;
1065 }
1066 }
Mark Mendellc4701932015-04-10 13:18:51 -04001067
Mark Mendellc4701932015-04-10 13:18:51 -04001068 HInstruction* left = condition->GetLeft();
1069 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001070
1071 // Try to fold an HCompare into this HCondition.
1072
Mark Mendellc4701932015-04-10 13:18:51 -04001073 // We can only replace an HCondition which compares a Compare to 0.
1074 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1075 // condition with a long, float or double comparison as input.
1076 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1077 // Conversion is not possible.
1078 return;
1079 }
1080
1081 // Is the Compare only used for this purpose?
1082 if (!left->GetUses().HasOnlyOneUse()) {
1083 // Someone else also wants the result of the compare.
1084 return;
1085 }
1086
1087 if (!left->GetEnvUses().IsEmpty()) {
1088 // There is a reference to the compare result in an environment. Do we really need it?
1089 if (GetGraph()->IsDebuggable()) {
1090 return;
1091 }
1092
1093 // We have to ensure that there are no deopt points in the sequence.
1094 if (left->HasAnyEnvironmentUseBefore(condition)) {
1095 return;
1096 }
1097 }
1098
1099 // Clean up any environment uses from the HCompare, if any.
1100 left->RemoveEnvironmentUsers();
1101
1102 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1103 condition->SetBias(left->AsCompare()->GetBias());
1104
1105 // Replace the operands of the HCondition.
1106 condition->ReplaceInput(left->InputAt(0), 0);
1107 condition->ReplaceInput(left->InputAt(1), 1);
1108
1109 // Remove the HCompare.
1110 left->GetBlock()->RemoveInstruction(left);
1111
1112 RecordSimplification();
1113}
1114
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001115void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1116 HConstant* input_cst = instruction->GetConstantRight();
1117 HInstruction* input_other = instruction->GetLeastConstantLeft();
1118 Primitive::Type type = instruction->GetType();
1119
1120 if ((input_cst != nullptr) && input_cst->IsOne()) {
1121 // Replace code looking like
1122 // DIV dst, src, 1
1123 // with
1124 // src
1125 instruction->ReplaceWith(input_other);
1126 instruction->GetBlock()->RemoveInstruction(instruction);
1127 return;
1128 }
1129
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001130 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001131 // Replace code looking like
1132 // DIV dst, src, -1
1133 // with
1134 // NEG dst, src
1135 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001136 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001137 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001138 return;
1139 }
1140
1141 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1142 // Try replacing code looking like
1143 // DIV dst, src, constant
1144 // with
1145 // MUL dst, src, 1 / constant
1146 HConstant* reciprocal = nullptr;
1147 if (type == Primitive::Primitive::kPrimDouble) {
1148 double value = input_cst->AsDoubleConstant()->GetValue();
1149 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1150 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1151 }
1152 } else {
1153 DCHECK_EQ(type, Primitive::kPrimFloat);
1154 float value = input_cst->AsFloatConstant()->GetValue();
1155 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1156 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1157 }
1158 }
1159
1160 if (reciprocal != nullptr) {
1161 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1162 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1163 RecordSimplification();
1164 return;
1165 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001166 }
1167}
1168
1169void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1170 HConstant* input_cst = instruction->GetConstantRight();
1171 HInstruction* input_other = instruction->GetLeastConstantLeft();
1172 Primitive::Type type = instruction->GetType();
1173 HBasicBlock* block = instruction->GetBlock();
1174 ArenaAllocator* allocator = GetGraph()->GetArena();
1175
1176 if (input_cst == nullptr) {
1177 return;
1178 }
1179
1180 if (input_cst->IsOne()) {
1181 // Replace code looking like
1182 // MUL dst, src, 1
1183 // with
1184 // src
1185 instruction->ReplaceWith(input_other);
1186 instruction->GetBlock()->RemoveInstruction(instruction);
1187 return;
1188 }
1189
1190 if (input_cst->IsMinusOne() &&
1191 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1192 // Replace code looking like
1193 // MUL dst, src, -1
1194 // with
1195 // NEG dst, src
1196 HNeg* neg = new (allocator) HNeg(type, input_other);
1197 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001198 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001199 return;
1200 }
1201
1202 if (Primitive::IsFloatingPointType(type) &&
1203 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1204 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1205 // Replace code looking like
1206 // FP_MUL dst, src, 2.0
1207 // with
1208 // FP_ADD dst, src, src
1209 // The 'int' and 'long' cases are handled below.
1210 block->ReplaceAndRemoveInstructionWith(instruction,
1211 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001212 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001213 return;
1214 }
1215
1216 if (Primitive::IsIntOrLongType(type)) {
1217 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001218 // Even though constant propagation also takes care of the zero case, other
1219 // optimizations can lead to having a zero multiplication.
1220 if (factor == 0) {
1221 // Replace code looking like
1222 // MUL dst, src, 0
1223 // with
1224 // 0
1225 instruction->ReplaceWith(input_cst);
1226 instruction->GetBlock()->RemoveInstruction(instruction);
1227 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001228 // Replace code looking like
1229 // MUL dst, src, pow_of_2
1230 // with
1231 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001232 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001233 HShl* shl = new(allocator) HShl(type, input_other, shift);
1234 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001235 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001236 } else if (IsPowerOfTwo(factor - 1)) {
1237 // Transform code looking like
1238 // MUL dst, src, (2^n + 1)
1239 // into
1240 // SHL tmp, src, n
1241 // ADD dst, src, tmp
1242 HShl* shl = new (allocator) HShl(type,
1243 input_other,
1244 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1245 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1246
1247 block->InsertInstructionBefore(shl, instruction);
1248 block->ReplaceAndRemoveInstructionWith(instruction, add);
1249 RecordSimplification();
1250 } else if (IsPowerOfTwo(factor + 1)) {
1251 // Transform code looking like
1252 // MUL dst, src, (2^n - 1)
1253 // into
1254 // SHL tmp, src, n
1255 // SUB dst, tmp, src
1256 HShl* shl = new (allocator) HShl(type,
1257 input_other,
1258 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1259 HSub* sub = new (allocator) HSub(type, shl, input_other);
1260
1261 block->InsertInstructionBefore(shl, instruction);
1262 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1263 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001264 }
1265 }
1266}
1267
Alexandre Rames188d4312015-04-09 18:30:21 +01001268void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1269 HInstruction* input = instruction->GetInput();
1270 if (input->IsNeg()) {
1271 // Replace code looking like
1272 // NEG tmp, src
1273 // NEG dst, tmp
1274 // with
1275 // src
1276 HNeg* previous_neg = input->AsNeg();
1277 instruction->ReplaceWith(previous_neg->GetInput());
1278 instruction->GetBlock()->RemoveInstruction(instruction);
1279 // We perform the optimization even if the input negation has environment
1280 // uses since it allows removing the current instruction. But we only delete
1281 // the input negation only if it is does not have any uses left.
1282 if (!previous_neg->HasUses()) {
1283 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1284 }
1285 RecordSimplification();
1286 return;
1287 }
1288
Serguei Katkov339dfc22015-04-20 12:29:32 +06001289 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1290 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001291 // Replace code looking like
1292 // SUB tmp, a, b
1293 // NEG dst, tmp
1294 // with
1295 // SUB dst, b, a
1296 // We do not perform the optimization if the input subtraction has
1297 // environment uses or multiple non-environment uses as it could lead to
1298 // worse code. In particular, we do not want the live ranges of `a` and `b`
1299 // to be extended if we are not sure the initial 'SUB' instruction can be
1300 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001301 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001302 HSub* sub = input->AsSub();
1303 HSub* new_sub =
1304 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1305 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1306 if (!sub->HasUses()) {
1307 sub->GetBlock()->RemoveInstruction(sub);
1308 }
1309 RecordSimplification();
1310 }
1311}
1312
1313void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1314 HInstruction* input = instruction->GetInput();
1315 if (input->IsNot()) {
1316 // Replace code looking like
1317 // NOT tmp, src
1318 // NOT dst, tmp
1319 // with
1320 // src
1321 // We perform the optimization even if the input negation has environment
1322 // uses since it allows removing the current instruction. But we only delete
1323 // the input negation only if it is does not have any uses left.
1324 HNot* previous_not = input->AsNot();
1325 instruction->ReplaceWith(previous_not->GetInput());
1326 instruction->GetBlock()->RemoveInstruction(instruction);
1327 if (!previous_not->HasUses()) {
1328 previous_not->GetBlock()->RemoveInstruction(previous_not);
1329 }
1330 RecordSimplification();
1331 }
1332}
1333
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001334void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1335 HConstant* input_cst = instruction->GetConstantRight();
1336 HInstruction* input_other = instruction->GetLeastConstantLeft();
1337
1338 if ((input_cst != nullptr) && input_cst->IsZero()) {
1339 // Replace code looking like
1340 // OR dst, src, 0
1341 // with
1342 // src
1343 instruction->ReplaceWith(input_other);
1344 instruction->GetBlock()->RemoveInstruction(instruction);
1345 return;
1346 }
1347
1348 // We assume that GVN has run before, so we only perform a pointer comparison.
1349 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001350 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001351 if (instruction->GetLeft() == instruction->GetRight()) {
1352 // Replace code looking like
1353 // OR dst, src, src
1354 // with
1355 // src
1356 instruction->ReplaceWith(instruction->GetLeft());
1357 instruction->GetBlock()->RemoveInstruction(instruction);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001358 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001359 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001360
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001361 if (TryDeMorganNegationFactoring(instruction)) return;
1362
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001363 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001364}
1365
1366void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1367 VisitShift(instruction);
1368}
1369
1370void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1371 VisitShift(instruction);
1372}
1373
1374void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1375 HConstant* input_cst = instruction->GetConstantRight();
1376 HInstruction* input_other = instruction->GetLeastConstantLeft();
1377
Serguei Katkov115b53f2015-08-05 17:03:30 +06001378 Primitive::Type type = instruction->GetType();
1379 if (Primitive::IsFloatingPointType(type)) {
1380 return;
1381 }
1382
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001383 if ((input_cst != nullptr) && input_cst->IsZero()) {
1384 // Replace code looking like
1385 // SUB dst, src, 0
1386 // with
1387 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001388 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1389 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1390 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001391 instruction->ReplaceWith(input_other);
1392 instruction->GetBlock()->RemoveInstruction(instruction);
1393 return;
1394 }
1395
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001396 HBasicBlock* block = instruction->GetBlock();
1397 ArenaAllocator* allocator = GetGraph()->GetArena();
1398
Alexandre Rames188d4312015-04-09 18:30:21 +01001399 HInstruction* left = instruction->GetLeft();
1400 HInstruction* right = instruction->GetRight();
1401 if (left->IsConstant()) {
1402 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001403 // Replace code looking like
1404 // SUB dst, 0, src
1405 // with
1406 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001407 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001408 // `x` is `0.0`, the former expression yields `0.0`, while the later
1409 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001410 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001411 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001412 RecordSimplification();
1413 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001414 }
1415 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001416
1417 if (left->IsNeg() && right->IsNeg()) {
1418 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1419 return;
1420 }
1421 }
1422
1423 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1424 // Replace code looking like
1425 // NEG tmp, b
1426 // SUB dst, a, tmp
1427 // with
1428 // ADD dst, a, b
1429 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1430 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1431 RecordSimplification();
1432 right->GetBlock()->RemoveInstruction(right);
1433 return;
1434 }
1435
1436 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1437 // Replace code looking like
1438 // NEG tmp, a
1439 // SUB dst, tmp, b
1440 // with
1441 // ADD tmp, a, b
1442 // NEG dst, tmp
1443 // The second version is not intrinsically better, but enables more
1444 // transformations.
1445 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1446 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1447 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1448 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1449 instruction->ReplaceWith(neg);
1450 instruction->GetBlock()->RemoveInstruction(instruction);
1451 RecordSimplification();
1452 left->GetBlock()->RemoveInstruction(left);
1453 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001454}
1455
1456void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1457 VisitShift(instruction);
1458}
1459
1460void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1461 HConstant* input_cst = instruction->GetConstantRight();
1462 HInstruction* input_other = instruction->GetLeastConstantLeft();
1463
1464 if ((input_cst != nullptr) && input_cst->IsZero()) {
1465 // Replace code looking like
1466 // XOR dst, src, 0
1467 // with
1468 // src
1469 instruction->ReplaceWith(input_other);
1470 instruction->GetBlock()->RemoveInstruction(instruction);
1471 return;
1472 }
1473
1474 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1475 // Replace code looking like
1476 // XOR dst, src, 0xFFF...FF
1477 // with
1478 // NOT dst, src
1479 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1480 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001481 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001482 return;
1483 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001484
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001485 HInstruction* left = instruction->GetLeft();
1486 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001487 if (((left->IsNot() && right->IsNot()) ||
1488 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001489 left->HasOnlyOneNonEnvironmentUse() &&
1490 right->HasOnlyOneNonEnvironmentUse()) {
1491 // Replace code looking like
1492 // NOT nota, a
1493 // NOT notb, b
1494 // XOR dst, nota, notb
1495 // with
1496 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001497 instruction->ReplaceInput(left->InputAt(0), 0);
1498 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001499 left->GetBlock()->RemoveInstruction(left);
1500 right->GetBlock()->RemoveInstruction(right);
1501 RecordSimplification();
1502 return;
1503 }
1504
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001505 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001506}
1507
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001508void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1509 HInstruction* argument = instruction->InputAt(1);
1510 HInstruction* receiver = instruction->InputAt(0);
1511 if (receiver == argument) {
1512 // Because String.equals is an instance call, the receiver is
1513 // a null check if we don't know it's null. The argument however, will
1514 // be the actual object. So we cannot end up in a situation where both
1515 // are equal but could be null.
1516 DCHECK(CanEnsureNotNullAt(argument, instruction));
1517 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1518 instruction->GetBlock()->RemoveInstruction(instruction);
1519 } else {
1520 StringEqualsOptimizations optimizations(instruction);
1521 if (CanEnsureNotNullAt(argument, instruction)) {
1522 optimizations.SetArgumentNotNull();
1523 }
1524 ScopedObjectAccess soa(Thread::Current());
1525 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1526 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1527 optimizations.SetArgumentIsString();
1528 }
1529 }
1530}
1531
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001532void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke, bool is_left) {
1533 DCHECK(invoke->IsInvokeStaticOrDirect());
1534 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001535 HInstruction* value = invoke->InputAt(0);
1536 HInstruction* distance = invoke->InputAt(1);
1537 // Replace the invoke with an HRor.
1538 if (is_left) {
1539 distance = new (GetGraph()->GetArena()) HNeg(distance->GetType(), distance);
1540 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1541 }
1542 HRor* ror = new (GetGraph()->GetArena()) HRor(value->GetType(), value, distance);
1543 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1544 // Remove ClinitCheck and LoadClass, if possible.
1545 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1546 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1547 clinit->GetBlock()->RemoveInstruction(clinit);
1548 HInstruction* ldclass = clinit->InputAt(0);
1549 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1550 ldclass->GetBlock()->RemoveInstruction(ldclass);
1551 }
1552 }
1553}
1554
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001555static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1556 if (potential_length->IsArrayLength()) {
1557 return potential_length->InputAt(0) == potential_array;
1558 }
1559
1560 if (potential_array->IsNewArray()) {
1561 return potential_array->InputAt(0) == potential_length;
1562 }
1563
1564 return false;
1565}
1566
1567void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1568 HInstruction* source = instruction->InputAt(0);
1569 HInstruction* destination = instruction->InputAt(2);
1570 HInstruction* count = instruction->InputAt(4);
1571 SystemArrayCopyOptimizations optimizations(instruction);
1572 if (CanEnsureNotNullAt(source, instruction)) {
1573 optimizations.SetSourceIsNotNull();
1574 }
1575 if (CanEnsureNotNullAt(destination, instruction)) {
1576 optimizations.SetDestinationIsNotNull();
1577 }
1578 if (destination == source) {
1579 optimizations.SetDestinationIsSource();
1580 }
1581
1582 if (IsArrayLengthOf(count, source)) {
1583 optimizations.SetCountIsSourceLength();
1584 }
1585
1586 if (IsArrayLengthOf(count, destination)) {
1587 optimizations.SetCountIsDestinationLength();
1588 }
1589
1590 {
1591 ScopedObjectAccess soa(Thread::Current());
1592 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1593 if (destination_rti.IsValid()) {
1594 if (destination_rti.IsObjectArray()) {
1595 if (destination_rti.IsExact()) {
1596 optimizations.SetDoesNotNeedTypeCheck();
1597 }
1598 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001599 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001600 if (destination_rti.IsPrimitiveArrayClass()) {
1601 optimizations.SetDestinationIsPrimitiveArray();
1602 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1603 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001604 }
1605 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001606 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1607 if (source_rti.IsValid()) {
1608 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1609 optimizations.SetDoesNotNeedTypeCheck();
1610 }
1611 if (source_rti.IsPrimitiveArrayClass()) {
1612 optimizations.SetSourceIsPrimitiveArray();
1613 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1614 optimizations.SetSourceIsNonPrimitiveArray();
1615 }
1616 }
1617 }
1618}
1619
Aart Bika19616e2016-02-01 18:57:58 -08001620void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke, bool is_signum) {
1621 DCHECK(invoke->IsInvokeStaticOrDirect());
1622 uint32_t dex_pc = invoke->GetDexPc();
1623 HInstruction* left = invoke->InputAt(0);
1624 HInstruction* right;
1625 Primitive::Type type = left->GetType();
1626 if (!is_signum) {
1627 right = invoke->InputAt(1);
1628 } else if (type == Primitive::kPrimLong) {
1629 right = GetGraph()->GetLongConstant(0);
1630 } else {
1631 right = GetGraph()->GetIntConstant(0);
1632 }
1633 HCompare* compare = new (GetGraph()->GetArena())
1634 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1635 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1636}
1637
Aart Bik75a38b22016-02-17 10:41:50 -08001638void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1639 DCHECK(invoke->IsInvokeStaticOrDirect());
1640 uint32_t dex_pc = invoke->GetDexPc();
1641 // IsNaN(x) is the same as x != x.
1642 HInstruction* x = invoke->InputAt(0);
1643 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001644 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001645 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1646}
1647
Aart Bik2a6aad92016-02-25 11:32:32 -08001648void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1649 DCHECK(invoke->IsInvokeStaticOrDirect());
1650 uint32_t dex_pc = invoke->GetDexPc();
1651 HInstruction* x = invoke->InputAt(0);
1652 Primitive::Type type = x->GetType();
1653 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1654 HInstruction* nan;
1655 if (type == Primitive::kPrimDouble) {
1656 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1657 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1658 kNeedsEnvironmentOrCache,
1659 kNoSideEffects,
1660 kNoThrow);
1661 } else {
1662 DCHECK_EQ(type, Primitive::kPrimFloat);
1663 nan = GetGraph()->GetIntConstant(0x7fc00000);
1664 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1665 kNeedsEnvironmentOrCache,
1666 kNoSideEffects,
1667 kNoThrow);
1668 }
1669 // Test IsNaN(x), which is the same as x != x.
1670 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1671 condition->SetBias(ComparisonBias::kLtBias);
1672 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1673 // Select between the two.
1674 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1675 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1676 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1677}
1678
Aart Bik11932592016-03-08 12:42:25 -08001679void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1680 uint32_t dex_pc = invoke->GetDexPc();
1681 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1682 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1683}
1684
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001685void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001686 switch (instruction->GetIntrinsic()) {
1687 case Intrinsics::kStringEquals:
1688 SimplifyStringEquals(instruction);
1689 break;
1690 case Intrinsics::kSystemArrayCopy:
1691 SimplifySystemArrayCopy(instruction);
1692 break;
1693 case Intrinsics::kIntegerRotateRight:
1694 case Intrinsics::kLongRotateRight:
1695 SimplifyRotate(instruction, false);
1696 break;
1697 case Intrinsics::kIntegerRotateLeft:
1698 case Intrinsics::kLongRotateLeft:
1699 SimplifyRotate(instruction, true);
1700 break;
1701 case Intrinsics::kIntegerCompare:
1702 case Intrinsics::kLongCompare:
1703 SimplifyCompare(instruction, /* is_signum */ false);
1704 break;
1705 case Intrinsics::kIntegerSignum:
1706 case Intrinsics::kLongSignum:
1707 SimplifyCompare(instruction, /* is_signum */ true);
1708 break;
1709 case Intrinsics::kFloatIsNaN:
1710 case Intrinsics::kDoubleIsNaN:
1711 SimplifyIsNaN(instruction);
1712 break;
1713 case Intrinsics::kFloatFloatToIntBits:
1714 case Intrinsics::kDoubleDoubleToLongBits:
1715 SimplifyFP2Int(instruction);
1716 break;
Aart Bik11932592016-03-08 12:42:25 -08001717 case Intrinsics::kUnsafeLoadFence:
1718 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1719 break;
1720 case Intrinsics::kUnsafeStoreFence:
1721 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1722 break;
1723 case Intrinsics::kUnsafeFullFence:
1724 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1725 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001726 default:
1727 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001728 }
1729}
1730
Aart Bikbb245d12015-10-19 11:05:03 -07001731void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1732 HInstruction* cond = deoptimize->InputAt(0);
1733 if (cond->IsConstant()) {
1734 if (cond->AsIntConstant()->IsZero()) {
1735 // Never deopt: instruction can be removed.
1736 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1737 } else {
1738 // Always deopt.
1739 }
1740 }
1741}
1742
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001743} // namespace art