blob: a31d378e468129df0e98d936d8df6b5633609499 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
Calin Juravle69158982016-03-16 11:53:41 +000037 MaybeRecordStat(kInstructionSimplifications);
38 }
39
40 void MaybeRecordStat(MethodCompilationStat stat) {
41 if (stats_ != nullptr) {
42 stats_->RecordStat(stat);
Alexandre Rames188d4312015-04-09 18:30:21 +010043 }
44 }
45
Scott Wakeling40a04bf2015-12-11 09:50:36 +000046 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
47 bool TryReplaceWithRotate(HBinaryOperation* instruction);
48 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
49 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
50 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51
Alexandre Rames188d4312015-04-09 18:30:21 +010052 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000053 // `op` should be either HOr or HAnd.
54 // De Morgan's laws:
55 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
56 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000057 void VisitShift(HBinaryOperation* shift);
58
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000059 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010060 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
61 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010062 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
63 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000064 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000065 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000066 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080067 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000068 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000069 void VisitAdd(HAdd* instruction) OVERRIDE;
70 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040071 void VisitCondition(HCondition* instruction) OVERRIDE;
72 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
73 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
74 void VisitLessThan(HLessThan* condition) OVERRIDE;
75 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060076 void VisitBelow(HBelow* condition) OVERRIDE;
77 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
78 void VisitAbove(HAbove* condition) OVERRIDE;
79 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000080 void VisitDiv(HDiv* instruction) OVERRIDE;
81 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010082 void VisitNeg(HNeg* instruction) OVERRIDE;
83 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000084 void VisitOr(HOr* instruction) OVERRIDE;
85 void VisitShl(HShl* instruction) OVERRIDE;
86 void VisitShr(HShr* instruction) OVERRIDE;
87 void VisitSub(HSub* instruction) OVERRIDE;
88 void VisitUShr(HUShr* instruction) OVERRIDE;
89 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000090 void VisitSelect(HSelect* select) OVERRIDE;
91 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010092 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010093 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -070094 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010095
96 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000097
Roland Levillain22c49222016-03-18 14:04:28 +000098 void SimplifyRotate(HInvoke* invoke, bool is_left, Primitive::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010099 void SimplifySystemArrayCopy(HInvoke* invoke);
100 void SimplifyStringEquals(HInvoke* invoke);
Roland Levillaina5c4a402016-03-15 15:02:50 +0000101 void SimplifyCompare(HInvoke* invoke, bool is_signum, Primitive::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800102 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800103 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100104 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800105 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100106
Calin Juravleacf735c2015-02-12 15:25:22 +0000107 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100108 bool simplification_occurred_ = false;
109 int simplifications_at_current_position_ = 0;
110 // We ensure we do not loop infinitely. The value is a finger in the air guess
111 // that should allow enough simplification.
112 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000113};
114
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100115void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000116 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100117 visitor.Run();
118}
119
120void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100121 // Iterate in reverse post order to open up more simplifications to users
122 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
124 // The simplification of an instruction to another instruction may yield
125 // possibilities for other simplifications. So although we perform a reverse
126 // post order visit, we sometimes need to revisit an instruction index.
127 simplification_occurred_ = false;
128 VisitBasicBlock(it.Current());
129 if (simplification_occurred_ &&
130 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
131 // New simplifications may be applicable to the instruction at the
132 // current index, so don't advance the iterator.
133 continue;
134 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100135 simplifications_at_current_position_ = 0;
136 it.Advance();
137 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100138}
139
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000140namespace {
141
142bool AreAllBitsSet(HConstant* constant) {
143 return Int64FromConstant(constant) == -1;
144}
145
146} // namespace
147
Alexandre Rames188d4312015-04-09 18:30:21 +0100148// Returns true if the code was simplified to use only one negation operation
149// after the binary operation instead of one on each of the inputs.
150bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
151 DCHECK(binop->IsAdd() || binop->IsSub());
152 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
153 HNeg* left_neg = binop->GetLeft()->AsNeg();
154 HNeg* right_neg = binop->GetRight()->AsNeg();
155 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
156 !right_neg->HasOnlyOneNonEnvironmentUse()) {
157 return false;
158 }
159 // Replace code looking like
160 // NEG tmp1, a
161 // NEG tmp2, b
162 // ADD dst, tmp1, tmp2
163 // with
164 // ADD tmp, a, b
165 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600166 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
167 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
168 // while the later yields `-0.0`.
169 if (!Primitive::IsIntegralType(binop->GetType())) {
170 return false;
171 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100172 binop->ReplaceInput(left_neg->GetInput(), 0);
173 binop->ReplaceInput(right_neg->GetInput(), 1);
174 left_neg->GetBlock()->RemoveInstruction(left_neg);
175 right_neg->GetBlock()->RemoveInstruction(right_neg);
176 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
177 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
178 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
179 RecordSimplification();
180 return true;
181}
182
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000183bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
184 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
185 Primitive::Type type = op->GetType();
186 HInstruction* left = op->GetLeft();
187 HInstruction* right = op->GetRight();
188
189 // We can apply De Morgan's laws if both inputs are Not's and are only used
190 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000191 if (((left->IsNot() && right->IsNot()) ||
192 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000193 left->HasOnlyOneNonEnvironmentUse() &&
194 right->HasOnlyOneNonEnvironmentUse()) {
195 // Replace code looking like
196 // NOT nota, a
197 // NOT notb, b
198 // AND dst, nota, notb (respectively OR)
199 // with
200 // OR or, a, b (respectively AND)
201 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000202 HInstruction* src_left = left->InputAt(0);
203 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000204 uint32_t dex_pc = op->GetDexPc();
205
206 // Remove the negations on the inputs.
207 left->ReplaceWith(src_left);
208 right->ReplaceWith(src_right);
209 left->GetBlock()->RemoveInstruction(left);
210 right->GetBlock()->RemoveInstruction(right);
211
212 // Replace the `HAnd` or `HOr`.
213 HBinaryOperation* hbin;
214 if (op->IsAnd()) {
215 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
216 } else {
217 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
218 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000219 HInstruction* hnot;
220 if (left->IsBooleanNot()) {
221 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
222 } else {
223 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
224 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000225
226 op->GetBlock()->InsertInstructionBefore(hbin, op);
227 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
228
229 RecordSimplification();
230 return true;
231 }
232
233 return false;
234}
235
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000236void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
237 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
238 HConstant* input_cst = instruction->GetConstantRight();
239 HInstruction* input_other = instruction->GetLeastConstantLeft();
240
Mark Mendellba56d062015-05-05 21:34:03 -0400241 if (input_cst != nullptr) {
Vladimir Marko164306e2016-03-15 14:57:32 +0000242 int64_t cst = Int64FromConstant(input_cst);
Roland Levillain5b5b9312016-03-22 14:57:31 +0000243 int64_t mask = (input_other->GetType() == Primitive::kPrimLong)
244 ? kMaxLongShiftDistance
245 : kMaxIntShiftDistance;
Vladimir Marko164306e2016-03-15 14:57:32 +0000246 if ((cst & mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400247 // Replace code looking like
248 // SHL dst, src, 0
249 // with
250 // src
251 instruction->ReplaceWith(input_other);
252 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100253 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400254 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000255 }
256}
257
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000258static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
259 return (sub->GetRight() == other &&
260 sub->GetLeft()->IsConstant() &&
261 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
262}
263
264bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
265 HUShr* ushr,
266 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000267 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
268 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000269 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
270 if (!ushr->HasUses()) {
271 ushr->GetBlock()->RemoveInstruction(ushr);
272 }
273 if (!ushr->GetRight()->HasUses()) {
274 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
275 }
276 if (!shl->HasUses()) {
277 shl->GetBlock()->RemoveInstruction(shl);
278 }
279 if (!shl->GetRight()->HasUses()) {
280 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
281 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100282 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000283 return true;
284}
285
286// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
287bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000288 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
289 HInstruction* left = op->GetLeft();
290 HInstruction* right = op->GetRight();
291 // If we have an UShr and a Shl (in either order).
292 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
293 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
294 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
295 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
296 if (ushr->GetType() == shl->GetType() &&
297 ushr->GetLeft() == shl->GetLeft()) {
298 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
299 // Shift distances are both constant, try replacing with Ror if they
300 // add up to the register size.
301 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
302 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
303 // Shift distances are potentially of the form x and (reg_size - x).
304 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
305 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
306 // Shift distances are potentially of the form d and -d.
307 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
308 }
309 }
310 }
311 return false;
312}
313
314// Try replacing code looking like (x >>> #rdist OP x << #ldist):
315// UShr dst, x, #rdist
316// Shl tmp, x, #ldist
317// OP dst, dst, tmp
318// or like (x >>> #rdist OP x << #-ldist):
319// UShr dst, x, #rdist
320// Shl tmp, x, #-ldist
321// OP dst, dst, tmp
322// with
323// Ror dst, x, #rdist
324bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
325 HUShr* ushr,
326 HShl* shl) {
327 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
328 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
329 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
330 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
331 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
332 ReplaceRotateWithRor(op, ushr, shl);
333 return true;
334 }
335 return false;
336}
337
338// Replace code looking like (x >>> -d OP x << d):
339// Neg neg, d
340// UShr dst, x, neg
341// Shl tmp, x, d
342// OP dst, dst, tmp
343// with
344// Neg neg, d
345// Ror dst, x, neg
346// *** OR ***
347// Replace code looking like (x >>> d OP x << -d):
348// UShr dst, x, d
349// Neg neg, d
350// Shl tmp, x, neg
351// OP dst, dst, tmp
352// with
353// Ror dst, x, d
354bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
355 HUShr* ushr,
356 HShl* shl) {
357 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
358 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
359 bool neg_is_left = shl->GetRight()->IsNeg();
360 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
361 // And the shift distance being negated is the distance being shifted the other way.
362 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
363 ReplaceRotateWithRor(op, ushr, shl);
364 }
365 return false;
366}
367
368// Try replacing code looking like (x >>> d OP x << (#bits - d)):
369// UShr dst, x, d
370// Sub ld, #bits, d
371// Shl tmp, x, ld
372// OP dst, dst, tmp
373// with
374// Ror dst, x, d
375// *** OR ***
376// Replace code looking like (x >>> (#bits - d) OP x << d):
377// Sub rd, #bits, d
378// UShr dst, x, rd
379// Shl tmp, x, d
380// OP dst, dst, tmp
381// with
382// Neg neg, d
383// Ror dst, x, neg
384bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
385 HUShr* ushr,
386 HShl* shl) {
387 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
388 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
389 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
390 HInstruction* shl_shift = shl->GetRight();
391 HInstruction* ushr_shift = ushr->GetRight();
392 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
393 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
394 return ReplaceRotateWithRor(op, ushr, shl);
395 }
396 return false;
397}
398
Calin Juravle10e244f2015-01-26 18:54:32 +0000399void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
400 HInstruction* obj = null_check->InputAt(0);
401 if (!obj->CanBeNull()) {
402 null_check->ReplaceWith(obj);
403 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000404 if (stats_ != nullptr) {
405 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
406 }
407 }
408}
409
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100410bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
411 if (!input->CanBeNull()) {
412 return true;
413 }
414
Vladimir Marko46817b82016-03-29 12:21:58 +0100415 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
416 HInstruction* user = use.GetUser();
417 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100418 return true;
419 }
420 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100421
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100422 return false;
423}
424
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100425// Returns whether doing a type test between the class of `object` against `klass` has
426// a statically known outcome. The result of the test is stored in `outcome`.
427static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000428 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
429 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
430 ScopedObjectAccess soa(Thread::Current());
431 if (!obj_rti.IsValid()) {
432 // We run the simplifier before the reference type propagation so type info might not be
433 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100434 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000435 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100436
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100437 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100438 if (!class_rti.IsValid()) {
439 // Happens when the loaded class is unresolved.
440 return false;
441 }
442 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000443 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100444 *outcome = true;
445 return true;
446 } else if (obj_rti.IsExact()) {
447 // The test failed at compile time so will also fail at runtime.
448 *outcome = false;
449 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100450 } else if (!class_rti.IsInterface()
451 && !obj_rti.IsInterface()
452 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100453 // Different type hierarchy. The test will fail.
454 *outcome = false;
455 return true;
456 }
457 return false;
458}
459
460void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
461 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100462 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
463 if (load_class->NeedsAccessCheck()) {
464 // If we need to perform an access check we cannot remove the instruction.
465 return;
466 }
467
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100468 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100469 check_cast->ClearMustDoNullCheck();
470 }
471
472 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000473 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000474 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100475 return;
476 }
477
Vladimir Markoa65ed302016-03-14 21:21:29 +0000478 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
479 // the return value check with the `outcome` check, b/27651442 .
480 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700481 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100482 if (outcome) {
483 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000484 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700485 if (!load_class->HasUses()) {
486 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
487 // However, here we know that it cannot because the checkcast was successfull, hence
488 // the class was already loaded.
489 load_class->GetBlock()->RemoveInstruction(load_class);
490 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100491 } else {
492 // Don't do anything for exceptional cases for now. Ideally we should remove
493 // all instructions and blocks this instruction dominates.
494 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000495 }
496}
497
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100498void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100499 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100500 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
501 if (load_class->NeedsAccessCheck()) {
502 // If we need to perform an access check we cannot remove the instruction.
503 return;
504 }
505
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100506 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100507 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100508 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100509 instruction->ClearMustDoNullCheck();
510 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100511
512 HGraph* graph = GetGraph();
513 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000514 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100515 instruction->ReplaceWith(graph->GetIntConstant(0));
516 instruction->GetBlock()->RemoveInstruction(instruction);
517 RecordSimplification();
518 return;
519 }
520
Vladimir Marko24bd8952016-03-15 10:40:33 +0000521 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
522 // the return value check with the `outcome` check, b/27651442 .
523 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700524 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000525 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100526 if (outcome && can_be_null) {
527 // Type test will succeed, we just need a null test.
528 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
529 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
530 instruction->ReplaceWith(test);
531 } else {
532 // We've statically determined the result of the instanceof.
533 instruction->ReplaceWith(graph->GetIntConstant(outcome));
534 }
535 RecordSimplification();
536 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700537 if (outcome && !load_class->HasUses()) {
538 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
539 // However, here we know that it cannot because the instanceof check was successfull, hence
540 // the class was already loaded.
541 load_class->GetBlock()->RemoveInstruction(load_class);
542 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100543 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100544}
545
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100546void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
547 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100548 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100549 instruction->ClearValueCanBeNull();
550 }
551}
552
553void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
554 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100555 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100556 instruction->ClearValueCanBeNull();
557 }
558}
559
Anton Shaminbdd79352016-02-15 12:48:36 +0600560static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
561 HInstruction *lhs = cond->InputAt(0);
562 HInstruction *rhs = cond->InputAt(1);
563 switch (cond->GetKind()) {
564 case HInstruction::kEqual:
565 return new (arena) HEqual(rhs, lhs);
566 case HInstruction::kNotEqual:
567 return new (arena) HNotEqual(rhs, lhs);
568 case HInstruction::kLessThan:
569 return new (arena) HGreaterThan(rhs, lhs);
570 case HInstruction::kLessThanOrEqual:
571 return new (arena) HGreaterThanOrEqual(rhs, lhs);
572 case HInstruction::kGreaterThan:
573 return new (arena) HLessThan(rhs, lhs);
574 case HInstruction::kGreaterThanOrEqual:
575 return new (arena) HLessThanOrEqual(rhs, lhs);
576 case HInstruction::kBelow:
577 return new (arena) HAbove(rhs, lhs);
578 case HInstruction::kBelowOrEqual:
579 return new (arena) HAboveOrEqual(rhs, lhs);
580 case HInstruction::kAbove:
581 return new (arena) HBelow(rhs, lhs);
582 case HInstruction::kAboveOrEqual:
583 return new (arena) HBelowOrEqual(rhs, lhs);
584 default:
585 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
586 }
587 return nullptr;
588}
589
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000590void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100591 HInstruction* input_const = equal->GetConstantRight();
592 if (input_const != nullptr) {
593 HInstruction* input_value = equal->GetLeastConstantLeft();
594 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
595 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100596 // We are comparing the boolean to a constant which is of type int and can
597 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000598 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100599 // Replace (bool_value == true) with bool_value
600 equal->ReplaceWith(input_value);
601 block->RemoveInstruction(equal);
602 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000603 } else if (input_const->AsIntConstant()->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500604 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
605 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100606 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100607 } else {
608 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
609 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
610 block->RemoveInstruction(equal);
611 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100612 }
Mark Mendellc4701932015-04-10 13:18:51 -0400613 } else {
614 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100615 }
Mark Mendellc4701932015-04-10 13:18:51 -0400616 } else {
617 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100618 }
619}
620
David Brazdil0d13fee2015-04-17 14:52:19 +0100621void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
622 HInstruction* input_const = not_equal->GetConstantRight();
623 if (input_const != nullptr) {
624 HInstruction* input_value = not_equal->GetLeastConstantLeft();
625 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
626 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100627 // We are comparing the boolean to a constant which is of type int and can
628 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000629 if (input_const->AsIntConstant()->IsTrue()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500630 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
631 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100632 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000633 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100634 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100635 not_equal->ReplaceWith(input_value);
636 block->RemoveInstruction(not_equal);
637 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100638 } else {
639 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
640 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
641 block->RemoveInstruction(not_equal);
642 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100643 }
Mark Mendellc4701932015-04-10 13:18:51 -0400644 } else {
645 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100646 }
Mark Mendellc4701932015-04-10 13:18:51 -0400647 } else {
648 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100649 }
650}
651
652void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000653 HInstruction* input = bool_not->InputAt(0);
654 HInstruction* replace_with = nullptr;
655
656 if (input->IsIntConstant()) {
657 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000658 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000659 replace_with = GetGraph()->GetIntConstant(0);
660 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000661 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000662 replace_with = GetGraph()->GetIntConstant(1);
663 }
664 } else if (input->IsBooleanNot()) {
665 // Replace (!(!bool_value)) with bool_value.
666 replace_with = input->InputAt(0);
667 } else if (input->IsCondition() &&
668 // Don't change FP compares. The definition of compares involving
669 // NaNs forces the compares to be done as written by the user.
670 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
671 // Replace condition with its opposite.
672 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
673 }
674
675 if (replace_with != nullptr) {
676 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100677 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000678 RecordSimplification();
679 }
680}
681
682void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
683 HInstruction* replace_with = nullptr;
684 HInstruction* condition = select->GetCondition();
685 HInstruction* true_value = select->GetTrueValue();
686 HInstruction* false_value = select->GetFalseValue();
687
688 if (condition->IsBooleanNot()) {
689 // Change ((!cond) ? x : y) to (cond ? y : x).
690 condition = condition->InputAt(0);
691 std::swap(true_value, false_value);
692 select->ReplaceInput(false_value, 0);
693 select->ReplaceInput(true_value, 1);
694 select->ReplaceInput(condition, 2);
695 RecordSimplification();
696 }
697
698 if (true_value == false_value) {
699 // Replace (cond ? x : x) with (x).
700 replace_with = true_value;
701 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000702 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000703 // Replace (true ? x : y) with (x).
704 replace_with = true_value;
705 } else {
706 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000707 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000708 replace_with = false_value;
709 }
710 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000711 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000712 // Replace (cond ? true : false) with (cond).
713 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000714 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000715 // Replace (cond ? false : true) with (!cond).
716 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
717 }
718 }
719
720 if (replace_with != nullptr) {
721 select->ReplaceWith(replace_with);
722 select->GetBlock()->RemoveInstruction(select);
723 RecordSimplification();
724 }
725}
726
727void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
728 HInstruction* condition = instruction->InputAt(0);
729 if (condition->IsBooleanNot()) {
730 // Swap successors if input is negated.
731 instruction->ReplaceInput(condition->InputAt(0), 0);
732 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100733 RecordSimplification();
734 }
735}
736
Mingyao Yang0304e182015-01-30 16:41:29 -0800737void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
738 HInstruction* input = instruction->InputAt(0);
739 // If the array is a NewArray with constant size, replace the array length
740 // with the constant instruction. This helps the bounds check elimination phase.
741 if (input->IsNewArray()) {
742 input = input->InputAt(0);
743 if (input->IsIntConstant()) {
744 instruction->ReplaceWith(input);
745 }
746 }
747}
748
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000749void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000750 HInstruction* value = instruction->GetValue();
751 if (value->GetType() != Primitive::kPrimNot) return;
752
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100753 if (CanEnsureNotNullAt(value, instruction)) {
754 instruction->ClearValueCanBeNull();
755 }
756
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000757 if (value->IsArrayGet()) {
758 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
759 // If the code is just swapping elements in the array, no need for a type check.
760 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100761 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000762 }
763 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100764
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100765 if (value->IsNullConstant()) {
766 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100767 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100768 }
769
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100770 ScopedObjectAccess soa(Thread::Current());
771 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
772 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
773 if (!array_rti.IsValid()) {
774 return;
775 }
776
777 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
778 instruction->ClearNeedsTypeCheck();
779 return;
780 }
781
782 if (array_rti.IsObjectArray()) {
783 if (array_rti.IsExact()) {
784 instruction->ClearNeedsTypeCheck();
785 return;
786 }
787 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100788 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000789}
790
Vladimir Markob52bbde2016-02-12 12:06:05 +0000791static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100792 // Invariant: We should never generate a conversion to a Boolean value.
793 DCHECK_NE(Primitive::kPrimBoolean, result_type);
794
Vladimir Markob52bbde2016-02-12 12:06:05 +0000795 // Besides conversion to the same type, widening integral conversions are implicit,
796 // excluding conversions to long and the byte->char conversion where we need to
797 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
798 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100799 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
800 input_type == Primitive::kPrimByte ||
801 input_type == Primitive::kPrimShort ||
802 input_type == Primitive::kPrimChar)) ||
803 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
804 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
805 input_type == Primitive::kPrimByte)) ||
806 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000807}
808
809static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
810 // The conversion to a larger type is loss-less with the exception of two cases,
811 // - conversion to char, the only unsigned type, where we may lose some bits, and
812 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
813 // For integral to FP conversions this holds because the FP mantissa is large enough.
814 DCHECK_NE(input_type, result_type);
815 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
816 result_type != Primitive::kPrimChar &&
817 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
818}
819
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000820void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000821 HInstruction* input = instruction->GetInput();
822 Primitive::Type input_type = input->GetType();
823 Primitive::Type result_type = instruction->GetResultType();
824 if (IsTypeConversionImplicit(input_type, result_type)) {
825 // Remove the implicit conversion; this includes conversion to the same type.
826 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000827 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000828 RecordSimplification();
829 return;
830 }
831
832 if (input->IsTypeConversion()) {
833 HTypeConversion* input_conversion = input->AsTypeConversion();
834 HInstruction* original_input = input_conversion->GetInput();
835 Primitive::Type original_type = original_input->GetType();
836
837 // When the first conversion is lossless, a direct conversion from the original type
838 // to the final type yields the same result, even for a lossy second conversion, for
839 // example float->double->int or int->double->float.
840 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
841
842 // For integral conversions, see if the first conversion loses only bits that the second
843 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
844 // conversion yields the same result, for example long->int->short or int->char->short.
845 bool integral_conversions_with_non_widening_second =
846 Primitive::IsIntegralType(input_type) &&
847 Primitive::IsIntegralType(original_type) &&
848 Primitive::IsIntegralType(result_type) &&
849 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
850
851 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
852 // If the merged conversion is implicit, do the simplification unconditionally.
853 if (IsTypeConversionImplicit(original_type, result_type)) {
854 instruction->ReplaceWith(original_input);
855 instruction->GetBlock()->RemoveInstruction(instruction);
856 if (!input_conversion->HasUses()) {
857 // Don't wait for DCE.
858 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
859 }
860 RecordSimplification();
861 return;
862 }
863 // Otherwise simplify only if the first conversion has no other use.
864 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
865 input_conversion->ReplaceWith(original_input);
866 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
867 RecordSimplification();
868 return;
869 }
870 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000871 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000872 DCHECK(Primitive::IsIntegralType(input_type));
873 HAnd* input_and = input->AsAnd();
874 HConstant* constant = input_and->GetConstantRight();
875 if (constant != nullptr) {
876 int64_t value = Int64FromConstant(constant);
877 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
878 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
879 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
880 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000881 HInstruction* original_input = input_and->GetLeastConstantLeft();
882 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
883 instruction->ReplaceWith(original_input);
884 instruction->GetBlock()->RemoveInstruction(instruction);
885 RecordSimplification();
886 return;
887 } else if (input->HasOnlyOneNonEnvironmentUse()) {
888 input_and->ReplaceWith(original_input);
889 input_and->GetBlock()->RemoveInstruction(input_and);
890 RecordSimplification();
891 return;
892 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000893 }
894 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000895 }
896}
897
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000898void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
899 HConstant* input_cst = instruction->GetConstantRight();
900 HInstruction* input_other = instruction->GetLeastConstantLeft();
Roland Levillain1a653882016-03-18 18:05:57 +0000901 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000902 // Replace code looking like
903 // ADD dst, src, 0
904 // with
905 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600906 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
907 // `x` is `-0.0`, the former expression yields `0.0`, while the later
908 // yields `-0.0`.
909 if (Primitive::IsIntegralType(instruction->GetType())) {
910 instruction->ReplaceWith(input_other);
911 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100912 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600913 return;
914 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100915 }
916
917 HInstruction* left = instruction->GetLeft();
918 HInstruction* right = instruction->GetRight();
919 bool left_is_neg = left->IsNeg();
920 bool right_is_neg = right->IsNeg();
921
922 if (left_is_neg && right_is_neg) {
923 if (TryMoveNegOnInputsAfterBinop(instruction)) {
924 return;
925 }
926 }
927
928 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
929 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
930 // Replace code looking like
931 // NEG tmp, b
932 // ADD dst, a, tmp
933 // with
934 // SUB dst, a, b
935 // We do not perform the optimization if the input negation has environment
936 // uses or multiple non-environment uses as it could lead to worse code. In
937 // particular, we do not want the live range of `b` to be extended if we are
938 // not sure the initial 'NEG' instruction can be removed.
939 HInstruction* other = left_is_neg ? right : left;
940 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
941 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
942 RecordSimplification();
943 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000944 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000945 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000946
947 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000948}
949
950void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
951 HConstant* input_cst = instruction->GetConstantRight();
952 HInstruction* input_other = instruction->GetLeastConstantLeft();
953
Vladimir Marko452c1b62015-09-25 14:44:17 +0100954 if (input_cst != nullptr) {
955 int64_t value = Int64FromConstant(input_cst);
956 if (value == -1) {
957 // Replace code looking like
958 // AND dst, src, 0xFFF...FF
959 // with
960 // src
961 instruction->ReplaceWith(input_other);
962 instruction->GetBlock()->RemoveInstruction(instruction);
963 RecordSimplification();
964 return;
965 }
966 // Eliminate And from UShr+And if the And-mask contains all the bits that
967 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
968 // precisely clears the shifted-in sign bits.
969 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
970 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
971 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
972 size_t num_tail_bits_set = CTZ(value + 1);
973 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
974 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
975 instruction->ReplaceWith(input_other);
976 instruction->GetBlock()->RemoveInstruction(instruction);
977 RecordSimplification();
978 return;
979 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
980 input_other->HasOnlyOneNonEnvironmentUse()) {
981 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
982 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
983 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
984 input_other->InputAt(0),
985 input_other->InputAt(1),
986 input_other->GetDexPc());
987 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
988 input_other->GetBlock()->RemoveInstruction(input_other);
989 RecordSimplification();
990 return;
991 }
992 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000993 }
994
995 // We assume that GVN has run before, so we only perform a pointer comparison.
996 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100997 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000998 if (instruction->GetLeft() == instruction->GetRight()) {
999 // Replace code looking like
1000 // AND dst, src, src
1001 // with
1002 // src
1003 instruction->ReplaceWith(instruction->GetLeft());
1004 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001005 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001006 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001007 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001008
1009 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001010}
1011
Mark Mendellc4701932015-04-10 13:18:51 -04001012void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1013 VisitCondition(condition);
1014}
1015
1016void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1017 VisitCondition(condition);
1018}
1019
1020void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1021 VisitCondition(condition);
1022}
1023
1024void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1025 VisitCondition(condition);
1026}
1027
Anton Shaminbdd79352016-02-15 12:48:36 +06001028void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1029 VisitCondition(condition);
1030}
1031
1032void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1033 VisitCondition(condition);
1034}
1035
1036void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1037 VisitCondition(condition);
1038}
1039
1040void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1041 VisitCondition(condition);
1042}
Aart Bike9f37602015-10-09 11:15:55 -07001043
Mark Mendellc4701932015-04-10 13:18:51 -04001044void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001045 // Reverse condition if left is constant. Our code generators prefer constant
1046 // on the right hand side.
1047 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1048 HBasicBlock* block = condition->GetBlock();
1049 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1050 // If it is a fp we must set the opposite bias.
1051 if (replacement != nullptr) {
1052 if (condition->IsLtBias()) {
1053 replacement->SetBias(ComparisonBias::kGtBias);
1054 } else if (condition->IsGtBias()) {
1055 replacement->SetBias(ComparisonBias::kLtBias);
1056 }
1057 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1058 RecordSimplification();
1059
1060 condition = replacement;
1061 }
1062 }
Mark Mendellc4701932015-04-10 13:18:51 -04001063
Mark Mendellc4701932015-04-10 13:18:51 -04001064 HInstruction* left = condition->GetLeft();
1065 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001066
1067 // Try to fold an HCompare into this HCondition.
1068
Mark Mendellc4701932015-04-10 13:18:51 -04001069 // We can only replace an HCondition which compares a Compare to 0.
1070 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1071 // condition with a long, float or double comparison as input.
1072 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1073 // Conversion is not possible.
1074 return;
1075 }
1076
1077 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001078 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001079 // Someone else also wants the result of the compare.
1080 return;
1081 }
1082
Vladimir Marko46817b82016-03-29 12:21:58 +01001083 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001084 // There is a reference to the compare result in an environment. Do we really need it?
1085 if (GetGraph()->IsDebuggable()) {
1086 return;
1087 }
1088
1089 // We have to ensure that there are no deopt points in the sequence.
1090 if (left->HasAnyEnvironmentUseBefore(condition)) {
1091 return;
1092 }
1093 }
1094
1095 // Clean up any environment uses from the HCompare, if any.
1096 left->RemoveEnvironmentUsers();
1097
1098 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1099 condition->SetBias(left->AsCompare()->GetBias());
1100
1101 // Replace the operands of the HCondition.
1102 condition->ReplaceInput(left->InputAt(0), 0);
1103 condition->ReplaceInput(left->InputAt(1), 1);
1104
1105 // Remove the HCompare.
1106 left->GetBlock()->RemoveInstruction(left);
1107
1108 RecordSimplification();
1109}
1110
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001111void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1112 HConstant* input_cst = instruction->GetConstantRight();
1113 HInstruction* input_other = instruction->GetLeastConstantLeft();
1114 Primitive::Type type = instruction->GetType();
1115
1116 if ((input_cst != nullptr) && input_cst->IsOne()) {
1117 // Replace code looking like
1118 // DIV dst, src, 1
1119 // with
1120 // src
1121 instruction->ReplaceWith(input_other);
1122 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001123 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001124 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);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001184 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001185 return;
1186 }
1187
1188 if (input_cst->IsMinusOne() &&
1189 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1190 // Replace code looking like
1191 // MUL dst, src, -1
1192 // with
1193 // NEG dst, src
1194 HNeg* neg = new (allocator) HNeg(type, input_other);
1195 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001196 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001197 return;
1198 }
1199
1200 if (Primitive::IsFloatingPointType(type) &&
1201 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1202 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1203 // Replace code looking like
1204 // FP_MUL dst, src, 2.0
1205 // with
1206 // FP_ADD dst, src, src
1207 // The 'int' and 'long' cases are handled below.
1208 block->ReplaceAndRemoveInstructionWith(instruction,
1209 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001210 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001211 return;
1212 }
1213
1214 if (Primitive::IsIntOrLongType(type)) {
1215 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001216 // Even though constant propagation also takes care of the zero case, other
1217 // optimizations can lead to having a zero multiplication.
1218 if (factor == 0) {
1219 // Replace code looking like
1220 // MUL dst, src, 0
1221 // with
1222 // 0
1223 instruction->ReplaceWith(input_cst);
1224 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001225 RecordSimplification();
Serguei Katkov53849192015-04-20 14:22:27 +06001226 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001227 // Replace code looking like
1228 // MUL dst, src, pow_of_2
1229 // with
1230 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001231 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001232 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001233 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001234 RecordSimplification();
Alexandre Rames38db7852015-11-20 15:02:45 +00001235 } else if (IsPowerOfTwo(factor - 1)) {
1236 // Transform code looking like
1237 // MUL dst, src, (2^n + 1)
1238 // into
1239 // SHL tmp, src, n
1240 // ADD dst, src, tmp
1241 HShl* shl = new (allocator) HShl(type,
1242 input_other,
1243 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1244 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1245
1246 block->InsertInstructionBefore(shl, instruction);
1247 block->ReplaceAndRemoveInstructionWith(instruction, add);
1248 RecordSimplification();
1249 } else if (IsPowerOfTwo(factor + 1)) {
1250 // Transform code looking like
1251 // MUL dst, src, (2^n - 1)
1252 // into
1253 // SHL tmp, src, n
1254 // SUB dst, tmp, src
1255 HShl* shl = new (allocator) HShl(type,
1256 input_other,
1257 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1258 HSub* sub = new (allocator) HSub(type, shl, input_other);
1259
1260 block->InsertInstructionBefore(shl, instruction);
1261 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1262 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001263 }
1264 }
1265}
1266
Alexandre Rames188d4312015-04-09 18:30:21 +01001267void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1268 HInstruction* input = instruction->GetInput();
1269 if (input->IsNeg()) {
1270 // Replace code looking like
1271 // NEG tmp, src
1272 // NEG dst, tmp
1273 // with
1274 // src
1275 HNeg* previous_neg = input->AsNeg();
1276 instruction->ReplaceWith(previous_neg->GetInput());
1277 instruction->GetBlock()->RemoveInstruction(instruction);
1278 // We perform the optimization even if the input negation has environment
1279 // uses since it allows removing the current instruction. But we only delete
1280 // the input negation only if it is does not have any uses left.
1281 if (!previous_neg->HasUses()) {
1282 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1283 }
1284 RecordSimplification();
1285 return;
1286 }
1287
Serguei Katkov339dfc22015-04-20 12:29:32 +06001288 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
1289 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001290 // Replace code looking like
1291 // SUB tmp, a, b
1292 // NEG dst, tmp
1293 // with
1294 // SUB dst, b, a
1295 // We do not perform the optimization if the input subtraction has
1296 // environment uses or multiple non-environment uses as it could lead to
1297 // worse code. In particular, we do not want the live ranges of `a` and `b`
1298 // to be extended if we are not sure the initial 'SUB' instruction can be
1299 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001300 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001301 HSub* sub = input->AsSub();
1302 HSub* new_sub =
1303 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1304 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1305 if (!sub->HasUses()) {
1306 sub->GetBlock()->RemoveInstruction(sub);
1307 }
1308 RecordSimplification();
1309 }
1310}
1311
1312void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1313 HInstruction* input = instruction->GetInput();
1314 if (input->IsNot()) {
1315 // Replace code looking like
1316 // NOT tmp, src
1317 // NOT dst, tmp
1318 // with
1319 // src
1320 // We perform the optimization even if the input negation has environment
1321 // uses since it allows removing the current instruction. But we only delete
1322 // the input negation only if it is does not have any uses left.
1323 HNot* previous_not = input->AsNot();
1324 instruction->ReplaceWith(previous_not->GetInput());
1325 instruction->GetBlock()->RemoveInstruction(instruction);
1326 if (!previous_not->HasUses()) {
1327 previous_not->GetBlock()->RemoveInstruction(previous_not);
1328 }
1329 RecordSimplification();
1330 }
1331}
1332
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001333void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1334 HConstant* input_cst = instruction->GetConstantRight();
1335 HInstruction* input_other = instruction->GetLeastConstantLeft();
1336
Roland Levillain1a653882016-03-18 18:05:57 +00001337 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001338 // Replace code looking like
1339 // OR dst, src, 0
1340 // with
1341 // src
1342 instruction->ReplaceWith(input_other);
1343 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001344 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001345 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);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001358 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001359 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001360 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001361
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001362 if (TryDeMorganNegationFactoring(instruction)) return;
1363
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001364 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001365}
1366
1367void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1368 VisitShift(instruction);
1369}
1370
1371void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1372 VisitShift(instruction);
1373}
1374
1375void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1376 HConstant* input_cst = instruction->GetConstantRight();
1377 HInstruction* input_other = instruction->GetLeastConstantLeft();
1378
Serguei Katkov115b53f2015-08-05 17:03:30 +06001379 Primitive::Type type = instruction->GetType();
1380 if (Primitive::IsFloatingPointType(type)) {
1381 return;
1382 }
1383
Roland Levillain1a653882016-03-18 18:05:57 +00001384 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001385 // Replace code looking like
1386 // SUB dst, src, 0
1387 // with
1388 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001389 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1390 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1391 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001392 instruction->ReplaceWith(input_other);
1393 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001394 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001395 return;
1396 }
1397
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001398 HBasicBlock* block = instruction->GetBlock();
1399 ArenaAllocator* allocator = GetGraph()->GetArena();
1400
Alexandre Rames188d4312015-04-09 18:30:21 +01001401 HInstruction* left = instruction->GetLeft();
1402 HInstruction* right = instruction->GetRight();
1403 if (left->IsConstant()) {
1404 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001405 // Replace code looking like
1406 // SUB dst, 0, src
1407 // with
1408 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001409 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001410 // `x` is `0.0`, the former expression yields `0.0`, while the later
1411 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001412 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001413 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001414 RecordSimplification();
1415 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001416 }
1417 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001418
1419 if (left->IsNeg() && right->IsNeg()) {
1420 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1421 return;
1422 }
1423 }
1424
1425 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1426 // Replace code looking like
1427 // NEG tmp, b
1428 // SUB dst, a, tmp
1429 // with
1430 // ADD dst, a, b
1431 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1432 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1433 RecordSimplification();
1434 right->GetBlock()->RemoveInstruction(right);
1435 return;
1436 }
1437
1438 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1439 // Replace code looking like
1440 // NEG tmp, a
1441 // SUB dst, tmp, b
1442 // with
1443 // ADD tmp, a, b
1444 // NEG dst, tmp
1445 // The second version is not intrinsically better, but enables more
1446 // transformations.
1447 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1448 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1449 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1450 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1451 instruction->ReplaceWith(neg);
1452 instruction->GetBlock()->RemoveInstruction(instruction);
1453 RecordSimplification();
1454 left->GetBlock()->RemoveInstruction(left);
1455 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001456}
1457
1458void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1459 VisitShift(instruction);
1460}
1461
1462void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1463 HConstant* input_cst = instruction->GetConstantRight();
1464 HInstruction* input_other = instruction->GetLeastConstantLeft();
1465
Roland Levillain1a653882016-03-18 18:05:57 +00001466 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001467 // Replace code looking like
1468 // XOR dst, src, 0
1469 // with
1470 // src
1471 instruction->ReplaceWith(input_other);
1472 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001473 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001474 return;
1475 }
1476
1477 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1478 // Replace code looking like
1479 // XOR dst, src, 0xFFF...FF
1480 // with
1481 // NOT dst, src
1482 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1483 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001484 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001485 return;
1486 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001487
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001488 HInstruction* left = instruction->GetLeft();
1489 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001490 if (((left->IsNot() && right->IsNot()) ||
1491 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001492 left->HasOnlyOneNonEnvironmentUse() &&
1493 right->HasOnlyOneNonEnvironmentUse()) {
1494 // Replace code looking like
1495 // NOT nota, a
1496 // NOT notb, b
1497 // XOR dst, nota, notb
1498 // with
1499 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001500 instruction->ReplaceInput(left->InputAt(0), 0);
1501 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001502 left->GetBlock()->RemoveInstruction(left);
1503 right->GetBlock()->RemoveInstruction(right);
1504 RecordSimplification();
1505 return;
1506 }
1507
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001508 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001509}
1510
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001511void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1512 HInstruction* argument = instruction->InputAt(1);
1513 HInstruction* receiver = instruction->InputAt(0);
1514 if (receiver == argument) {
1515 // Because String.equals is an instance call, the receiver is
1516 // a null check if we don't know it's null. The argument however, will
1517 // be the actual object. So we cannot end up in a situation where both
1518 // are equal but could be null.
1519 DCHECK(CanEnsureNotNullAt(argument, instruction));
1520 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1521 instruction->GetBlock()->RemoveInstruction(instruction);
1522 } else {
1523 StringEqualsOptimizations optimizations(instruction);
1524 if (CanEnsureNotNullAt(argument, instruction)) {
1525 optimizations.SetArgumentNotNull();
1526 }
1527 ScopedObjectAccess soa(Thread::Current());
1528 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1529 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1530 optimizations.SetArgumentIsString();
1531 }
1532 }
1533}
1534
Roland Levillain22c49222016-03-18 14:04:28 +00001535void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1536 bool is_left,
1537 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001538 DCHECK(invoke->IsInvokeStaticOrDirect());
1539 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001540 HInstruction* value = invoke->InputAt(0);
1541 HInstruction* distance = invoke->InputAt(1);
1542 // Replace the invoke with an HRor.
1543 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001544 // Unconditionally set the type of the negated distance to `int`,
1545 // as shift and rotate operations expect a 32-bit (or narrower)
1546 // value for their distance input.
1547 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001548 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1549 }
Roland Levillain22c49222016-03-18 14:04:28 +00001550 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001551 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1552 // Remove ClinitCheck and LoadClass, if possible.
1553 HInstruction* clinit = invoke->InputAt(invoke->InputCount() - 1);
1554 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1555 clinit->GetBlock()->RemoveInstruction(clinit);
1556 HInstruction* ldclass = clinit->InputAt(0);
1557 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1558 ldclass->GetBlock()->RemoveInstruction(ldclass);
1559 }
1560 }
1561}
1562
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001563static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1564 if (potential_length->IsArrayLength()) {
1565 return potential_length->InputAt(0) == potential_array;
1566 }
1567
1568 if (potential_array->IsNewArray()) {
1569 return potential_array->InputAt(0) == potential_length;
1570 }
1571
1572 return false;
1573}
1574
1575void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1576 HInstruction* source = instruction->InputAt(0);
1577 HInstruction* destination = instruction->InputAt(2);
1578 HInstruction* count = instruction->InputAt(4);
1579 SystemArrayCopyOptimizations optimizations(instruction);
1580 if (CanEnsureNotNullAt(source, instruction)) {
1581 optimizations.SetSourceIsNotNull();
1582 }
1583 if (CanEnsureNotNullAt(destination, instruction)) {
1584 optimizations.SetDestinationIsNotNull();
1585 }
1586 if (destination == source) {
1587 optimizations.SetDestinationIsSource();
1588 }
1589
1590 if (IsArrayLengthOf(count, source)) {
1591 optimizations.SetCountIsSourceLength();
1592 }
1593
1594 if (IsArrayLengthOf(count, destination)) {
1595 optimizations.SetCountIsDestinationLength();
1596 }
1597
1598 {
1599 ScopedObjectAccess soa(Thread::Current());
1600 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1601 if (destination_rti.IsValid()) {
1602 if (destination_rti.IsObjectArray()) {
1603 if (destination_rti.IsExact()) {
1604 optimizations.SetDoesNotNeedTypeCheck();
1605 }
1606 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001607 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001608 if (destination_rti.IsPrimitiveArrayClass()) {
1609 optimizations.SetDestinationIsPrimitiveArray();
1610 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1611 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001612 }
1613 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001614 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1615 if (source_rti.IsValid()) {
1616 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1617 optimizations.SetDoesNotNeedTypeCheck();
1618 }
1619 if (source_rti.IsPrimitiveArrayClass()) {
1620 optimizations.SetSourceIsPrimitiveArray();
1621 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1622 optimizations.SetSourceIsNonPrimitiveArray();
1623 }
1624 }
1625 }
1626}
1627
Roland Levillaina5c4a402016-03-15 15:02:50 +00001628void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1629 bool is_signum,
1630 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001631 DCHECK(invoke->IsInvokeStaticOrDirect());
1632 uint32_t dex_pc = invoke->GetDexPc();
1633 HInstruction* left = invoke->InputAt(0);
1634 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001635 if (!is_signum) {
1636 right = invoke->InputAt(1);
1637 } else if (type == Primitive::kPrimLong) {
1638 right = GetGraph()->GetLongConstant(0);
1639 } else {
1640 right = GetGraph()->GetIntConstant(0);
1641 }
1642 HCompare* compare = new (GetGraph()->GetArena())
1643 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1644 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1645}
1646
Aart Bik75a38b22016-02-17 10:41:50 -08001647void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1648 DCHECK(invoke->IsInvokeStaticOrDirect());
1649 uint32_t dex_pc = invoke->GetDexPc();
1650 // IsNaN(x) is the same as x != x.
1651 HInstruction* x = invoke->InputAt(0);
1652 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001653 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001654 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1655}
1656
Aart Bik2a6aad92016-02-25 11:32:32 -08001657void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1658 DCHECK(invoke->IsInvokeStaticOrDirect());
1659 uint32_t dex_pc = invoke->GetDexPc();
1660 HInstruction* x = invoke->InputAt(0);
1661 Primitive::Type type = x->GetType();
1662 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1663 HInstruction* nan;
1664 if (type == Primitive::kPrimDouble) {
1665 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1666 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1667 kNeedsEnvironmentOrCache,
1668 kNoSideEffects,
1669 kNoThrow);
1670 } else {
1671 DCHECK_EQ(type, Primitive::kPrimFloat);
1672 nan = GetGraph()->GetIntConstant(0x7fc00000);
1673 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1674 kNeedsEnvironmentOrCache,
1675 kNoSideEffects,
1676 kNoThrow);
1677 }
1678 // Test IsNaN(x), which is the same as x != x.
1679 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1680 condition->SetBias(ComparisonBias::kLtBias);
1681 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1682 // Select between the two.
1683 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1684 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1685 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1686}
1687
Vladimir Markodce016e2016-04-28 13:10:02 +01001688void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1689 HInstruction* str = invoke->InputAt(0);
1690 uint32_t dex_pc = invoke->GetDexPc();
1691 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1692 // so create the HArrayLength.
1693 HArrayLength* length = new (GetGraph()->GetArena()) HArrayLength(str, dex_pc);
1694 length->MarkAsStringLength();
1695 HInstruction* replacement;
1696 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1697 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1698 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1699 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1700 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1701 replacement = equal;
1702 } else {
1703 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1704 replacement = length;
1705 }
1706 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1707}
1708
Aart Bik11932592016-03-08 12:42:25 -08001709void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1710 uint32_t dex_pc = invoke->GetDexPc();
1711 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1712 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1713}
1714
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001715void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001716 switch (instruction->GetIntrinsic()) {
1717 case Intrinsics::kStringEquals:
1718 SimplifyStringEquals(instruction);
1719 break;
1720 case Intrinsics::kSystemArrayCopy:
1721 SimplifySystemArrayCopy(instruction);
1722 break;
1723 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001724 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
1725 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001726 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001727 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001728 break;
1729 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001730 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
1731 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001732 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001733 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001734 break;
1735 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001736 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
1737 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001738 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001739 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001740 break;
1741 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001742 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
1743 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001744 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001745 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001746 break;
1747 case Intrinsics::kFloatIsNaN:
1748 case Intrinsics::kDoubleIsNaN:
1749 SimplifyIsNaN(instruction);
1750 break;
1751 case Intrinsics::kFloatFloatToIntBits:
1752 case Intrinsics::kDoubleDoubleToLongBits:
1753 SimplifyFP2Int(instruction);
1754 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01001755 case Intrinsics::kStringIsEmpty:
1756 case Intrinsics::kStringLength:
1757 SimplifyStringIsEmptyOrLength(instruction);
1758 break;
Aart Bik11932592016-03-08 12:42:25 -08001759 case Intrinsics::kUnsafeLoadFence:
1760 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1761 break;
1762 case Intrinsics::kUnsafeStoreFence:
1763 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1764 break;
1765 case Intrinsics::kUnsafeFullFence:
1766 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1767 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001768 default:
1769 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001770 }
1771}
1772
Aart Bikbb245d12015-10-19 11:05:03 -07001773void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1774 HInstruction* cond = deoptimize->InputAt(0);
1775 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001776 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07001777 // Never deopt: instruction can be removed.
1778 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1779 } else {
1780 // Always deopt.
1781 }
1782 }
1783}
1784
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001785} // namespace art