blob: a85354c182463666e1c6a71a0a633065d30437d4 [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
Andreas Gampec6ea7d02017-02-01 16:46:28 -080019#include "art_method-inl.h"
20#include "class_linker-inl.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010021#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080022#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010023#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070025#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070026#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027
Nicolas Geoffray3c049742014-09-24 18:10:46 +010028namespace art {
29
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010030class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000031 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000032 InstructionSimplifierVisitor(HGraph* graph,
33 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010034 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000035 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010036 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010038 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010039 stats_(stats) {}
40
41 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000042
43 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010044 void RecordSimplification() {
45 simplification_occurred_ = true;
46 simplifications_at_current_position_++;
Igor Murashkin1e065a52017-08-09 13:20:34 -070047 MaybeRecordStat(stats_, kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010048 }
49
Scott Wakeling40a04bf2015-12-11 09:50:36 +000050 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51 bool TryReplaceWithRotate(HBinaryOperation* instruction);
52 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
53 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55
Alexandre Rames188d4312015-04-09 18:30:21 +010056 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000057 // `op` should be either HOr or HAnd.
58 // De Morgan's laws:
59 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
60 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010061 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
62 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020063 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010064
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000065 void VisitShift(HBinaryOperation* shift);
66
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010068 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
69 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010070 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
71 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000072 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000073 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000074 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080075 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000076 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitAdd(HAdd* instruction) OVERRIDE;
78 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040079 void VisitCondition(HCondition* instruction) OVERRIDE;
80 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
81 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
82 void VisitLessThan(HLessThan* condition) OVERRIDE;
83 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060084 void VisitBelow(HBelow* condition) OVERRIDE;
85 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
86 void VisitAbove(HAbove* condition) OVERRIDE;
87 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000088 void VisitDiv(HDiv* instruction) OVERRIDE;
89 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010090 void VisitNeg(HNeg* instruction) OVERRIDE;
91 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitOr(HOr* instruction) OVERRIDE;
93 void VisitShl(HShl* instruction) OVERRIDE;
94 void VisitShr(HShr* instruction) OVERRIDE;
95 void VisitSub(HSub* instruction) OVERRIDE;
96 void VisitUShr(HUShr* instruction) OVERRIDE;
97 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000098 void VisitSelect(HSelect* select) OVERRIDE;
99 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100100 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100101 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700102 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200103 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100104
105 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000106
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100107 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100108 void SimplifySystemArrayCopy(HInvoke* invoke);
109 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800111 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800112 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100113 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100114 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800115 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800116 void SimplifyReturnThis(HInvoke* invoke);
117 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800118 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100119
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000120 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100121 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000122 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 bool simplification_occurred_ = false;
124 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700125 // We ensure we do not loop infinitely. The value should not be too high, since that
126 // would allow looping around the same basic block too many times. The value should
127 // not be too low either, however, since we want to allow revisiting a basic block
128 // with many statements and simplifications at least once.
129 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000130};
131
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100132void InstructionSimplifier::Run() {
Vladimir Marko65979462017-05-19 17:25:12 +0100133 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100134 visitor.Run();
135}
136
137void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100138 // Iterate in reverse post order to open up more simplifications to users
139 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100140 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100141 // The simplification of an instruction to another instruction may yield
142 // possibilities for other simplifications. So although we perform a reverse
143 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100144 do {
145 simplification_occurred_ = false;
146 VisitBasicBlock(block);
147 } while (simplification_occurred_ &&
148 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100149 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100150 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100151}
152
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000153namespace {
154
155bool AreAllBitsSet(HConstant* constant) {
156 return Int64FromConstant(constant) == -1;
157}
158
159} // namespace
160
Alexandre Rames188d4312015-04-09 18:30:21 +0100161// Returns true if the code was simplified to use only one negation operation
162// after the binary operation instead of one on each of the inputs.
163bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
164 DCHECK(binop->IsAdd() || binop->IsSub());
165 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
166 HNeg* left_neg = binop->GetLeft()->AsNeg();
167 HNeg* right_neg = binop->GetRight()->AsNeg();
168 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
169 !right_neg->HasOnlyOneNonEnvironmentUse()) {
170 return false;
171 }
172 // Replace code looking like
173 // NEG tmp1, a
174 // NEG tmp2, b
175 // ADD dst, tmp1, tmp2
176 // with
177 // ADD tmp, a, b
178 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600179 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
180 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
181 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100182 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600183 return false;
184 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100185 binop->ReplaceInput(left_neg->GetInput(), 0);
186 binop->ReplaceInput(right_neg->GetInput(), 1);
187 left_neg->GetBlock()->RemoveInstruction(left_neg);
188 right_neg->GetBlock()->RemoveInstruction(right_neg);
189 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
190 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
191 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
192 RecordSimplification();
193 return true;
194}
195
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000196bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
197 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100198 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000199 HInstruction* left = op->GetLeft();
200 HInstruction* right = op->GetRight();
201
202 // We can apply De Morgan's laws if both inputs are Not's and are only used
203 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000204 if (((left->IsNot() && right->IsNot()) ||
205 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000206 left->HasOnlyOneNonEnvironmentUse() &&
207 right->HasOnlyOneNonEnvironmentUse()) {
208 // Replace code looking like
209 // NOT nota, a
210 // NOT notb, b
211 // AND dst, nota, notb (respectively OR)
212 // with
213 // OR or, a, b (respectively AND)
214 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000215 HInstruction* src_left = left->InputAt(0);
216 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000217 uint32_t dex_pc = op->GetDexPc();
218
219 // Remove the negations on the inputs.
220 left->ReplaceWith(src_left);
221 right->ReplaceWith(src_right);
222 left->GetBlock()->RemoveInstruction(left);
223 right->GetBlock()->RemoveInstruction(right);
224
225 // Replace the `HAnd` or `HOr`.
226 HBinaryOperation* hbin;
227 if (op->IsAnd()) {
228 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
229 } else {
230 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
231 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* hnot;
233 if (left->IsBooleanNot()) {
234 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
235 } else {
236 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
237 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000238
239 op->GetBlock()->InsertInstructionBefore(hbin, op);
240 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
241
242 RecordSimplification();
243 return true;
244 }
245
246 return false;
247}
248
Lena Djokicbc5460b2017-07-20 16:07:36 +0200249bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100250 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200251 InstructionSet isa = codegen_->GetInstructionSet();
252 switch (isa) {
253 case kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100254 if (!(type == DataType::Type::kUint8 ||
255 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100256 type == DataType::Type::kUint16 ||
257 type == DataType::Type::kInt16 ||
258 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200259 return false;
260 }
261 break;
262 case kMips:
263 case kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100264 if (!(type == DataType::Type::kUint8 ||
265 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 type == DataType::Type::kUint16 ||
267 type == DataType::Type::kInt16 ||
268 type == DataType::Type::kInt32 ||
269 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200270 return false;
271 }
272 break;
273 default:
274 return false;
275 }
276
277 ArenaAllocator* arena = mul->GetBlock()->GetGraph()->GetArena();
278
279 if (mul->HasOnlyOneNonEnvironmentUse()) {
280 HInstruction* use = mul->GetUses().front().GetUser();
281 if (use->IsVecAdd() || use->IsVecSub()) {
282 // Replace code looking like
283 // VECMUL tmp, x, y
284 // VECADD/SUB dst, acc, tmp
285 // with
286 // VECMULACC dst, acc, x, y
287 // Note that we do not want to (unconditionally) perform the merge when the
288 // multiplication has multiple uses and it can be merged in all of them.
289 // Multiple uses could happen on the same control-flow path, and we would
290 // then increase the amount of work. In the future we could try to evaluate
291 // whether all uses are on different control-flow paths (using dominance and
292 // reverse-dominance information) and only perform the merge when they are.
293 HInstruction* accumulator = nullptr;
294 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
295 HInstruction* binop_left = binop->GetLeft();
296 HInstruction* binop_right = binop->GetRight();
297 // This is always true since the `HVecMul` has only one use (which is checked above).
298 DCHECK_NE(binop_left, binop_right);
299 if (binop_right == mul) {
300 accumulator = binop_left;
301 } else if (use->IsVecAdd()) {
302 DCHECK_EQ(binop_left, mul);
303 accumulator = binop_right;
304 }
305
306 HInstruction::InstructionKind kind =
307 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
308 if (accumulator != nullptr) {
309 HVecMultiplyAccumulate* mulacc =
310 new (arena) HVecMultiplyAccumulate(arena,
311 kind,
312 accumulator,
313 mul->GetLeft(),
314 mul->GetRight(),
315 binop->GetPackedType(),
316 binop->GetVectorLength());
317
318 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
319 DCHECK(!mul->HasUses());
320 mul->GetBlock()->RemoveInstruction(mul);
321 return true;
322 }
323 }
324 }
325
326 return false;
327}
328
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000329void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
330 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100331 HInstruction* shift_amount = instruction->GetRight();
332 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000333
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100334 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100335 ? kMaxLongShiftDistance
336 : kMaxIntShiftDistance;
337
338 if (shift_amount->IsConstant()) {
339 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700340 int64_t masked_cst = cst & implicit_mask;
341 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400342 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100343 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400344 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100345 // value
346 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400347 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100348 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100349 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700350 } else if (masked_cst != cst) {
351 // Replace code looking like
352 // SHL dst, value, cst
353 // where cst exceeds maximum distance with the equivalent
354 // SHL dst, value, cst & implicit_mask
355 // (as defined by shift semantics). This ensures other
356 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100357 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700358 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
359 RecordSimplification();
360 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100361 }
362 }
363
364 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100365 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
366 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100367 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100368 // AND adjusted_shift, shift, <superset of implicit mask>
369 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
370 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
371 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100372 // with
373 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100374 if (shift_amount->IsAnd() ||
375 shift_amount->IsOr() ||
376 shift_amount->IsXor() ||
377 shift_amount->IsAdd() ||
378 shift_amount->IsSub()) {
379 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
380 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
381 HConstant* mask = bin_op->GetConstantRight();
382 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
383 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100384 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100385 return;
386 }
387 } else if (shift_amount->IsTypeConversion()) {
388 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
389 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
390 // Non-integral and 64-bit source types require an explicit type conversion.
391 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
392 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
393 RecordSimplification();
394 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400395 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000396 }
397}
398
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000399static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
400 return (sub->GetRight() == other &&
401 sub->GetLeft()->IsConstant() &&
402 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
403}
404
405bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
406 HUShr* ushr,
407 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000408 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
409 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000410 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
411 if (!ushr->HasUses()) {
412 ushr->GetBlock()->RemoveInstruction(ushr);
413 }
414 if (!ushr->GetRight()->HasUses()) {
415 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
416 }
417 if (!shl->HasUses()) {
418 shl->GetBlock()->RemoveInstruction(shl);
419 }
420 if (!shl->GetRight()->HasUses()) {
421 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
422 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100423 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000424 return true;
425}
426
427// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
428bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000429 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
430 HInstruction* left = op->GetLeft();
431 HInstruction* right = op->GetRight();
432 // If we have an UShr and a Shl (in either order).
433 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
434 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
435 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100436 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000437 if (ushr->GetType() == shl->GetType() &&
438 ushr->GetLeft() == shl->GetLeft()) {
439 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
440 // Shift distances are both constant, try replacing with Ror if they
441 // add up to the register size.
442 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
443 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
444 // Shift distances are potentially of the form x and (reg_size - x).
445 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
446 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
447 // Shift distances are potentially of the form d and -d.
448 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
449 }
450 }
451 }
452 return false;
453}
454
455// Try replacing code looking like (x >>> #rdist OP x << #ldist):
456// UShr dst, x, #rdist
457// Shl tmp, x, #ldist
458// OP dst, dst, tmp
459// or like (x >>> #rdist OP x << #-ldist):
460// UShr dst, x, #rdist
461// Shl tmp, x, #-ldist
462// OP dst, dst, tmp
463// with
464// Ror dst, x, #rdist
465bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
466 HUShr* ushr,
467 HShl* shl) {
468 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100469 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000470 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
471 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
472 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
473 ReplaceRotateWithRor(op, ushr, shl);
474 return true;
475 }
476 return false;
477}
478
479// Replace code looking like (x >>> -d OP x << d):
480// Neg neg, d
481// UShr dst, x, neg
482// Shl tmp, x, d
483// OP dst, dst, tmp
484// with
485// Neg neg, d
486// Ror dst, x, neg
487// *** OR ***
488// Replace code looking like (x >>> d OP x << -d):
489// UShr dst, x, d
490// Neg neg, d
491// Shl tmp, x, neg
492// OP dst, dst, tmp
493// with
494// Ror dst, x, d
495bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
496 HUShr* ushr,
497 HShl* shl) {
498 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
499 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
500 bool neg_is_left = shl->GetRight()->IsNeg();
501 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
502 // And the shift distance being negated is the distance being shifted the other way.
503 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
504 ReplaceRotateWithRor(op, ushr, shl);
505 }
506 return false;
507}
508
509// Try replacing code looking like (x >>> d OP x << (#bits - d)):
510// UShr dst, x, d
511// Sub ld, #bits, d
512// Shl tmp, x, ld
513// OP dst, dst, tmp
514// with
515// Ror dst, x, d
516// *** OR ***
517// Replace code looking like (x >>> (#bits - d) OP x << d):
518// Sub rd, #bits, d
519// UShr dst, x, rd
520// Shl tmp, x, d
521// OP dst, dst, tmp
522// with
523// Neg neg, d
524// Ror dst, x, neg
525bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
526 HUShr* ushr,
527 HShl* shl) {
528 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
529 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100530 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000531 HInstruction* shl_shift = shl->GetRight();
532 HInstruction* ushr_shift = ushr->GetRight();
533 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
534 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
535 return ReplaceRotateWithRor(op, ushr, shl);
536 }
537 return false;
538}
539
Calin Juravle10e244f2015-01-26 18:54:32 +0000540void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
541 HInstruction* obj = null_check->InputAt(0);
542 if (!obj->CanBeNull()) {
543 null_check->ReplaceWith(obj);
544 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000545 if (stats_ != nullptr) {
546 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
547 }
548 }
549}
550
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100551bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
552 if (!input->CanBeNull()) {
553 return true;
554 }
555
Vladimir Marko46817b82016-03-29 12:21:58 +0100556 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
557 HInstruction* user = use.GetUser();
558 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100559 return true;
560 }
561 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100562
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100563 return false;
564}
565
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100566// Returns whether doing a type test between the class of `object` against `klass` has
567// a statically known outcome. The result of the test is stored in `outcome`.
568static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000569 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
570 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
571 ScopedObjectAccess soa(Thread::Current());
572 if (!obj_rti.IsValid()) {
573 // We run the simplifier before the reference type propagation so type info might not be
574 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100575 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000576 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100577
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100578 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100579 if (!class_rti.IsValid()) {
580 // Happens when the loaded class is unresolved.
581 return false;
582 }
583 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000584 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100585 *outcome = true;
586 return true;
587 } else if (obj_rti.IsExact()) {
588 // The test failed at compile time so will also fail at runtime.
589 *outcome = false;
590 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100591 } else if (!class_rti.IsInterface()
592 && !obj_rti.IsInterface()
593 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100594 // Different type hierarchy. The test will fail.
595 *outcome = false;
596 return true;
597 }
598 return false;
599}
600
601void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
602 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100603 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
604 if (load_class->NeedsAccessCheck()) {
605 // If we need to perform an access check we cannot remove the instruction.
606 return;
607 }
608
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100609 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100610 check_cast->ClearMustDoNullCheck();
611 }
612
613 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000614 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700615 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100616 return;
617 }
618
Vladimir Markoa65ed302016-03-14 21:21:29 +0000619 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
620 // the return value check with the `outcome` check, b/27651442 .
621 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700622 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100623 if (outcome) {
624 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700625 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700626 if (!load_class->HasUses()) {
627 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
628 // However, here we know that it cannot because the checkcast was successfull, hence
629 // the class was already loaded.
630 load_class->GetBlock()->RemoveInstruction(load_class);
631 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100632 } else {
633 // Don't do anything for exceptional cases for now. Ideally we should remove
634 // all instructions and blocks this instruction dominates.
635 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000636 }
637}
638
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100639void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100640 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100641 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
642 if (load_class->NeedsAccessCheck()) {
643 // If we need to perform an access check we cannot remove the instruction.
644 return;
645 }
646
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100647 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100648 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100649 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100650 instruction->ClearMustDoNullCheck();
651 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100652
653 HGraph* graph = GetGraph();
654 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700655 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100656 instruction->ReplaceWith(graph->GetIntConstant(0));
657 instruction->GetBlock()->RemoveInstruction(instruction);
658 RecordSimplification();
659 return;
660 }
661
Vladimir Marko24bd8952016-03-15 10:40:33 +0000662 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
663 // the return value check with the `outcome` check, b/27651442 .
664 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700665 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700666 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100667 if (outcome && can_be_null) {
668 // Type test will succeed, we just need a null test.
669 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
670 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
671 instruction->ReplaceWith(test);
672 } else {
673 // We've statically determined the result of the instanceof.
674 instruction->ReplaceWith(graph->GetIntConstant(outcome));
675 }
676 RecordSimplification();
677 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700678 if (outcome && !load_class->HasUses()) {
679 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
680 // However, here we know that it cannot because the instanceof check was successfull, hence
681 // the class was already loaded.
682 load_class->GetBlock()->RemoveInstruction(load_class);
683 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100684 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100685}
686
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100687void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100688 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100689 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100690 instruction->ClearValueCanBeNull();
691 }
692}
693
694void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100695 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100696 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100697 instruction->ClearValueCanBeNull();
698 }
699}
700
Anton Shaminbdd79352016-02-15 12:48:36 +0600701static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
702 HInstruction *lhs = cond->InputAt(0);
703 HInstruction *rhs = cond->InputAt(1);
704 switch (cond->GetKind()) {
705 case HInstruction::kEqual:
706 return new (arena) HEqual(rhs, lhs);
707 case HInstruction::kNotEqual:
708 return new (arena) HNotEqual(rhs, lhs);
709 case HInstruction::kLessThan:
710 return new (arena) HGreaterThan(rhs, lhs);
711 case HInstruction::kLessThanOrEqual:
712 return new (arena) HGreaterThanOrEqual(rhs, lhs);
713 case HInstruction::kGreaterThan:
714 return new (arena) HLessThan(rhs, lhs);
715 case HInstruction::kGreaterThanOrEqual:
716 return new (arena) HLessThanOrEqual(rhs, lhs);
717 case HInstruction::kBelow:
718 return new (arena) HAbove(rhs, lhs);
719 case HInstruction::kBelowOrEqual:
720 return new (arena) HAboveOrEqual(rhs, lhs);
721 case HInstruction::kAbove:
722 return new (arena) HBelow(rhs, lhs);
723 case HInstruction::kAboveOrEqual:
724 return new (arena) HBelowOrEqual(rhs, lhs);
725 default:
726 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
727 }
728 return nullptr;
729}
730
Aart Bik2767f4b2016-10-28 15:03:53 -0700731static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100732 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700733 return true; // input has direct boolean type
734 } else if (cmp->GetUses().HasExactlyOneElement()) {
735 // Comparison also has boolean type if both its input and the instruction
736 // itself feed into the same phi node.
737 HInstruction* user = cmp->GetUses().front().GetUser();
738 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
739 }
740 return false;
741}
742
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000743void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100744 HInstruction* input_const = equal->GetConstantRight();
745 if (input_const != nullptr) {
746 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700747 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100748 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100749 // We are comparing the boolean to a constant which is of type int and can
750 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000751 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100752 // Replace (bool_value == true) with bool_value
753 equal->ReplaceWith(input_value);
754 block->RemoveInstruction(equal);
755 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000756 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700757 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500758 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
759 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100760 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100761 } else {
762 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
763 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
764 block->RemoveInstruction(equal);
765 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100766 }
Mark Mendellc4701932015-04-10 13:18:51 -0400767 } else {
768 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100769 }
Mark Mendellc4701932015-04-10 13:18:51 -0400770 } else {
771 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100772 }
773}
774
David Brazdil0d13fee2015-04-17 14:52:19 +0100775void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
776 HInstruction* input_const = not_equal->GetConstantRight();
777 if (input_const != nullptr) {
778 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700779 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100780 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100781 // We are comparing the boolean to a constant which is of type int and can
782 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000783 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700784 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500785 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
786 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100787 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000788 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100790 not_equal->ReplaceWith(input_value);
791 block->RemoveInstruction(not_equal);
792 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100793 } else {
794 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
795 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
796 block->RemoveInstruction(not_equal);
797 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100798 }
Mark Mendellc4701932015-04-10 13:18:51 -0400799 } else {
800 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100801 }
Mark Mendellc4701932015-04-10 13:18:51 -0400802 } else {
803 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100804 }
805}
806
807void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000808 HInstruction* input = bool_not->InputAt(0);
809 HInstruction* replace_with = nullptr;
810
811 if (input->IsIntConstant()) {
812 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000813 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000814 replace_with = GetGraph()->GetIntConstant(0);
815 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000816 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000817 replace_with = GetGraph()->GetIntConstant(1);
818 }
819 } else if (input->IsBooleanNot()) {
820 // Replace (!(!bool_value)) with bool_value.
821 replace_with = input->InputAt(0);
822 } else if (input->IsCondition() &&
823 // Don't change FP compares. The definition of compares involving
824 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100825 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000826 // Replace condition with its opposite.
827 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
828 }
829
830 if (replace_with != nullptr) {
831 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100832 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000833 RecordSimplification();
834 }
835}
836
Aart Bik4f7dd342017-09-12 13:12:57 -0700837// Constructs a new ABS(x) node in the HIR.
838static HInstruction* NewIntegralAbs(ArenaAllocator* arena, HInstruction* x, HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100839 DataType::Type type = x->GetType();
840 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700841 // Construct a fake intrinsic with as much context as is needed to allocate one.
842 // The intrinsic will always be lowered into code later anyway.
843 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
844 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
845 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
846 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
847 0u
848 };
849 HInvokeStaticOrDirect* invoke = new (arena) HInvokeStaticOrDirect(
850 arena,
851 1,
852 type,
853 x->GetDexPc(),
854 /*method_idx*/ -1,
855 /*resolved_method*/ nullptr,
856 dispatch_info,
857 kStatic,
858 MethodReference(nullptr, dex::kDexNoIndex),
859 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
860 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100861 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
862 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700863 kNoEnvironmentOrCache,
864 kNoSideEffects,
865 kNoThrow);
866 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
867 return invoke;
868}
869
870// Returns true if operands a and b consists of widening type conversions
871// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100872static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700873 if (a->IsTypeConversion() && a->GetType() == to_type) {
874 a = a->InputAt(0);
875 }
876 if (b->IsTypeConversion() && b->GetType() == to_type) {
877 b = b->InputAt(0);
878 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100879 DataType::Type type1 = a->GetType();
880 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100881 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
882 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
883 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
884 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
885 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100886 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700887}
888
David Brazdil74eb1b22015-12-14 11:44:01 +0000889void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
890 HInstruction* replace_with = nullptr;
891 HInstruction* condition = select->GetCondition();
892 HInstruction* true_value = select->GetTrueValue();
893 HInstruction* false_value = select->GetFalseValue();
894
895 if (condition->IsBooleanNot()) {
896 // Change ((!cond) ? x : y) to (cond ? y : x).
897 condition = condition->InputAt(0);
898 std::swap(true_value, false_value);
899 select->ReplaceInput(false_value, 0);
900 select->ReplaceInput(true_value, 1);
901 select->ReplaceInput(condition, 2);
902 RecordSimplification();
903 }
904
905 if (true_value == false_value) {
906 // Replace (cond ? x : x) with (x).
907 replace_with = true_value;
908 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000909 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000910 // Replace (true ? x : y) with (x).
911 replace_with = true_value;
912 } else {
913 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000914 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000915 replace_with = false_value;
916 }
917 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000918 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000919 // Replace (cond ? true : false) with (cond).
920 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000921 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000922 // Replace (cond ? false : true) with (!cond).
923 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
924 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700925 } else if (condition->IsCondition()) {
926 IfCondition cmp = condition->AsCondition()->GetCondition();
927 HInstruction* a = condition->InputAt(0);
928 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100929 DataType::Type t_type = true_value->GetType();
930 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700931 // Here we have a <cmp> b ? true_value : false_value.
932 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100933 if (t_type == f_type &&
934 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700935 // Try to replace typical integral ABS constructs.
936 if (true_value->IsNeg()) {
937 HInstruction* negated = true_value->InputAt(0);
938 if ((cmp == kCondLT || cmp == kCondLE) &&
939 (a == negated && a == false_value && IsInt64Value(b, 0))) {
940 // Found a < 0 ? -a : a which can be replaced by ABS(a).
941 replace_with = NewIntegralAbs(GetGraph()->GetArena(), false_value, select);
942 }
943 } else if (false_value->IsNeg()) {
944 HInstruction* negated = false_value->InputAt(0);
945 if ((cmp == kCondGT || cmp == kCondGE) &&
946 (a == true_value && a == negated && IsInt64Value(b, 0))) {
947 // Found a > 0 ? a : -a which can be replaced by ABS(a).
948 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
949 }
950 } else if (true_value->IsSub() && false_value->IsSub()) {
951 HInstruction* true_sub1 = true_value->InputAt(0);
952 HInstruction* true_sub2 = true_value->InputAt(1);
953 HInstruction* false_sub1 = false_value->InputAt(0);
954 HInstruction* false_sub2 = false_value->InputAt(1);
955 if ((((cmp == kCondGT || cmp == kCondGE) &&
956 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
957 ((cmp == kCondLT || cmp == kCondLE) &&
958 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
959 AreLowerPrecisionArgs(t_type, a, b)) {
960 // Found a > b ? a - b : b - a or
961 // a < b ? b - a : a - b
962 // which can be replaced by ABS(a - b) for lower precision operands a, b.
963 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
964 }
965 }
966 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000967 }
968
969 if (replace_with != nullptr) {
970 select->ReplaceWith(replace_with);
971 select->GetBlock()->RemoveInstruction(select);
972 RecordSimplification();
973 }
974}
975
976void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
977 HInstruction* condition = instruction->InputAt(0);
978 if (condition->IsBooleanNot()) {
979 // Swap successors if input is negated.
980 instruction->ReplaceInput(condition->InputAt(0), 0);
981 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100982 RecordSimplification();
983 }
984}
985
Mingyao Yang0304e182015-01-30 16:41:29 -0800986void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
987 HInstruction* input = instruction->InputAt(0);
988 // If the array is a NewArray with constant size, replace the array length
989 // with the constant instruction. This helps the bounds check elimination phase.
990 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000991 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800992 if (input->IsIntConstant()) {
993 instruction->ReplaceWith(input);
994 }
995 }
996}
997
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000998void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000999 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001000 if (value->GetType() != DataType::Type::kReference) {
1001 return;
1002 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001003
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001004 if (CanEnsureNotNullAt(value, instruction)) {
1005 instruction->ClearValueCanBeNull();
1006 }
1007
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001008 if (value->IsArrayGet()) {
1009 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1010 // If the code is just swapping elements in the array, no need for a type check.
1011 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001012 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001013 }
1014 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001015
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001016 if (value->IsNullConstant()) {
1017 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001018 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001019 }
1020
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001021 ScopedObjectAccess soa(Thread::Current());
1022 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1023 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1024 if (!array_rti.IsValid()) {
1025 return;
1026 }
1027
1028 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1029 instruction->ClearNeedsTypeCheck();
1030 return;
1031 }
1032
1033 if (array_rti.IsObjectArray()) {
1034 if (array_rti.IsExact()) {
1035 instruction->ClearNeedsTypeCheck();
1036 return;
1037 }
1038 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001039 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001040}
1041
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001042static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001043 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001044 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001045 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1046 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001047 // Note: The size check excludes Uint8 as the result type.
1048 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001049 return DataType::Size(result_type) > DataType::Size(input_type) &&
1050 result_type != DataType::Type::kUint16 &&
1051 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001052}
1053
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001054void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001055 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001056 DataType::Type input_type = input->GetType();
1057 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001058 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001059 // Remove the implicit conversion; this includes conversion to the same type.
1060 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001061 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001062 RecordSimplification();
1063 return;
1064 }
1065
1066 if (input->IsTypeConversion()) {
1067 HTypeConversion* input_conversion = input->AsTypeConversion();
1068 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001069 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001070
1071 // When the first conversion is lossless, a direct conversion from the original type
1072 // to the final type yields the same result, even for a lossy second conversion, for
1073 // example float->double->int or int->double->float.
1074 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1075
1076 // For integral conversions, see if the first conversion loses only bits that the second
1077 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1078 // conversion yields the same result, for example long->int->short or int->char->short.
1079 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001080 DataType::IsIntegralType(input_type) &&
1081 DataType::IsIntegralType(original_type) &&
1082 DataType::IsIntegralType(result_type) &&
1083 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001084
1085 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1086 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001087 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001088 instruction->ReplaceWith(original_input);
1089 instruction->GetBlock()->RemoveInstruction(instruction);
1090 if (!input_conversion->HasUses()) {
1091 // Don't wait for DCE.
1092 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1093 }
1094 RecordSimplification();
1095 return;
1096 }
1097 // Otherwise simplify only if the first conversion has no other use.
1098 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1099 input_conversion->ReplaceWith(original_input);
1100 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1101 RecordSimplification();
1102 return;
1103 }
1104 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001105 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1106 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001107 HAnd* input_and = input->AsAnd();
1108 HConstant* constant = input_and->GetConstantRight();
1109 if (constant != nullptr) {
1110 int64_t value = Int64FromConstant(constant);
1111 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1112 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001113 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001114 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001115 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001116 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001117 instruction->ReplaceWith(original_input);
1118 instruction->GetBlock()->RemoveInstruction(instruction);
1119 RecordSimplification();
1120 return;
1121 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1122 input_and->ReplaceWith(original_input);
1123 input_and->GetBlock()->RemoveInstruction(input_and);
1124 RecordSimplification();
1125 return;
1126 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001127 }
1128 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001129 }
1130}
1131
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001132void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1133 HConstant* input_cst = instruction->GetConstantRight();
1134 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001135 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001136 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001137 // Replace code looking like
1138 // ADD dst, src, 0
1139 // with
1140 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001141 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1142 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1143 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001144 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001145 instruction->ReplaceWith(input_other);
1146 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001147 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001148 return;
1149 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001150 }
1151
1152 HInstruction* left = instruction->GetLeft();
1153 HInstruction* right = instruction->GetRight();
1154 bool left_is_neg = left->IsNeg();
1155 bool right_is_neg = right->IsNeg();
1156
1157 if (left_is_neg && right_is_neg) {
1158 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1159 return;
1160 }
1161 }
1162
1163 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1164 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1165 // Replace code looking like
1166 // NEG tmp, b
1167 // ADD dst, a, tmp
1168 // with
1169 // SUB dst, a, b
1170 // We do not perform the optimization if the input negation has environment
1171 // uses or multiple non-environment uses as it could lead to worse code. In
1172 // particular, we do not want the live range of `b` to be extended if we are
1173 // not sure the initial 'NEG' instruction can be removed.
1174 HInstruction* other = left_is_neg ? right : left;
1175 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
1176 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1177 RecordSimplification();
1178 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001179 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001180 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001181
Anton Kirilove14dc862016-05-13 17:56:15 +01001182 if (TryReplaceWithRotate(instruction)) {
1183 return;
1184 }
1185
1186 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1187 // so no need to return.
1188 TryHandleAssociativeAndCommutativeOperation(instruction);
1189
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001190 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001191 TrySubtractionChainSimplification(instruction)) {
1192 return;
1193 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001194
1195 if (integral_type) {
1196 // Replace code patterns looking like
1197 // SUB dst1, x, y SUB dst1, x, y
1198 // ADD dst2, dst1, y ADD dst2, y, dst1
1199 // with
1200 // SUB dst1, x, y
1201 // ADD instruction is not needed in this case, we may use
1202 // one of inputs of SUB instead.
1203 if (left->IsSub() && left->InputAt(1) == right) {
1204 instruction->ReplaceWith(left->InputAt(0));
1205 RecordSimplification();
1206 instruction->GetBlock()->RemoveInstruction(instruction);
1207 return;
1208 } else if (right->IsSub() && right->InputAt(1) == left) {
1209 instruction->ReplaceWith(right->InputAt(0));
1210 RecordSimplification();
1211 instruction->GetBlock()->RemoveInstruction(instruction);
1212 return;
1213 }
1214 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001215}
1216
1217void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1218 HConstant* input_cst = instruction->GetConstantRight();
1219 HInstruction* input_other = instruction->GetLeastConstantLeft();
1220
Vladimir Marko452c1b62015-09-25 14:44:17 +01001221 if (input_cst != nullptr) {
1222 int64_t value = Int64FromConstant(input_cst);
1223 if (value == -1) {
1224 // Replace code looking like
1225 // AND dst, src, 0xFFF...FF
1226 // with
1227 // src
1228 instruction->ReplaceWith(input_other);
1229 instruction->GetBlock()->RemoveInstruction(instruction);
1230 RecordSimplification();
1231 return;
1232 }
1233 // Eliminate And from UShr+And if the And-mask contains all the bits that
1234 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1235 // precisely clears the shifted-in sign bits.
1236 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001237 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001238 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1239 size_t num_tail_bits_set = CTZ(value + 1);
1240 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1241 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1242 instruction->ReplaceWith(input_other);
1243 instruction->GetBlock()->RemoveInstruction(instruction);
1244 RecordSimplification();
1245 return;
1246 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1247 input_other->HasOnlyOneNonEnvironmentUse()) {
1248 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1249 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1250 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1251 input_other->InputAt(0),
1252 input_other->InputAt(1),
1253 input_other->GetDexPc());
1254 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1255 input_other->GetBlock()->RemoveInstruction(input_other);
1256 RecordSimplification();
1257 return;
1258 }
1259 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001260 }
1261
1262 // We assume that GVN has run before, so we only perform a pointer comparison.
1263 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001264 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001265 if (instruction->GetLeft() == instruction->GetRight()) {
1266 // Replace code looking like
1267 // AND dst, src, src
1268 // with
1269 // src
1270 instruction->ReplaceWith(instruction->GetLeft());
1271 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001272 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001273 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001274 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001275
Anton Kirilove14dc862016-05-13 17:56:15 +01001276 if (TryDeMorganNegationFactoring(instruction)) {
1277 return;
1278 }
1279
1280 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1281 // so no need to return.
1282 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001283}
1284
Mark Mendellc4701932015-04-10 13:18:51 -04001285void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1286 VisitCondition(condition);
1287}
1288
1289void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1290 VisitCondition(condition);
1291}
1292
1293void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1294 VisitCondition(condition);
1295}
1296
1297void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1298 VisitCondition(condition);
1299}
1300
Anton Shaminbdd79352016-02-15 12:48:36 +06001301void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1302 VisitCondition(condition);
1303}
1304
1305void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1306 VisitCondition(condition);
1307}
1308
1309void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1310 VisitCondition(condition);
1311}
1312
1313void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1314 VisitCondition(condition);
1315}
Aart Bike9f37602015-10-09 11:15:55 -07001316
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001317// Recognize the following pattern:
1318// obj.getClass() ==/!= Foo.class
1319// And replace it with a constant value if the type of `obj` is statically known.
1320static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1321 HInstruction* input_one = condition->InputAt(0);
1322 HInstruction* input_two = condition->InputAt(1);
1323 HLoadClass* load_class = input_one->IsLoadClass()
1324 ? input_one->AsLoadClass()
1325 : input_two->AsLoadClass();
1326 if (load_class == nullptr) {
1327 return false;
1328 }
1329
1330 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1331 if (!class_rti.IsValid()) {
1332 // Unresolved class.
1333 return false;
1334 }
1335
1336 HInstanceFieldGet* field_get = (load_class == input_one)
1337 ? input_two->AsInstanceFieldGet()
1338 : input_one->AsInstanceFieldGet();
1339 if (field_get == nullptr) {
1340 return false;
1341 }
1342
1343 HInstruction* receiver = field_get->InputAt(0);
1344 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1345 if (!receiver_type.IsExact()) {
1346 return false;
1347 }
1348
1349 {
1350 ScopedObjectAccess soa(Thread::Current());
1351 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1352 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1353 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1354 if (field_get->GetFieldInfo().GetField() != field) {
1355 return false;
1356 }
1357
1358 // We can replace the compare.
1359 int value = 0;
1360 if (receiver_type.IsEqual(class_rti)) {
1361 value = condition->IsEqual() ? 1 : 0;
1362 } else {
1363 value = condition->IsNotEqual() ? 1 : 0;
1364 }
1365 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1366 return true;
1367 }
1368}
1369
Mark Mendellc4701932015-04-10 13:18:51 -04001370void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001371 if (condition->IsEqual() || condition->IsNotEqual()) {
1372 if (RecognizeAndSimplifyClassCheck(condition)) {
1373 return;
1374 }
1375 }
1376
Anton Shaminbdd79352016-02-15 12:48:36 +06001377 // Reverse condition if left is constant. Our code generators prefer constant
1378 // on the right hand side.
1379 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1380 HBasicBlock* block = condition->GetBlock();
1381 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1382 // If it is a fp we must set the opposite bias.
1383 if (replacement != nullptr) {
1384 if (condition->IsLtBias()) {
1385 replacement->SetBias(ComparisonBias::kGtBias);
1386 } else if (condition->IsGtBias()) {
1387 replacement->SetBias(ComparisonBias::kLtBias);
1388 }
1389 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1390 RecordSimplification();
1391
1392 condition = replacement;
1393 }
1394 }
Mark Mendellc4701932015-04-10 13:18:51 -04001395
Mark Mendellc4701932015-04-10 13:18:51 -04001396 HInstruction* left = condition->GetLeft();
1397 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001398
1399 // Try to fold an HCompare into this HCondition.
1400
Mark Mendellc4701932015-04-10 13:18:51 -04001401 // We can only replace an HCondition which compares a Compare to 0.
1402 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1403 // condition with a long, float or double comparison as input.
1404 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1405 // Conversion is not possible.
1406 return;
1407 }
1408
1409 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001410 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001411 // Someone else also wants the result of the compare.
1412 return;
1413 }
1414
Vladimir Marko46817b82016-03-29 12:21:58 +01001415 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001416 // There is a reference to the compare result in an environment. Do we really need it?
1417 if (GetGraph()->IsDebuggable()) {
1418 return;
1419 }
1420
1421 // We have to ensure that there are no deopt points in the sequence.
1422 if (left->HasAnyEnvironmentUseBefore(condition)) {
1423 return;
1424 }
1425 }
1426
1427 // Clean up any environment uses from the HCompare, if any.
1428 left->RemoveEnvironmentUsers();
1429
1430 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1431 condition->SetBias(left->AsCompare()->GetBias());
1432
1433 // Replace the operands of the HCondition.
1434 condition->ReplaceInput(left->InputAt(0), 0);
1435 condition->ReplaceInput(left->InputAt(1), 1);
1436
1437 // Remove the HCompare.
1438 left->GetBlock()->RemoveInstruction(left);
1439
1440 RecordSimplification();
1441}
1442
Andreas Gampe9186ced2016-12-12 14:28:21 -08001443// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1444static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1445 // True, if the most significant bits of divisor are 0.
1446 return ((divisor & 0x7fffff) == 0);
1447}
1448
1449// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1450static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1451 // True, if the most significant bits of divisor are 0.
1452 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1453}
1454
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001455void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1456 HConstant* input_cst = instruction->GetConstantRight();
1457 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001458 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001459
1460 if ((input_cst != nullptr) && input_cst->IsOne()) {
1461 // Replace code looking like
1462 // DIV dst, src, 1
1463 // with
1464 // src
1465 instruction->ReplaceWith(input_other);
1466 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001467 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001468 return;
1469 }
1470
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001471 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001472 // Replace code looking like
1473 // DIV dst, src, -1
1474 // with
1475 // NEG dst, src
1476 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001477 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001478 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001479 return;
1480 }
1481
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001482 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001483 // Try replacing code looking like
1484 // DIV dst, src, constant
1485 // with
1486 // MUL dst, src, 1 / constant
1487 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001489 double value = input_cst->AsDoubleConstant()->GetValue();
1490 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1491 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1492 }
1493 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001494 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001495 float value = input_cst->AsFloatConstant()->GetValue();
1496 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1497 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1498 }
1499 }
1500
1501 if (reciprocal != nullptr) {
1502 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1503 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1504 RecordSimplification();
1505 return;
1506 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001507 }
1508}
1509
1510void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1511 HConstant* input_cst = instruction->GetConstantRight();
1512 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001513 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001514 HBasicBlock* block = instruction->GetBlock();
1515 ArenaAllocator* allocator = GetGraph()->GetArena();
1516
1517 if (input_cst == nullptr) {
1518 return;
1519 }
1520
1521 if (input_cst->IsOne()) {
1522 // Replace code looking like
1523 // MUL dst, src, 1
1524 // with
1525 // src
1526 instruction->ReplaceWith(input_other);
1527 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001528 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001529 return;
1530 }
1531
1532 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001533 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001534 // Replace code looking like
1535 // MUL dst, src, -1
1536 // with
1537 // NEG dst, src
1538 HNeg* neg = new (allocator) HNeg(type, input_other);
1539 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001540 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001541 return;
1542 }
1543
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001545 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1546 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1547 // Replace code looking like
1548 // FP_MUL dst, src, 2.0
1549 // with
1550 // FP_ADD dst, src, src
1551 // The 'int' and 'long' cases are handled below.
1552 block->ReplaceAndRemoveInstructionWith(instruction,
1553 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001554 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001555 return;
1556 }
1557
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001558 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001559 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001560 // Even though constant propagation also takes care of the zero case, other
1561 // optimizations can lead to having a zero multiplication.
1562 if (factor == 0) {
1563 // Replace code looking like
1564 // MUL dst, src, 0
1565 // with
1566 // 0
1567 instruction->ReplaceWith(input_cst);
1568 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001569 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001570 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001571 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001572 // Replace code looking like
1573 // MUL dst, src, pow_of_2
1574 // with
1575 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001576 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001577 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001578 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001579 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001580 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001581 } else if (IsPowerOfTwo(factor - 1)) {
1582 // Transform code looking like
1583 // MUL dst, src, (2^n + 1)
1584 // into
1585 // SHL tmp, src, n
1586 // ADD dst, src, tmp
1587 HShl* shl = new (allocator) HShl(type,
1588 input_other,
1589 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1590 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1591
1592 block->InsertInstructionBefore(shl, instruction);
1593 block->ReplaceAndRemoveInstructionWith(instruction, add);
1594 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001595 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001596 } else if (IsPowerOfTwo(factor + 1)) {
1597 // Transform code looking like
1598 // MUL dst, src, (2^n - 1)
1599 // into
1600 // SHL tmp, src, n
1601 // SUB dst, tmp, src
1602 HShl* shl = new (allocator) HShl(type,
1603 input_other,
1604 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1605 HSub* sub = new (allocator) HSub(type, shl, input_other);
1606
1607 block->InsertInstructionBefore(shl, instruction);
1608 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1609 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001610 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001611 }
1612 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001613
1614 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1615 // so no need to return.
1616 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001617}
1618
Alexandre Rames188d4312015-04-09 18:30:21 +01001619void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1620 HInstruction* input = instruction->GetInput();
1621 if (input->IsNeg()) {
1622 // Replace code looking like
1623 // NEG tmp, src
1624 // NEG dst, tmp
1625 // with
1626 // src
1627 HNeg* previous_neg = input->AsNeg();
1628 instruction->ReplaceWith(previous_neg->GetInput());
1629 instruction->GetBlock()->RemoveInstruction(instruction);
1630 // We perform the optimization even if the input negation has environment
1631 // uses since it allows removing the current instruction. But we only delete
1632 // the input negation only if it is does not have any uses left.
1633 if (!previous_neg->HasUses()) {
1634 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1635 }
1636 RecordSimplification();
1637 return;
1638 }
1639
Serguei Katkov339dfc22015-04-20 12:29:32 +06001640 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001641 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001642 // Replace code looking like
1643 // SUB tmp, a, b
1644 // NEG dst, tmp
1645 // with
1646 // SUB dst, b, a
1647 // We do not perform the optimization if the input subtraction has
1648 // environment uses or multiple non-environment uses as it could lead to
1649 // worse code. In particular, we do not want the live ranges of `a` and `b`
1650 // to be extended if we are not sure the initial 'SUB' instruction can be
1651 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001652 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001653 HSub* sub = input->AsSub();
1654 HSub* new_sub =
1655 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1656 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1657 if (!sub->HasUses()) {
1658 sub->GetBlock()->RemoveInstruction(sub);
1659 }
1660 RecordSimplification();
1661 }
1662}
1663
1664void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1665 HInstruction* input = instruction->GetInput();
1666 if (input->IsNot()) {
1667 // Replace code looking like
1668 // NOT tmp, src
1669 // NOT dst, tmp
1670 // with
1671 // src
1672 // We perform the optimization even if the input negation has environment
1673 // uses since it allows removing the current instruction. But we only delete
1674 // the input negation only if it is does not have any uses left.
1675 HNot* previous_not = input->AsNot();
1676 instruction->ReplaceWith(previous_not->GetInput());
1677 instruction->GetBlock()->RemoveInstruction(instruction);
1678 if (!previous_not->HasUses()) {
1679 previous_not->GetBlock()->RemoveInstruction(previous_not);
1680 }
1681 RecordSimplification();
1682 }
1683}
1684
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001685void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1686 HConstant* input_cst = instruction->GetConstantRight();
1687 HInstruction* input_other = instruction->GetLeastConstantLeft();
1688
Roland Levillain1a653882016-03-18 18:05:57 +00001689 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001690 // Replace code looking like
1691 // OR dst, src, 0
1692 // with
1693 // src
1694 instruction->ReplaceWith(input_other);
1695 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001696 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001697 return;
1698 }
1699
1700 // We assume that GVN has run before, so we only perform a pointer comparison.
1701 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001702 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001703 if (instruction->GetLeft() == instruction->GetRight()) {
1704 // Replace code looking like
1705 // OR dst, src, src
1706 // with
1707 // src
1708 instruction->ReplaceWith(instruction->GetLeft());
1709 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001710 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001711 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001712 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001713
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001714 if (TryDeMorganNegationFactoring(instruction)) return;
1715
Anton Kirilove14dc862016-05-13 17:56:15 +01001716 if (TryReplaceWithRotate(instruction)) {
1717 return;
1718 }
1719
1720 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1721 // so no need to return.
1722 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001723}
1724
1725void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1726 VisitShift(instruction);
1727}
1728
1729void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1730 VisitShift(instruction);
1731}
1732
1733void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1734 HConstant* input_cst = instruction->GetConstantRight();
1735 HInstruction* input_other = instruction->GetLeastConstantLeft();
1736
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001737 DataType::Type type = instruction->GetType();
1738 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001739 return;
1740 }
1741
Roland Levillain1a653882016-03-18 18:05:57 +00001742 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001743 // Replace code looking like
1744 // SUB dst, src, 0
1745 // with
1746 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001747 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1748 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1749 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001750 instruction->ReplaceWith(input_other);
1751 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001752 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001753 return;
1754 }
1755
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001756 HBasicBlock* block = instruction->GetBlock();
1757 ArenaAllocator* allocator = GetGraph()->GetArena();
1758
Alexandre Rames188d4312015-04-09 18:30:21 +01001759 HInstruction* left = instruction->GetLeft();
1760 HInstruction* right = instruction->GetRight();
1761 if (left->IsConstant()) {
1762 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001763 // Replace code looking like
1764 // SUB dst, 0, src
1765 // with
1766 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001767 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001768 // `x` is `0.0`, the former expression yields `0.0`, while the later
1769 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001770 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001771 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001772 RecordSimplification();
1773 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001774 }
1775 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001776
1777 if (left->IsNeg() && right->IsNeg()) {
1778 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1779 return;
1780 }
1781 }
1782
1783 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1784 // Replace code looking like
1785 // NEG tmp, b
1786 // SUB dst, a, tmp
1787 // with
1788 // ADD dst, a, b
1789 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1790 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1791 RecordSimplification();
1792 right->GetBlock()->RemoveInstruction(right);
1793 return;
1794 }
1795
1796 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1797 // Replace code looking like
1798 // NEG tmp, a
1799 // SUB dst, tmp, b
1800 // with
1801 // ADD tmp, a, b
1802 // NEG dst, tmp
1803 // The second version is not intrinsically better, but enables more
1804 // transformations.
1805 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1806 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1807 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1808 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1809 instruction->ReplaceWith(neg);
1810 instruction->GetBlock()->RemoveInstruction(instruction);
1811 RecordSimplification();
1812 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001813 return;
1814 }
1815
1816 if (TrySubtractionChainSimplification(instruction)) {
1817 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001818 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001819
1820 if (left->IsAdd()) {
1821 // Replace code patterns looking like
1822 // ADD dst1, x, y ADD dst1, x, y
1823 // SUB dst2, dst1, y SUB dst2, dst1, x
1824 // with
1825 // ADD dst1, x, y
1826 // SUB instruction is not needed in this case, we may use
1827 // one of inputs of ADD instead.
1828 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001829 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001830 if (left->InputAt(1) == right) {
1831 instruction->ReplaceWith(left->InputAt(0));
1832 RecordSimplification();
1833 instruction->GetBlock()->RemoveInstruction(instruction);
1834 return;
1835 } else if (left->InputAt(0) == right) {
1836 instruction->ReplaceWith(left->InputAt(1));
1837 RecordSimplification();
1838 instruction->GetBlock()->RemoveInstruction(instruction);
1839 return;
1840 }
1841 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001842}
1843
1844void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1845 VisitShift(instruction);
1846}
1847
1848void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1849 HConstant* input_cst = instruction->GetConstantRight();
1850 HInstruction* input_other = instruction->GetLeastConstantLeft();
1851
Roland Levillain1a653882016-03-18 18:05:57 +00001852 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001853 // Replace code looking like
1854 // XOR dst, src, 0
1855 // with
1856 // src
1857 instruction->ReplaceWith(input_other);
1858 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001859 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001860 return;
1861 }
1862
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001863 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001864 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001865 // Replace code looking like
1866 // XOR dst, src, 1
1867 // with
1868 // BOOLEAN_NOT dst, src
1869 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1870 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1871 RecordSimplification();
1872 return;
1873 }
1874
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001875 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1876 // Replace code looking like
1877 // XOR dst, src, 0xFFF...FF
1878 // with
1879 // NOT dst, src
1880 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1881 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001882 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001883 return;
1884 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001885
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001886 HInstruction* left = instruction->GetLeft();
1887 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001888 if (((left->IsNot() && right->IsNot()) ||
1889 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001890 left->HasOnlyOneNonEnvironmentUse() &&
1891 right->HasOnlyOneNonEnvironmentUse()) {
1892 // Replace code looking like
1893 // NOT nota, a
1894 // NOT notb, b
1895 // XOR dst, nota, notb
1896 // with
1897 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001898 instruction->ReplaceInput(left->InputAt(0), 0);
1899 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001900 left->GetBlock()->RemoveInstruction(left);
1901 right->GetBlock()->RemoveInstruction(right);
1902 RecordSimplification();
1903 return;
1904 }
1905
Anton Kirilove14dc862016-05-13 17:56:15 +01001906 if (TryReplaceWithRotate(instruction)) {
1907 return;
1908 }
1909
1910 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1911 // so no need to return.
1912 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001913}
1914
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001915void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1916 HInstruction* argument = instruction->InputAt(1);
1917 HInstruction* receiver = instruction->InputAt(0);
1918 if (receiver == argument) {
1919 // Because String.equals is an instance call, the receiver is
1920 // a null check if we don't know it's null. The argument however, will
1921 // be the actual object. So we cannot end up in a situation where both
1922 // are equal but could be null.
1923 DCHECK(CanEnsureNotNullAt(argument, instruction));
1924 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1925 instruction->GetBlock()->RemoveInstruction(instruction);
1926 } else {
1927 StringEqualsOptimizations optimizations(instruction);
1928 if (CanEnsureNotNullAt(argument, instruction)) {
1929 optimizations.SetArgumentNotNull();
1930 }
1931 ScopedObjectAccess soa(Thread::Current());
1932 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1933 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1934 optimizations.SetArgumentIsString();
1935 }
1936 }
1937}
1938
Roland Levillain22c49222016-03-18 14:04:28 +00001939void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1940 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001941 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001942 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001943 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001944 HInstruction* value = invoke->InputAt(0);
1945 HInstruction* distance = invoke->InputAt(1);
1946 // Replace the invoke with an HRor.
1947 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001948 // Unconditionally set the type of the negated distance to `int`,
1949 // as shift and rotate operations expect a 32-bit (or narrower)
1950 // value for their distance input.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001951 distance = new (GetGraph()->GetArena()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001952 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1953 }
Roland Levillain22c49222016-03-18 14:04:28 +00001954 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001955 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1956 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001957 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001958 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1959 clinit->GetBlock()->RemoveInstruction(clinit);
1960 HInstruction* ldclass = clinit->InputAt(0);
1961 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1962 ldclass->GetBlock()->RemoveInstruction(ldclass);
1963 }
1964 }
1965}
1966
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001967static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1968 if (potential_length->IsArrayLength()) {
1969 return potential_length->InputAt(0) == potential_array;
1970 }
1971
1972 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001973 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001974 }
1975
1976 return false;
1977}
1978
1979void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1980 HInstruction* source = instruction->InputAt(0);
1981 HInstruction* destination = instruction->InputAt(2);
1982 HInstruction* count = instruction->InputAt(4);
1983 SystemArrayCopyOptimizations optimizations(instruction);
1984 if (CanEnsureNotNullAt(source, instruction)) {
1985 optimizations.SetSourceIsNotNull();
1986 }
1987 if (CanEnsureNotNullAt(destination, instruction)) {
1988 optimizations.SetDestinationIsNotNull();
1989 }
1990 if (destination == source) {
1991 optimizations.SetDestinationIsSource();
1992 }
1993
1994 if (IsArrayLengthOf(count, source)) {
1995 optimizations.SetCountIsSourceLength();
1996 }
1997
1998 if (IsArrayLengthOf(count, destination)) {
1999 optimizations.SetCountIsDestinationLength();
2000 }
2001
2002 {
2003 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002004 DataType::Type source_component_type = DataType::Type::kVoid;
2005 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002006 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2007 if (destination_rti.IsValid()) {
2008 if (destination_rti.IsObjectArray()) {
2009 if (destination_rti.IsExact()) {
2010 optimizations.SetDoesNotNeedTypeCheck();
2011 }
2012 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002013 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002014 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002015 destination_component_type = DataTypeFromPrimitive(
2016 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002017 optimizations.SetDestinationIsPrimitiveArray();
2018 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2019 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002020 }
2021 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002022 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2023 if (source_rti.IsValid()) {
2024 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2025 optimizations.SetDoesNotNeedTypeCheck();
2026 }
2027 if (source_rti.IsPrimitiveArrayClass()) {
2028 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002029 source_component_type = DataTypeFromPrimitive(
2030 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002031 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2032 optimizations.SetSourceIsNonPrimitiveArray();
2033 }
2034 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002035 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002036 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002037 (source_component_type == destination_component_type)) {
2038 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2039 PointerSize image_size = class_linker->GetImagePointerSize();
2040 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2041 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2042 ArtMethod* method = nullptr;
2043 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002044 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002045 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002046 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002047 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002048 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002049 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002050 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002051 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002052 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002053 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002054 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002055 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002056 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002057 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002058 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002059 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002060 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002061 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002062 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002063 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002064 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002065 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002066 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002067 break;
2068 default:
2069 LOG(FATAL) << "Unreachable";
2070 }
2071 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002072 DCHECK(method->IsStatic());
2073 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002074 invoke->SetResolvedMethod(method);
2075 // Sharpen the new invoke. Note that we do not update the dex method index of
2076 // the invoke, as we would need to look it up in the current dex file, and it
2077 // is unlikely that it exists. The most usual situation for such typed
2078 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002079 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002080 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002081 }
2082}
2083
Roland Levillaina5c4a402016-03-15 15:02:50 +00002084void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2085 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002086 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002087 DCHECK(invoke->IsInvokeStaticOrDirect());
2088 uint32_t dex_pc = invoke->GetDexPc();
2089 HInstruction* left = invoke->InputAt(0);
2090 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002091 if (!is_signum) {
2092 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002093 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002094 right = GetGraph()->GetLongConstant(0);
2095 } else {
2096 right = GetGraph()->GetIntConstant(0);
2097 }
2098 HCompare* compare = new (GetGraph()->GetArena())
2099 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2100 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2101}
2102
Aart Bik75a38b22016-02-17 10:41:50 -08002103void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2104 DCHECK(invoke->IsInvokeStaticOrDirect());
2105 uint32_t dex_pc = invoke->GetDexPc();
2106 // IsNaN(x) is the same as x != x.
2107 HInstruction* x = invoke->InputAt(0);
2108 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002109 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002110 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2111}
2112
Aart Bik2a6aad92016-02-25 11:32:32 -08002113void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2114 DCHECK(invoke->IsInvokeStaticOrDirect());
2115 uint32_t dex_pc = invoke->GetDexPc();
2116 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002117 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002118 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2119 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002120 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002121 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2122 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2123 kNeedsEnvironmentOrCache,
2124 kNoSideEffects,
2125 kNoThrow);
2126 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002127 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002128 nan = GetGraph()->GetIntConstant(0x7fc00000);
2129 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2130 kNeedsEnvironmentOrCache,
2131 kNoSideEffects,
2132 kNoThrow);
2133 }
2134 // Test IsNaN(x), which is the same as x != x.
2135 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
2136 condition->SetBias(ComparisonBias::kLtBias);
2137 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2138 // Select between the two.
2139 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
2140 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2141 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2142}
2143
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002144void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2145 HInstruction* str = invoke->InputAt(0);
2146 HInstruction* index = invoke->InputAt(1);
2147 uint32_t dex_pc = invoke->GetDexPc();
2148 ArenaAllocator* arena = GetGraph()->GetArena();
2149 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2150 // so create the HArrayLength, HBoundsCheck and HArrayGet.
2151 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
2152 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002153 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
2154 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002155 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002156 HArrayGet* array_get = new (arena) HArrayGet(str,
2157 bounds_check,
2158 DataType::Type::kUint16,
2159 SideEffects::None(), // Strings are immutable.
2160 dex_pc,
2161 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002162 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2163 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2164 GetGraph()->SetHasBoundsChecks(true);
2165}
2166
Vladimir Markodce016e2016-04-28 13:10:02 +01002167void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2168 HInstruction* str = invoke->InputAt(0);
2169 uint32_t dex_pc = invoke->GetDexPc();
2170 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2171 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002172 HArrayLength* length =
2173 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002174 HInstruction* replacement;
2175 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2176 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2177 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2178 HIntConstant* zero = GetGraph()->GetIntConstant(0);
2179 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
2180 replacement = equal;
2181 } else {
2182 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2183 replacement = length;
2184 }
2185 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2186}
2187
Aart Bikff7d89c2016-11-07 08:49:28 -08002188// This method should only be used on intrinsics whose sole way of throwing an
2189// exception is raising a NPE when the nth argument is null. If that argument
2190// is provably non-null, we can clear the flag.
2191void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2192 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002193 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002194 invoke->SetCanThrow(false);
2195 }
2196}
2197
Aart Bik71bf7b42016-11-16 10:17:46 -08002198// Methods that return "this" can replace the returned value with the receiver.
2199void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2200 if (invoke->HasUses()) {
2201 HInstruction* receiver = invoke->InputAt(0);
2202 invoke->ReplaceWith(receiver);
2203 RecordSimplification();
2204 }
2205}
2206
2207// Helper method for StringBuffer escape analysis.
2208static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2209 if (user->IsInvokeStaticOrDirect()) {
2210 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002211 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2212 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002213 user->InputAt(0) == reference;
2214 } else if (user->IsInvokeVirtual()) {
2215 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2216 case Intrinsics::kStringBufferLength:
2217 case Intrinsics::kStringBufferToString:
2218 DCHECK_EQ(user->InputAt(0), reference);
2219 return true;
2220 case Intrinsics::kStringBufferAppend:
2221 // Returns "this", so only okay if no further uses.
2222 DCHECK_EQ(user->InputAt(0), reference);
2223 DCHECK_NE(user->InputAt(1), reference);
2224 return !user->HasUses();
2225 default:
2226 break;
2227 }
2228 }
2229 return false;
2230}
2231
2232// Certain allocation intrinsics are not removed by dead code elimination
2233// because of potentially throwing an OOM exception or other side effects.
2234// This method removes such intrinsics when special circumstances allow.
2235void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2236 if (!invoke->HasUses()) {
2237 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2238 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2239 // call does not escape since only thread-local synchronization may be removed.
2240 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2241 HInstruction* receiver = invoke->InputAt(0);
2242 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2243 invoke->GetBlock()->RemoveInstruction(invoke);
2244 RecordSimplification();
2245 }
2246 }
2247}
2248
Aart Bik11932592016-03-08 12:42:25 -08002249void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2250 uint32_t dex_pc = invoke->GetDexPc();
2251 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2252 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2253}
2254
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002255void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002256 switch (instruction->GetIntrinsic()) {
2257 case Intrinsics::kStringEquals:
2258 SimplifyStringEquals(instruction);
2259 break;
2260 case Intrinsics::kSystemArrayCopy:
2261 SimplifySystemArrayCopy(instruction);
2262 break;
2263 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002264 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002265 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002266 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002267 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002268 break;
2269 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002270 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002271 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002272 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002273 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002274 break;
2275 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002276 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002277 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002278 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002279 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002280 break;
2281 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002282 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002283 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002284 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002285 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002286 break;
2287 case Intrinsics::kFloatIsNaN:
2288 case Intrinsics::kDoubleIsNaN:
2289 SimplifyIsNaN(instruction);
2290 break;
2291 case Intrinsics::kFloatFloatToIntBits:
2292 case Intrinsics::kDoubleDoubleToLongBits:
2293 SimplifyFP2Int(instruction);
2294 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002295 case Intrinsics::kStringCharAt:
2296 SimplifyStringCharAt(instruction);
2297 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002298 case Intrinsics::kStringIsEmpty:
2299 case Intrinsics::kStringLength:
2300 SimplifyStringIsEmptyOrLength(instruction);
2301 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002302 case Intrinsics::kStringStringIndexOf:
2303 case Intrinsics::kStringStringIndexOfAfter:
2304 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2305 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002306 case Intrinsics::kStringBufferAppend:
2307 case Intrinsics::kStringBuilderAppend:
2308 SimplifyReturnThis(instruction);
2309 break;
2310 case Intrinsics::kStringBufferToString:
2311 case Intrinsics::kStringBuilderToString:
2312 SimplifyAllocationIntrinsic(instruction);
2313 break;
Aart Bik11932592016-03-08 12:42:25 -08002314 case Intrinsics::kUnsafeLoadFence:
2315 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2316 break;
2317 case Intrinsics::kUnsafeStoreFence:
2318 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2319 break;
2320 case Intrinsics::kUnsafeFullFence:
2321 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2322 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002323 case Intrinsics::kVarHandleFullFence:
2324 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2325 break;
2326 case Intrinsics::kVarHandleAcquireFence:
2327 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2328 break;
2329 case Intrinsics::kVarHandleReleaseFence:
2330 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2331 break;
2332 case Intrinsics::kVarHandleLoadLoadFence:
2333 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2334 break;
2335 case Intrinsics::kVarHandleStoreStoreFence:
2336 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2337 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002338 default:
2339 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002340 }
2341}
2342
Aart Bikbb245d12015-10-19 11:05:03 -07002343void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2344 HInstruction* cond = deoptimize->InputAt(0);
2345 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002346 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002347 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002348 if (deoptimize->GuardsAnInput()) {
2349 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2350 }
Aart Bikbb245d12015-10-19 11:05:03 -07002351 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2352 } else {
2353 // Always deopt.
2354 }
2355 }
2356}
2357
Anton Kirilove14dc862016-05-13 17:56:15 +01002358// Replace code looking like
2359// OP y, x, const1
2360// OP z, y, const2
2361// with
2362// OP z, x, const3
2363// where OP is both an associative and a commutative operation.
2364bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2365 HBinaryOperation* instruction) {
2366 DCHECK(instruction->IsCommutative());
2367
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002368 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002369 return false;
2370 }
2371
2372 HInstruction* left = instruction->GetLeft();
2373 HInstruction* right = instruction->GetRight();
2374 // Variable names as described above.
2375 HConstant* const2;
2376 HBinaryOperation* y;
2377
2378 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2379 const2 = right->AsConstant();
2380 y = left->AsBinaryOperation();
2381 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2382 const2 = left->AsConstant();
2383 y = right->AsBinaryOperation();
2384 } else {
2385 // The node does not match the pattern.
2386 return false;
2387 }
2388
2389 // If `y` has more than one use, we do not perform the optimization
2390 // because it might increase code size (e.g. if the new constant is
2391 // no longer encodable as an immediate operand in the target ISA).
2392 if (!y->HasOnlyOneNonEnvironmentUse()) {
2393 return false;
2394 }
2395
2396 // GetConstantRight() can return both left and right constants
2397 // for commutative operations.
2398 HConstant* const1 = y->GetConstantRight();
2399 if (const1 == nullptr) {
2400 return false;
2401 }
2402
2403 instruction->ReplaceInput(const1, 0);
2404 instruction->ReplaceInput(const2, 1);
2405 HConstant* const3 = instruction->TryStaticEvaluation();
2406 DCHECK(const3 != nullptr);
2407 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2408 instruction->ReplaceInput(const3, 1);
2409 RecordSimplification();
2410 return true;
2411}
2412
2413static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2414 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2415}
2416
2417// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002418static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002419 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002420 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002421 return HAdd::Compute<int32_t>(x, y);
2422 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002423 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002424 return HAdd::Compute<int64_t>(x, y);
2425 }
2426}
2427
2428// Helper function that handles the child classes of HConstant
2429// and returns an integer with the appropriate sign.
2430static int64_t GetValue(HConstant* constant, bool is_negated) {
2431 int64_t ret = Int64FromConstant(constant);
2432 return is_negated ? -ret : ret;
2433}
2434
2435// Replace code looking like
2436// OP1 y, x, const1
2437// OP2 z, y, const2
2438// with
2439// OP3 z, x, const3
2440// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2441bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2442 HBinaryOperation* instruction) {
2443 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2444
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002445 DataType::Type type = instruction->GetType();
2446 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002447 return false;
2448 }
2449
2450 HInstruction* left = instruction->GetLeft();
2451 HInstruction* right = instruction->GetRight();
2452 // Variable names as described above.
2453 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2454 if (const2 == nullptr) {
2455 return false;
2456 }
2457
2458 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2459 ? left->AsBinaryOperation()
2460 : AsAddOrSub(right);
2461 // If y has more than one use, we do not perform the optimization because
2462 // it might increase code size (e.g. if the new constant is no longer
2463 // encodable as an immediate operand in the target ISA).
2464 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2465 return false;
2466 }
2467
2468 left = y->GetLeft();
2469 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2470 if (const1 == nullptr) {
2471 return false;
2472 }
2473
2474 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2475 // If both inputs are constants, let the constant folding pass deal with it.
2476 if (x->IsConstant()) {
2477 return false;
2478 }
2479
2480 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2481 int64_t const2_val = GetValue(const2, is_const2_negated);
2482 bool is_y_negated = (y == right) && instruction->IsSub();
2483 right = y->GetRight();
2484 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2485 int64_t const1_val = GetValue(const1, is_const1_negated);
2486 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2487 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2488 HBasicBlock* block = instruction->GetBlock();
2489 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2490 ArenaAllocator* arena = instruction->GetArena();
2491 HInstruction* z;
2492
2493 if (is_x_negated) {
2494 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2495 } else {
2496 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2497 }
2498
2499 block->ReplaceAndRemoveInstructionWith(instruction, z);
2500 RecordSimplification();
2501 return true;
2502}
2503
Lena Djokicbc5460b2017-07-20 16:07:36 +02002504void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2505 if (TryCombineVecMultiplyAccumulate(instruction)) {
2506 RecordSimplification();
2507 }
2508}
2509
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002510} // namespace art