blob: 62d637081d8c82f99bc0f426e47943c9dd6074ce [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 Marko87f3fcb2016-04-28 15:52:11 +0100104 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100105 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800106 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100107
Calin Juravleacf735c2015-02-12 15:25:22 +0000108 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100109 bool simplification_occurred_ = false;
110 int simplifications_at_current_position_ = 0;
111 // We ensure we do not loop infinitely. The value is a finger in the air guess
112 // that should allow enough simplification.
113 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000114};
115
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100116void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +0000117 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100118 visitor.Run();
119}
120
121void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100122 // Iterate in reverse post order to open up more simplifications to users
123 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +0100124 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
125 // The simplification of an instruction to another instruction may yield
126 // possibilities for other simplifications. So although we perform a reverse
127 // post order visit, we sometimes need to revisit an instruction index.
128 simplification_occurred_ = false;
129 VisitBasicBlock(it.Current());
130 if (simplification_occurred_ &&
131 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
132 // New simplifications may be applicable to the instruction at the
133 // current index, so don't advance the iterator.
134 continue;
135 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100136 simplifications_at_current_position_ = 0;
137 it.Advance();
138 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100139}
140
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000141namespace {
142
143bool AreAllBitsSet(HConstant* constant) {
144 return Int64FromConstant(constant) == -1;
145}
146
147} // namespace
148
Alexandre Rames188d4312015-04-09 18:30:21 +0100149// Returns true if the code was simplified to use only one negation operation
150// after the binary operation instead of one on each of the inputs.
151bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
152 DCHECK(binop->IsAdd() || binop->IsSub());
153 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
154 HNeg* left_neg = binop->GetLeft()->AsNeg();
155 HNeg* right_neg = binop->GetRight()->AsNeg();
156 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
157 !right_neg->HasOnlyOneNonEnvironmentUse()) {
158 return false;
159 }
160 // Replace code looking like
161 // NEG tmp1, a
162 // NEG tmp2, b
163 // ADD dst, tmp1, tmp2
164 // with
165 // ADD tmp, a, b
166 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600167 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
168 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
169 // while the later yields `-0.0`.
170 if (!Primitive::IsIntegralType(binop->GetType())) {
171 return false;
172 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100173 binop->ReplaceInput(left_neg->GetInput(), 0);
174 binop->ReplaceInput(right_neg->GetInput(), 1);
175 left_neg->GetBlock()->RemoveInstruction(left_neg);
176 right_neg->GetBlock()->RemoveInstruction(right_neg);
177 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
178 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
179 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
180 RecordSimplification();
181 return true;
182}
183
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000184bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
185 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
186 Primitive::Type type = op->GetType();
187 HInstruction* left = op->GetLeft();
188 HInstruction* right = op->GetRight();
189
190 // We can apply De Morgan's laws if both inputs are Not's and are only used
191 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000192 if (((left->IsNot() && right->IsNot()) ||
193 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000194 left->HasOnlyOneNonEnvironmentUse() &&
195 right->HasOnlyOneNonEnvironmentUse()) {
196 // Replace code looking like
197 // NOT nota, a
198 // NOT notb, b
199 // AND dst, nota, notb (respectively OR)
200 // with
201 // OR or, a, b (respectively AND)
202 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000203 HInstruction* src_left = left->InputAt(0);
204 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000205 uint32_t dex_pc = op->GetDexPc();
206
207 // Remove the negations on the inputs.
208 left->ReplaceWith(src_left);
209 right->ReplaceWith(src_right);
210 left->GetBlock()->RemoveInstruction(left);
211 right->GetBlock()->RemoveInstruction(right);
212
213 // Replace the `HAnd` or `HOr`.
214 HBinaryOperation* hbin;
215 if (op->IsAnd()) {
216 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
217 } else {
218 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
219 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000220 HInstruction* hnot;
221 if (left->IsBooleanNot()) {
222 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
223 } else {
224 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
225 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000226
227 op->GetBlock()->InsertInstructionBefore(hbin, op);
228 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
229
230 RecordSimplification();
231 return true;
232 }
233
234 return false;
235}
236
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000237void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
238 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
239 HConstant* input_cst = instruction->GetConstantRight();
240 HInstruction* input_other = instruction->GetLeastConstantLeft();
241
Mark Mendellba56d062015-05-05 21:34:03 -0400242 if (input_cst != nullptr) {
Vladimir Marko164306e2016-03-15 14:57:32 +0000243 int64_t cst = Int64FromConstant(input_cst);
Roland Levillain5b5b9312016-03-22 14:57:31 +0000244 int64_t mask = (input_other->GetType() == Primitive::kPrimLong)
245 ? kMaxLongShiftDistance
246 : kMaxIntShiftDistance;
Vladimir Marko164306e2016-03-15 14:57:32 +0000247 if ((cst & mask) == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400248 // Replace code looking like
249 // SHL dst, src, 0
250 // with
251 // src
252 instruction->ReplaceWith(input_other);
253 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100254 RecordSimplification();
Mark Mendellba56d062015-05-05 21:34:03 -0400255 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000256 }
257}
258
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000259static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
260 return (sub->GetRight() == other &&
261 sub->GetLeft()->IsConstant() &&
262 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
263}
264
265bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
266 HUShr* ushr,
267 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000268 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
269 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000270 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
271 if (!ushr->HasUses()) {
272 ushr->GetBlock()->RemoveInstruction(ushr);
273 }
274 if (!ushr->GetRight()->HasUses()) {
275 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
276 }
277 if (!shl->HasUses()) {
278 shl->GetBlock()->RemoveInstruction(shl);
279 }
280 if (!shl->GetRight()->HasUses()) {
281 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
282 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100283 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000284 return true;
285}
286
287// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
288bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000289 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
290 HInstruction* left = op->GetLeft();
291 HInstruction* right = op->GetRight();
292 // If we have an UShr and a Shl (in either order).
293 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
294 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
295 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
296 DCHECK(Primitive::IsIntOrLongType(ushr->GetType()));
297 if (ushr->GetType() == shl->GetType() &&
298 ushr->GetLeft() == shl->GetLeft()) {
299 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
300 // Shift distances are both constant, try replacing with Ror if they
301 // add up to the register size.
302 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
303 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
304 // Shift distances are potentially of the form x and (reg_size - x).
305 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
306 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
307 // Shift distances are potentially of the form d and -d.
308 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
309 }
310 }
311 }
312 return false;
313}
314
315// Try replacing code looking like (x >>> #rdist OP x << #ldist):
316// UShr dst, x, #rdist
317// Shl tmp, x, #ldist
318// OP dst, dst, tmp
319// or like (x >>> #rdist OP x << #-ldist):
320// UShr dst, x, #rdist
321// Shl tmp, x, #-ldist
322// OP dst, dst, tmp
323// with
324// Ror dst, x, #rdist
325bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
326 HUShr* ushr,
327 HShl* shl) {
328 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
329 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
330 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
331 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
332 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
333 ReplaceRotateWithRor(op, ushr, shl);
334 return true;
335 }
336 return false;
337}
338
339// Replace code looking like (x >>> -d OP x << d):
340// Neg neg, d
341// UShr dst, x, neg
342// Shl tmp, x, d
343// OP dst, dst, tmp
344// with
345// Neg neg, d
346// Ror dst, x, neg
347// *** OR ***
348// Replace code looking like (x >>> d OP x << -d):
349// UShr dst, x, d
350// Neg neg, d
351// Shl tmp, x, neg
352// OP dst, dst, tmp
353// with
354// Ror dst, x, d
355bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
356 HUShr* ushr,
357 HShl* shl) {
358 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
359 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
360 bool neg_is_left = shl->GetRight()->IsNeg();
361 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
362 // And the shift distance being negated is the distance being shifted the other way.
363 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
364 ReplaceRotateWithRor(op, ushr, shl);
365 }
366 return false;
367}
368
369// Try replacing code looking like (x >>> d OP x << (#bits - d)):
370// UShr dst, x, d
371// Sub ld, #bits, d
372// Shl tmp, x, ld
373// OP dst, dst, tmp
374// with
375// Ror dst, x, d
376// *** OR ***
377// Replace code looking like (x >>> (#bits - d) OP x << d):
378// Sub rd, #bits, d
379// UShr dst, x, rd
380// Shl tmp, x, d
381// OP dst, dst, tmp
382// with
383// Neg neg, d
384// Ror dst, x, neg
385bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
386 HUShr* ushr,
387 HShl* shl) {
388 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
389 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
390 size_t reg_bits = Primitive::ComponentSize(ushr->GetType()) * kBitsPerByte;
391 HInstruction* shl_shift = shl->GetRight();
392 HInstruction* ushr_shift = ushr->GetRight();
393 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
394 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
395 return ReplaceRotateWithRor(op, ushr, shl);
396 }
397 return false;
398}
399
Calin Juravle10e244f2015-01-26 18:54:32 +0000400void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
401 HInstruction* obj = null_check->InputAt(0);
402 if (!obj->CanBeNull()) {
403 null_check->ReplaceWith(obj);
404 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000405 if (stats_ != nullptr) {
406 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
407 }
408 }
409}
410
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100411bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
412 if (!input->CanBeNull()) {
413 return true;
414 }
415
Vladimir Marko46817b82016-03-29 12:21:58 +0100416 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
417 HInstruction* user = use.GetUser();
418 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100419 return true;
420 }
421 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100422
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100423 return false;
424}
425
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100426// Returns whether doing a type test between the class of `object` against `klass` has
427// a statically known outcome. The result of the test is stored in `outcome`.
428static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000429 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
430 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
431 ScopedObjectAccess soa(Thread::Current());
432 if (!obj_rti.IsValid()) {
433 // We run the simplifier before the reference type propagation so type info might not be
434 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100435 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000436 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100437
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100438 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100439 if (!class_rti.IsValid()) {
440 // Happens when the loaded class is unresolved.
441 return false;
442 }
443 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000444 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100445 *outcome = true;
446 return true;
447 } else if (obj_rti.IsExact()) {
448 // The test failed at compile time so will also fail at runtime.
449 *outcome = false;
450 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100451 } else if (!class_rti.IsInterface()
452 && !obj_rti.IsInterface()
453 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100454 // Different type hierarchy. The test will fail.
455 *outcome = false;
456 return true;
457 }
458 return false;
459}
460
461void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
462 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100463 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
464 if (load_class->NeedsAccessCheck()) {
465 // If we need to perform an access check we cannot remove the instruction.
466 return;
467 }
468
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100469 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100470 check_cast->ClearMustDoNullCheck();
471 }
472
473 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000474 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000475 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100476 return;
477 }
478
Vladimir Markoa65ed302016-03-14 21:21:29 +0000479 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
480 // the return value check with the `outcome` check, b/27651442 .
481 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700482 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100483 if (outcome) {
484 check_cast->GetBlock()->RemoveInstruction(check_cast);
Calin Juravle69158982016-03-16 11:53:41 +0000485 MaybeRecordStat(MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700486 if (!load_class->HasUses()) {
487 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
488 // However, here we know that it cannot because the checkcast was successfull, hence
489 // the class was already loaded.
490 load_class->GetBlock()->RemoveInstruction(load_class);
491 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100492 } else {
493 // Don't do anything for exceptional cases for now. Ideally we should remove
494 // all instructions and blocks this instruction dominates.
495 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000496 }
497}
498
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100499void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100500 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100501 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
502 if (load_class->NeedsAccessCheck()) {
503 // If we need to perform an access check we cannot remove the instruction.
504 return;
505 }
506
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100507 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100508 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100509 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100510 instruction->ClearMustDoNullCheck();
511 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100512
513 HGraph* graph = GetGraph();
514 if (object->IsNullConstant()) {
Calin Juravle69158982016-03-16 11:53:41 +0000515 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100516 instruction->ReplaceWith(graph->GetIntConstant(0));
517 instruction->GetBlock()->RemoveInstruction(instruction);
518 RecordSimplification();
519 return;
520 }
521
Vladimir Marko24bd8952016-03-15 10:40:33 +0000522 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
523 // the return value check with the `outcome` check, b/27651442 .
524 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700525 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Calin Juravle69158982016-03-16 11:53:41 +0000526 MaybeRecordStat(kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100527 if (outcome && can_be_null) {
528 // Type test will succeed, we just need a null test.
529 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
530 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
531 instruction->ReplaceWith(test);
532 } else {
533 // We've statically determined the result of the instanceof.
534 instruction->ReplaceWith(graph->GetIntConstant(outcome));
535 }
536 RecordSimplification();
537 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700538 if (outcome && !load_class->HasUses()) {
539 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
540 // However, here we know that it cannot because the instanceof check was successfull, hence
541 // the class was already loaded.
542 load_class->GetBlock()->RemoveInstruction(load_class);
543 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100544 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100545}
546
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100547void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
548 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100549 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100550 instruction->ClearValueCanBeNull();
551 }
552}
553
554void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
555 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100556 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100557 instruction->ClearValueCanBeNull();
558 }
559}
560
Anton Shaminbdd79352016-02-15 12:48:36 +0600561static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
562 HInstruction *lhs = cond->InputAt(0);
563 HInstruction *rhs = cond->InputAt(1);
564 switch (cond->GetKind()) {
565 case HInstruction::kEqual:
566 return new (arena) HEqual(rhs, lhs);
567 case HInstruction::kNotEqual:
568 return new (arena) HNotEqual(rhs, lhs);
569 case HInstruction::kLessThan:
570 return new (arena) HGreaterThan(rhs, lhs);
571 case HInstruction::kLessThanOrEqual:
572 return new (arena) HGreaterThanOrEqual(rhs, lhs);
573 case HInstruction::kGreaterThan:
574 return new (arena) HLessThan(rhs, lhs);
575 case HInstruction::kGreaterThanOrEqual:
576 return new (arena) HLessThanOrEqual(rhs, lhs);
577 case HInstruction::kBelow:
578 return new (arena) HAbove(rhs, lhs);
579 case HInstruction::kBelowOrEqual:
580 return new (arena) HAboveOrEqual(rhs, lhs);
581 case HInstruction::kAbove:
582 return new (arena) HBelow(rhs, lhs);
583 case HInstruction::kAboveOrEqual:
584 return new (arena) HBelowOrEqual(rhs, lhs);
585 default:
586 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
587 }
588 return nullptr;
589}
590
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000591void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100592 HInstruction* input_const = equal->GetConstantRight();
593 if (input_const != nullptr) {
594 HInstruction* input_value = equal->GetLeastConstantLeft();
595 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
596 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100597 // We are comparing the boolean to a constant which is of type int and can
598 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000599 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100600 // Replace (bool_value == true) with bool_value
601 equal->ReplaceWith(input_value);
602 block->RemoveInstruction(equal);
603 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000604 } else if (input_const->AsIntConstant()->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500605 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
606 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100607 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100608 } else {
609 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
610 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
611 block->RemoveInstruction(equal);
612 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100613 }
Mark Mendellc4701932015-04-10 13:18:51 -0400614 } else {
615 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100616 }
Mark Mendellc4701932015-04-10 13:18:51 -0400617 } else {
618 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100619 }
620}
621
David Brazdil0d13fee2015-04-17 14:52:19 +0100622void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
623 HInstruction* input_const = not_equal->GetConstantRight();
624 if (input_const != nullptr) {
625 HInstruction* input_value = not_equal->GetLeastConstantLeft();
626 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
627 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100628 // We are comparing the boolean to a constant which is of type int and can
629 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000630 if (input_const->AsIntConstant()->IsTrue()) {
Mark Mendellf6529172015-11-17 11:16:56 -0500631 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
632 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100633 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000634 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100635 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100636 not_equal->ReplaceWith(input_value);
637 block->RemoveInstruction(not_equal);
638 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100639 } else {
640 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
641 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
642 block->RemoveInstruction(not_equal);
643 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100644 }
Mark Mendellc4701932015-04-10 13:18:51 -0400645 } else {
646 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100647 }
Mark Mendellc4701932015-04-10 13:18:51 -0400648 } else {
649 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100650 }
651}
652
653void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000654 HInstruction* input = bool_not->InputAt(0);
655 HInstruction* replace_with = nullptr;
656
657 if (input->IsIntConstant()) {
658 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000659 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000660 replace_with = GetGraph()->GetIntConstant(0);
661 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000662 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000663 replace_with = GetGraph()->GetIntConstant(1);
664 }
665 } else if (input->IsBooleanNot()) {
666 // Replace (!(!bool_value)) with bool_value.
667 replace_with = input->InputAt(0);
668 } else if (input->IsCondition() &&
669 // Don't change FP compares. The definition of compares involving
670 // NaNs forces the compares to be done as written by the user.
671 !Primitive::IsFloatingPointType(input->InputAt(0)->GetType())) {
672 // Replace condition with its opposite.
673 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
674 }
675
676 if (replace_with != nullptr) {
677 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100678 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000679 RecordSimplification();
680 }
681}
682
683void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
684 HInstruction* replace_with = nullptr;
685 HInstruction* condition = select->GetCondition();
686 HInstruction* true_value = select->GetTrueValue();
687 HInstruction* false_value = select->GetFalseValue();
688
689 if (condition->IsBooleanNot()) {
690 // Change ((!cond) ? x : y) to (cond ? y : x).
691 condition = condition->InputAt(0);
692 std::swap(true_value, false_value);
693 select->ReplaceInput(false_value, 0);
694 select->ReplaceInput(true_value, 1);
695 select->ReplaceInput(condition, 2);
696 RecordSimplification();
697 }
698
699 if (true_value == false_value) {
700 // Replace (cond ? x : x) with (x).
701 replace_with = true_value;
702 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000703 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000704 // Replace (true ? x : y) with (x).
705 replace_with = true_value;
706 } else {
707 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000708 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000709 replace_with = false_value;
710 }
711 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000712 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000713 // Replace (cond ? true : false) with (cond).
714 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000715 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000716 // Replace (cond ? false : true) with (!cond).
717 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
718 }
719 }
720
721 if (replace_with != nullptr) {
722 select->ReplaceWith(replace_with);
723 select->GetBlock()->RemoveInstruction(select);
724 RecordSimplification();
725 }
726}
727
728void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
729 HInstruction* condition = instruction->InputAt(0);
730 if (condition->IsBooleanNot()) {
731 // Swap successors if input is negated.
732 instruction->ReplaceInput(condition->InputAt(0), 0);
733 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100734 RecordSimplification();
735 }
736}
737
Mingyao Yang0304e182015-01-30 16:41:29 -0800738void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
739 HInstruction* input = instruction->InputAt(0);
740 // If the array is a NewArray with constant size, replace the array length
741 // with the constant instruction. This helps the bounds check elimination phase.
742 if (input->IsNewArray()) {
743 input = input->InputAt(0);
744 if (input->IsIntConstant()) {
745 instruction->ReplaceWith(input);
746 }
747 }
748}
749
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000750void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000751 HInstruction* value = instruction->GetValue();
752 if (value->GetType() != Primitive::kPrimNot) return;
753
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100754 if (CanEnsureNotNullAt(value, instruction)) {
755 instruction->ClearValueCanBeNull();
756 }
757
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000758 if (value->IsArrayGet()) {
759 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
760 // If the code is just swapping elements in the array, no need for a type check.
761 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100762 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000763 }
764 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100765
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100766 if (value->IsNullConstant()) {
767 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100768 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100769 }
770
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100771 ScopedObjectAccess soa(Thread::Current());
772 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
773 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
774 if (!array_rti.IsValid()) {
775 return;
776 }
777
778 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
779 instruction->ClearNeedsTypeCheck();
780 return;
781 }
782
783 if (array_rti.IsObjectArray()) {
784 if (array_rti.IsExact()) {
785 instruction->ClearNeedsTypeCheck();
786 return;
787 }
788 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100789 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000790}
791
Vladimir Markob52bbde2016-02-12 12:06:05 +0000792static bool IsTypeConversionImplicit(Primitive::Type input_type, Primitive::Type result_type) {
Roland Levillainf355c3f2016-03-30 19:09:03 +0100793 // Invariant: We should never generate a conversion to a Boolean value.
794 DCHECK_NE(Primitive::kPrimBoolean, result_type);
795
Vladimir Markob52bbde2016-02-12 12:06:05 +0000796 // Besides conversion to the same type, widening integral conversions are implicit,
797 // excluding conversions to long and the byte->char conversion where we need to
798 // clear the high 16 bits of the 32-bit sign-extended representation of byte.
799 return result_type == input_type ||
Roland Levillainf355c3f2016-03-30 19:09:03 +0100800 (result_type == Primitive::kPrimInt && (input_type == Primitive::kPrimBoolean ||
801 input_type == Primitive::kPrimByte ||
802 input_type == Primitive::kPrimShort ||
803 input_type == Primitive::kPrimChar)) ||
804 (result_type == Primitive::kPrimChar && input_type == Primitive::kPrimBoolean) ||
805 (result_type == Primitive::kPrimShort && (input_type == Primitive::kPrimBoolean ||
806 input_type == Primitive::kPrimByte)) ||
807 (result_type == Primitive::kPrimByte && input_type == Primitive::kPrimBoolean);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000808}
809
810static bool IsTypeConversionLossless(Primitive::Type input_type, Primitive::Type result_type) {
811 // The conversion to a larger type is loss-less with the exception of two cases,
812 // - conversion to char, the only unsigned type, where we may lose some bits, and
813 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
814 // For integral to FP conversions this holds because the FP mantissa is large enough.
815 DCHECK_NE(input_type, result_type);
816 return Primitive::ComponentSize(result_type) > Primitive::ComponentSize(input_type) &&
817 result_type != Primitive::kPrimChar &&
818 !(result_type == Primitive::kPrimLong && input_type == Primitive::kPrimFloat);
819}
820
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000821void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +0000822 HInstruction* input = instruction->GetInput();
823 Primitive::Type input_type = input->GetType();
824 Primitive::Type result_type = instruction->GetResultType();
825 if (IsTypeConversionImplicit(input_type, result_type)) {
826 // Remove the implicit conversion; this includes conversion to the same type.
827 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000828 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +0000829 RecordSimplification();
830 return;
831 }
832
833 if (input->IsTypeConversion()) {
834 HTypeConversion* input_conversion = input->AsTypeConversion();
835 HInstruction* original_input = input_conversion->GetInput();
836 Primitive::Type original_type = original_input->GetType();
837
838 // When the first conversion is lossless, a direct conversion from the original type
839 // to the final type yields the same result, even for a lossy second conversion, for
840 // example float->double->int or int->double->float.
841 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
842
843 // For integral conversions, see if the first conversion loses only bits that the second
844 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
845 // conversion yields the same result, for example long->int->short or int->char->short.
846 bool integral_conversions_with_non_widening_second =
847 Primitive::IsIntegralType(input_type) &&
848 Primitive::IsIntegralType(original_type) &&
849 Primitive::IsIntegralType(result_type) &&
850 Primitive::ComponentSize(result_type) <= Primitive::ComponentSize(input_type);
851
852 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
853 // If the merged conversion is implicit, do the simplification unconditionally.
854 if (IsTypeConversionImplicit(original_type, result_type)) {
855 instruction->ReplaceWith(original_input);
856 instruction->GetBlock()->RemoveInstruction(instruction);
857 if (!input_conversion->HasUses()) {
858 // Don't wait for DCE.
859 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
860 }
861 RecordSimplification();
862 return;
863 }
864 // Otherwise simplify only if the first conversion has no other use.
865 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
866 input_conversion->ReplaceWith(original_input);
867 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
868 RecordSimplification();
869 return;
870 }
871 }
Vladimir Marko625090f2016-03-14 18:00:05 +0000872 } else if (input->IsAnd() && Primitive::IsIntegralType(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +0000873 DCHECK(Primitive::IsIntegralType(input_type));
874 HAnd* input_and = input->AsAnd();
875 HConstant* constant = input_and->GetConstantRight();
876 if (constant != nullptr) {
877 int64_t value = Int64FromConstant(constant);
878 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
879 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
880 if (trailing_ones >= kBitsPerByte * Primitive::ComponentSize(result_type)) {
881 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +0000882 HInstruction* original_input = input_and->GetLeastConstantLeft();
883 if (IsTypeConversionImplicit(original_input->GetType(), result_type)) {
884 instruction->ReplaceWith(original_input);
885 instruction->GetBlock()->RemoveInstruction(instruction);
886 RecordSimplification();
887 return;
888 } else if (input->HasOnlyOneNonEnvironmentUse()) {
889 input_and->ReplaceWith(original_input);
890 input_and->GetBlock()->RemoveInstruction(input_and);
891 RecordSimplification();
892 return;
893 }
Vladimir Marko8428bd32016-02-12 16:53:57 +0000894 }
895 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000896 }
897}
898
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000899void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
900 HConstant* input_cst = instruction->GetConstantRight();
901 HInstruction* input_other = instruction->GetLeastConstantLeft();
Roland Levillain1a653882016-03-18 18:05:57 +0000902 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000903 // Replace code looking like
904 // ADD dst, src, 0
905 // with
906 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600907 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
908 // `x` is `-0.0`, the former expression yields `0.0`, while the later
909 // yields `-0.0`.
910 if (Primitive::IsIntegralType(instruction->GetType())) {
911 instruction->ReplaceWith(input_other);
912 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100913 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +0600914 return;
915 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100916 }
917
918 HInstruction* left = instruction->GetLeft();
919 HInstruction* right = instruction->GetRight();
920 bool left_is_neg = left->IsNeg();
921 bool right_is_neg = right->IsNeg();
922
923 if (left_is_neg && right_is_neg) {
924 if (TryMoveNegOnInputsAfterBinop(instruction)) {
925 return;
926 }
927 }
928
929 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
930 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
931 // Replace code looking like
932 // NEG tmp, b
933 // ADD dst, a, tmp
934 // with
935 // SUB dst, a, b
936 // We do not perform the optimization if the input negation has environment
937 // uses or multiple non-environment uses as it could lead to worse code. In
938 // particular, we do not want the live range of `b` to be extended if we are
939 // not sure the initial 'NEG' instruction can be removed.
940 HInstruction* other = left_is_neg ? right : left;
941 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
942 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
943 RecordSimplification();
944 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000945 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000946 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000947
948 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000949}
950
951void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
952 HConstant* input_cst = instruction->GetConstantRight();
953 HInstruction* input_other = instruction->GetLeastConstantLeft();
954
Vladimir Marko452c1b62015-09-25 14:44:17 +0100955 if (input_cst != nullptr) {
956 int64_t value = Int64FromConstant(input_cst);
957 if (value == -1) {
958 // Replace code looking like
959 // AND dst, src, 0xFFF...FF
960 // with
961 // src
962 instruction->ReplaceWith(input_other);
963 instruction->GetBlock()->RemoveInstruction(instruction);
964 RecordSimplification();
965 return;
966 }
967 // Eliminate And from UShr+And if the And-mask contains all the bits that
968 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
969 // precisely clears the shifted-in sign bits.
970 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
971 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
972 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
973 size_t num_tail_bits_set = CTZ(value + 1);
974 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
975 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
976 instruction->ReplaceWith(input_other);
977 instruction->GetBlock()->RemoveInstruction(instruction);
978 RecordSimplification();
979 return;
980 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
981 input_other->HasOnlyOneNonEnvironmentUse()) {
982 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
983 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
984 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
985 input_other->InputAt(0),
986 input_other->InputAt(1),
987 input_other->GetDexPc());
988 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
989 input_other->GetBlock()->RemoveInstruction(input_other);
990 RecordSimplification();
991 return;
992 }
993 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000994 }
995
996 // We assume that GVN has run before, so we only perform a pointer comparison.
997 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100998 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000999 if (instruction->GetLeft() == instruction->GetRight()) {
1000 // Replace code looking like
1001 // AND dst, src, src
1002 // with
1003 // src
1004 instruction->ReplaceWith(instruction->GetLeft());
1005 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001006 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001007 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001008 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001009
1010 TryDeMorganNegationFactoring(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001011}
1012
Mark Mendellc4701932015-04-10 13:18:51 -04001013void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1014 VisitCondition(condition);
1015}
1016
1017void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1018 VisitCondition(condition);
1019}
1020
1021void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1022 VisitCondition(condition);
1023}
1024
1025void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1026 VisitCondition(condition);
1027}
1028
Anton Shaminbdd79352016-02-15 12:48:36 +06001029void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1030 VisitCondition(condition);
1031}
1032
1033void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1034 VisitCondition(condition);
1035}
1036
1037void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1038 VisitCondition(condition);
1039}
1040
1041void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1042 VisitCondition(condition);
1043}
Aart Bike9f37602015-10-09 11:15:55 -07001044
Mark Mendellc4701932015-04-10 13:18:51 -04001045void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Anton Shaminbdd79352016-02-15 12:48:36 +06001046 // Reverse condition if left is constant. Our code generators prefer constant
1047 // on the right hand side.
1048 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1049 HBasicBlock* block = condition->GetBlock();
1050 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1051 // If it is a fp we must set the opposite bias.
1052 if (replacement != nullptr) {
1053 if (condition->IsLtBias()) {
1054 replacement->SetBias(ComparisonBias::kGtBias);
1055 } else if (condition->IsGtBias()) {
1056 replacement->SetBias(ComparisonBias::kLtBias);
1057 }
1058 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1059 RecordSimplification();
1060
1061 condition = replacement;
1062 }
1063 }
Mark Mendellc4701932015-04-10 13:18:51 -04001064
Mark Mendellc4701932015-04-10 13:18:51 -04001065 HInstruction* left = condition->GetLeft();
1066 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001067
1068 // Try to fold an HCompare into this HCondition.
1069
Mark Mendellc4701932015-04-10 13:18:51 -04001070 // We can only replace an HCondition which compares a Compare to 0.
1071 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1072 // condition with a long, float or double comparison as input.
1073 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1074 // Conversion is not possible.
1075 return;
1076 }
1077
1078 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001079 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001080 // Someone else also wants the result of the compare.
1081 return;
1082 }
1083
Vladimir Marko46817b82016-03-29 12:21:58 +01001084 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001085 // There is a reference to the compare result in an environment. Do we really need it?
1086 if (GetGraph()->IsDebuggable()) {
1087 return;
1088 }
1089
1090 // We have to ensure that there are no deopt points in the sequence.
1091 if (left->HasAnyEnvironmentUseBefore(condition)) {
1092 return;
1093 }
1094 }
1095
1096 // Clean up any environment uses from the HCompare, if any.
1097 left->RemoveEnvironmentUsers();
1098
1099 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1100 condition->SetBias(left->AsCompare()->GetBias());
1101
1102 // Replace the operands of the HCondition.
1103 condition->ReplaceInput(left->InputAt(0), 0);
1104 condition->ReplaceInput(left->InputAt(1), 1);
1105
1106 // Remove the HCompare.
1107 left->GetBlock()->RemoveInstruction(left);
1108
1109 RecordSimplification();
1110}
1111
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001112void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1113 HConstant* input_cst = instruction->GetConstantRight();
1114 HInstruction* input_other = instruction->GetLeastConstantLeft();
1115 Primitive::Type type = instruction->GetType();
1116
1117 if ((input_cst != nullptr) && input_cst->IsOne()) {
1118 // Replace code looking like
1119 // DIV dst, src, 1
1120 // with
1121 // src
1122 instruction->ReplaceWith(input_other);
1123 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001124 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001125 return;
1126 }
1127
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001128 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001129 // Replace code looking like
1130 // DIV dst, src, -1
1131 // with
1132 // NEG dst, src
1133 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001134 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001135 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001136 return;
1137 }
1138
1139 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
1140 // Try replacing code looking like
1141 // DIV dst, src, constant
1142 // with
1143 // MUL dst, src, 1 / constant
1144 HConstant* reciprocal = nullptr;
1145 if (type == Primitive::Primitive::kPrimDouble) {
1146 double value = input_cst->AsDoubleConstant()->GetValue();
1147 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1148 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1149 }
1150 } else {
1151 DCHECK_EQ(type, Primitive::kPrimFloat);
1152 float value = input_cst->AsFloatConstant()->GetValue();
1153 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1154 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1155 }
1156 }
1157
1158 if (reciprocal != nullptr) {
1159 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1160 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1161 RecordSimplification();
1162 return;
1163 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001164 }
1165}
1166
1167void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1168 HConstant* input_cst = instruction->GetConstantRight();
1169 HInstruction* input_other = instruction->GetLeastConstantLeft();
1170 Primitive::Type type = instruction->GetType();
1171 HBasicBlock* block = instruction->GetBlock();
1172 ArenaAllocator* allocator = GetGraph()->GetArena();
1173
1174 if (input_cst == nullptr) {
1175 return;
1176 }
1177
1178 if (input_cst->IsOne()) {
1179 // Replace code looking like
1180 // MUL dst, src, 1
1181 // with
1182 // src
1183 instruction->ReplaceWith(input_other);
1184 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001185 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001186 return;
1187 }
1188
1189 if (input_cst->IsMinusOne() &&
1190 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
1191 // Replace code looking like
1192 // MUL dst, src, -1
1193 // with
1194 // NEG dst, src
1195 HNeg* neg = new (allocator) HNeg(type, input_other);
1196 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001197 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001198 return;
1199 }
1200
1201 if (Primitive::IsFloatingPointType(type) &&
1202 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1203 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1204 // Replace code looking like
1205 // FP_MUL dst, src, 2.0
1206 // with
1207 // FP_ADD dst, src, src
1208 // The 'int' and 'long' cases are handled below.
1209 block->ReplaceAndRemoveInstructionWith(instruction,
1210 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001211 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001212 return;
1213 }
1214
1215 if (Primitive::IsIntOrLongType(type)) {
1216 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001217 // Even though constant propagation also takes care of the zero case, other
1218 // optimizations can lead to having a zero multiplication.
1219 if (factor == 0) {
1220 // Replace code looking like
1221 // MUL dst, src, 0
1222 // with
1223 // 0
1224 instruction->ReplaceWith(input_cst);
1225 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001226 RecordSimplification();
Serguei Katkov53849192015-04-20 14:22:27 +06001227 } 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));
Roland Levillain22c49222016-03-18 14:04:28 +00001233 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001234 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
Roland Levillain1a653882016-03-18 18:05:57 +00001338 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001339 // Replace code looking like
1340 // OR dst, src, 0
1341 // with
1342 // src
1343 instruction->ReplaceWith(input_other);
1344 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001345 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001346 return;
1347 }
1348
1349 // We assume that GVN has run before, so we only perform a pointer comparison.
1350 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001351 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001352 if (instruction->GetLeft() == instruction->GetRight()) {
1353 // Replace code looking like
1354 // OR dst, src, src
1355 // with
1356 // src
1357 instruction->ReplaceWith(instruction->GetLeft());
1358 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001359 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001360 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001361 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001362
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001363 if (TryDeMorganNegationFactoring(instruction)) return;
1364
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001365 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001366}
1367
1368void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1369 VisitShift(instruction);
1370}
1371
1372void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1373 VisitShift(instruction);
1374}
1375
1376void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1377 HConstant* input_cst = instruction->GetConstantRight();
1378 HInstruction* input_other = instruction->GetLeastConstantLeft();
1379
Serguei Katkov115b53f2015-08-05 17:03:30 +06001380 Primitive::Type type = instruction->GetType();
1381 if (Primitive::IsFloatingPointType(type)) {
1382 return;
1383 }
1384
Roland Levillain1a653882016-03-18 18:05:57 +00001385 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001386 // Replace code looking like
1387 // SUB dst, src, 0
1388 // with
1389 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001390 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1391 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1392 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001393 instruction->ReplaceWith(input_other);
1394 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001395 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001396 return;
1397 }
1398
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001399 HBasicBlock* block = instruction->GetBlock();
1400 ArenaAllocator* allocator = GetGraph()->GetArena();
1401
Alexandre Rames188d4312015-04-09 18:30:21 +01001402 HInstruction* left = instruction->GetLeft();
1403 HInstruction* right = instruction->GetRight();
1404 if (left->IsConstant()) {
1405 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001406 // Replace code looking like
1407 // SUB dst, 0, src
1408 // with
1409 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001410 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001411 // `x` is `0.0`, the former expression yields `0.0`, while the later
1412 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001413 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001414 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001415 RecordSimplification();
1416 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001417 }
1418 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001419
1420 if (left->IsNeg() && right->IsNeg()) {
1421 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1422 return;
1423 }
1424 }
1425
1426 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1427 // Replace code looking like
1428 // NEG tmp, b
1429 // SUB dst, a, tmp
1430 // with
1431 // ADD dst, a, b
1432 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1433 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1434 RecordSimplification();
1435 right->GetBlock()->RemoveInstruction(right);
1436 return;
1437 }
1438
1439 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1440 // Replace code looking like
1441 // NEG tmp, a
1442 // SUB dst, tmp, b
1443 // with
1444 // ADD tmp, a, b
1445 // NEG dst, tmp
1446 // The second version is not intrinsically better, but enables more
1447 // transformations.
1448 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1449 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1450 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1451 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1452 instruction->ReplaceWith(neg);
1453 instruction->GetBlock()->RemoveInstruction(instruction);
1454 RecordSimplification();
1455 left->GetBlock()->RemoveInstruction(left);
1456 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001457}
1458
1459void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1460 VisitShift(instruction);
1461}
1462
1463void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1464 HConstant* input_cst = instruction->GetConstantRight();
1465 HInstruction* input_other = instruction->GetLeastConstantLeft();
1466
Roland Levillain1a653882016-03-18 18:05:57 +00001467 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001468 // Replace code looking like
1469 // XOR dst, src, 0
1470 // with
1471 // src
1472 instruction->ReplaceWith(input_other);
1473 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001474 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001475 return;
1476 }
1477
1478 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1479 // Replace code looking like
1480 // XOR dst, src, 0xFFF...FF
1481 // with
1482 // NOT dst, src
1483 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1484 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001485 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001486 return;
1487 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001488
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001489 HInstruction* left = instruction->GetLeft();
1490 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001491 if (((left->IsNot() && right->IsNot()) ||
1492 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001493 left->HasOnlyOneNonEnvironmentUse() &&
1494 right->HasOnlyOneNonEnvironmentUse()) {
1495 // Replace code looking like
1496 // NOT nota, a
1497 // NOT notb, b
1498 // XOR dst, nota, notb
1499 // with
1500 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001501 instruction->ReplaceInput(left->InputAt(0), 0);
1502 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001503 left->GetBlock()->RemoveInstruction(left);
1504 right->GetBlock()->RemoveInstruction(right);
1505 RecordSimplification();
1506 return;
1507 }
1508
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001509 TryReplaceWithRotate(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001510}
1511
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001512void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1513 HInstruction* argument = instruction->InputAt(1);
1514 HInstruction* receiver = instruction->InputAt(0);
1515 if (receiver == argument) {
1516 // Because String.equals is an instance call, the receiver is
1517 // a null check if we don't know it's null. The argument however, will
1518 // be the actual object. So we cannot end up in a situation where both
1519 // are equal but could be null.
1520 DCHECK(CanEnsureNotNullAt(argument, instruction));
1521 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1522 instruction->GetBlock()->RemoveInstruction(instruction);
1523 } else {
1524 StringEqualsOptimizations optimizations(instruction);
1525 if (CanEnsureNotNullAt(argument, instruction)) {
1526 optimizations.SetArgumentNotNull();
1527 }
1528 ScopedObjectAccess soa(Thread::Current());
1529 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1530 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1531 optimizations.SetArgumentIsString();
1532 }
1533 }
1534}
1535
Roland Levillain22c49222016-03-18 14:04:28 +00001536void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1537 bool is_left,
1538 Primitive::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001539 DCHECK(invoke->IsInvokeStaticOrDirect());
1540 DCHECK_EQ(invoke->GetOriginalInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001541 HInstruction* value = invoke->InputAt(0);
1542 HInstruction* distance = invoke->InputAt(1);
1543 // Replace the invoke with an HRor.
1544 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001545 // Unconditionally set the type of the negated distance to `int`,
1546 // as shift and rotate operations expect a 32-bit (or narrower)
1547 // value for their distance input.
1548 distance = new (GetGraph()->GetArena()) HNeg(Primitive::kPrimInt, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001549 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1550 }
Roland Levillain22c49222016-03-18 14:04:28 +00001551 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001552 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1553 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001554 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001555 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1556 clinit->GetBlock()->RemoveInstruction(clinit);
1557 HInstruction* ldclass = clinit->InputAt(0);
1558 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1559 ldclass->GetBlock()->RemoveInstruction(ldclass);
1560 }
1561 }
1562}
1563
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001564static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1565 if (potential_length->IsArrayLength()) {
1566 return potential_length->InputAt(0) == potential_array;
1567 }
1568
1569 if (potential_array->IsNewArray()) {
1570 return potential_array->InputAt(0) == potential_length;
1571 }
1572
1573 return false;
1574}
1575
1576void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1577 HInstruction* source = instruction->InputAt(0);
1578 HInstruction* destination = instruction->InputAt(2);
1579 HInstruction* count = instruction->InputAt(4);
1580 SystemArrayCopyOptimizations optimizations(instruction);
1581 if (CanEnsureNotNullAt(source, instruction)) {
1582 optimizations.SetSourceIsNotNull();
1583 }
1584 if (CanEnsureNotNullAt(destination, instruction)) {
1585 optimizations.SetDestinationIsNotNull();
1586 }
1587 if (destination == source) {
1588 optimizations.SetDestinationIsSource();
1589 }
1590
1591 if (IsArrayLengthOf(count, source)) {
1592 optimizations.SetCountIsSourceLength();
1593 }
1594
1595 if (IsArrayLengthOf(count, destination)) {
1596 optimizations.SetCountIsDestinationLength();
1597 }
1598
1599 {
1600 ScopedObjectAccess soa(Thread::Current());
1601 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1602 if (destination_rti.IsValid()) {
1603 if (destination_rti.IsObjectArray()) {
1604 if (destination_rti.IsExact()) {
1605 optimizations.SetDoesNotNeedTypeCheck();
1606 }
1607 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001608 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001609 if (destination_rti.IsPrimitiveArrayClass()) {
1610 optimizations.SetDestinationIsPrimitiveArray();
1611 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1612 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001613 }
1614 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001615 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1616 if (source_rti.IsValid()) {
1617 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1618 optimizations.SetDoesNotNeedTypeCheck();
1619 }
1620 if (source_rti.IsPrimitiveArrayClass()) {
1621 optimizations.SetSourceIsPrimitiveArray();
1622 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1623 optimizations.SetSourceIsNonPrimitiveArray();
1624 }
1625 }
1626 }
1627}
1628
Roland Levillaina5c4a402016-03-15 15:02:50 +00001629void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
1630 bool is_signum,
1631 Primitive::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08001632 DCHECK(invoke->IsInvokeStaticOrDirect());
1633 uint32_t dex_pc = invoke->GetDexPc();
1634 HInstruction* left = invoke->InputAt(0);
1635 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08001636 if (!is_signum) {
1637 right = invoke->InputAt(1);
1638 } else if (type == Primitive::kPrimLong) {
1639 right = GetGraph()->GetLongConstant(0);
1640 } else {
1641 right = GetGraph()->GetIntConstant(0);
1642 }
1643 HCompare* compare = new (GetGraph()->GetArena())
1644 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
1645 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
1646}
1647
Aart Bik75a38b22016-02-17 10:41:50 -08001648void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
1649 DCHECK(invoke->IsInvokeStaticOrDirect());
1650 uint32_t dex_pc = invoke->GetDexPc();
1651 // IsNaN(x) is the same as x != x.
1652 HInstruction* x = invoke->InputAt(0);
1653 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08001654 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08001655 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
1656}
1657
Aart Bik2a6aad92016-02-25 11:32:32 -08001658void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
1659 DCHECK(invoke->IsInvokeStaticOrDirect());
1660 uint32_t dex_pc = invoke->GetDexPc();
1661 HInstruction* x = invoke->InputAt(0);
1662 Primitive::Type type = x->GetType();
1663 // Set proper bit pattern for NaN and replace intrinsic with raw version.
1664 HInstruction* nan;
1665 if (type == Primitive::kPrimDouble) {
1666 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
1667 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
1668 kNeedsEnvironmentOrCache,
1669 kNoSideEffects,
1670 kNoThrow);
1671 } else {
1672 DCHECK_EQ(type, Primitive::kPrimFloat);
1673 nan = GetGraph()->GetIntConstant(0x7fc00000);
1674 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
1675 kNeedsEnvironmentOrCache,
1676 kNoSideEffects,
1677 kNoThrow);
1678 }
1679 // Test IsNaN(x), which is the same as x != x.
1680 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
1681 condition->SetBias(ComparisonBias::kLtBias);
1682 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
1683 // Select between the two.
1684 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
1685 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
1686 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
1687}
1688
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001689void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
1690 HInstruction* str = invoke->InputAt(0);
1691 HInstruction* index = invoke->InputAt(1);
1692 uint32_t dex_pc = invoke->GetDexPc();
1693 ArenaAllocator* arena = GetGraph()->GetArena();
1694 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1695 // so create the HArrayLength, HBoundsCheck and HArrayGet.
1696 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
1697 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1698 HBoundsCheck* bounds_check =
1699 new (arena) HBoundsCheck(index, length, dex_pc, invoke->GetDexMethodIndex());
1700 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
1701 HArrayGet* array_get =
1702 new (arena) HArrayGet(str, index, Primitive::kPrimChar, dex_pc, /* is_string_char_at */ true);
1703 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
1704 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
1705 GetGraph()->SetHasBoundsChecks(true);
1706}
1707
Vladimir Markodce016e2016-04-28 13:10:02 +01001708void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
1709 HInstruction* str = invoke->InputAt(0);
1710 uint32_t dex_pc = invoke->GetDexPc();
1711 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
1712 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001713 HArrayLength* length =
1714 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01001715 HInstruction* replacement;
1716 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
1717 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
1718 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
1719 HIntConstant* zero = GetGraph()->GetIntConstant(0);
1720 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
1721 replacement = equal;
1722 } else {
1723 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
1724 replacement = length;
1725 }
1726 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
1727}
1728
Aart Bik11932592016-03-08 12:42:25 -08001729void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
1730 uint32_t dex_pc = invoke->GetDexPc();
1731 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
1732 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
1733}
1734
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001735void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08001736 switch (instruction->GetIntrinsic()) {
1737 case Intrinsics::kStringEquals:
1738 SimplifyStringEquals(instruction);
1739 break;
1740 case Intrinsics::kSystemArrayCopy:
1741 SimplifySystemArrayCopy(instruction);
1742 break;
1743 case Intrinsics::kIntegerRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001744 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimInt);
1745 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001746 case Intrinsics::kLongRotateRight:
Roland Levillain22c49222016-03-18 14:04:28 +00001747 SimplifyRotate(instruction, /* is_left */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001748 break;
1749 case Intrinsics::kIntegerRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001750 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimInt);
1751 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001752 case Intrinsics::kLongRotateLeft:
Roland Levillain22c49222016-03-18 14:04:28 +00001753 SimplifyRotate(instruction, /* is_left */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001754 break;
1755 case Intrinsics::kIntegerCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001756 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimInt);
1757 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001758 case Intrinsics::kLongCompare:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001759 SimplifyCompare(instruction, /* is_signum */ false, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001760 break;
1761 case Intrinsics::kIntegerSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001762 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimInt);
1763 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001764 case Intrinsics::kLongSignum:
Roland Levillaina5c4a402016-03-15 15:02:50 +00001765 SimplifyCompare(instruction, /* is_signum */ true, Primitive::kPrimLong);
Aart Bik2a6aad92016-02-25 11:32:32 -08001766 break;
1767 case Intrinsics::kFloatIsNaN:
1768 case Intrinsics::kDoubleIsNaN:
1769 SimplifyIsNaN(instruction);
1770 break;
1771 case Intrinsics::kFloatFloatToIntBits:
1772 case Intrinsics::kDoubleDoubleToLongBits:
1773 SimplifyFP2Int(instruction);
1774 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01001775 case Intrinsics::kStringCharAt:
1776 SimplifyStringCharAt(instruction);
1777 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01001778 case Intrinsics::kStringIsEmpty:
1779 case Intrinsics::kStringLength:
1780 SimplifyStringIsEmptyOrLength(instruction);
1781 break;
Aart Bik11932592016-03-08 12:42:25 -08001782 case Intrinsics::kUnsafeLoadFence:
1783 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
1784 break;
1785 case Intrinsics::kUnsafeStoreFence:
1786 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
1787 break;
1788 case Intrinsics::kUnsafeFullFence:
1789 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
1790 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08001791 default:
1792 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001793 }
1794}
1795
Aart Bikbb245d12015-10-19 11:05:03 -07001796void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
1797 HInstruction* cond = deoptimize->InputAt(0);
1798 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001799 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07001800 // Never deopt: instruction can be removed.
1801 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
1802 } else {
1803 // Always deopt.
1804 }
1805 }
1806}
1807
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001808} // namespace art