blob: 1cebeb5bd7d8e99496e06a26992b3e860e4c1675 [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);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100189 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100190 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()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100228 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000229 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100230 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000231 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* hnot;
233 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100234 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000235 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100236 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000237 }
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
Vladimir Markoca6fff82017-10-03 14:49:14 +0100277 ArenaAllocator* arena = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200278
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(),
Aart Bik46b6dbc2017-10-03 11:37:37 -0700316 binop->GetVectorLength(),
317 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200318
319 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
320 DCHECK(!mul->HasUses());
321 mul->GetBlock()->RemoveInstruction(mul);
322 return true;
323 }
324 }
325 }
326
327 return false;
328}
329
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000330void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
331 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100332 HInstruction* shift_amount = instruction->GetRight();
333 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000334
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100335 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100336 ? kMaxLongShiftDistance
337 : kMaxIntShiftDistance;
338
339 if (shift_amount->IsConstant()) {
340 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700341 int64_t masked_cst = cst & implicit_mask;
342 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400343 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100344 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400345 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100346 // value
347 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400348 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100349 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100350 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700351 } else if (masked_cst != cst) {
352 // Replace code looking like
353 // SHL dst, value, cst
354 // where cst exceeds maximum distance with the equivalent
355 // SHL dst, value, cst & implicit_mask
356 // (as defined by shift semantics). This ensures other
357 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100358 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700359 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
360 RecordSimplification();
361 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100362 }
363 }
364
365 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100366 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
367 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100368 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100369 // AND adjusted_shift, shift, <superset of implicit mask>
370 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
371 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
372 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100373 // with
374 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100375 if (shift_amount->IsAnd() ||
376 shift_amount->IsOr() ||
377 shift_amount->IsXor() ||
378 shift_amount->IsAdd() ||
379 shift_amount->IsSub()) {
380 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
381 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
382 HConstant* mask = bin_op->GetConstantRight();
383 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
384 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100385 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100386 return;
387 }
388 } else if (shift_amount->IsTypeConversion()) {
389 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
390 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
391 // Non-integral and 64-bit source types require an explicit type conversion.
392 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
393 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
394 RecordSimplification();
395 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400396 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000397 }
398}
399
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000400static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
401 return (sub->GetRight() == other &&
402 sub->GetLeft()->IsConstant() &&
403 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
404}
405
406bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
407 HUShr* ushr,
408 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000409 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100410 HRor* ror =
411 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000412 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
413 if (!ushr->HasUses()) {
414 ushr->GetBlock()->RemoveInstruction(ushr);
415 }
416 if (!ushr->GetRight()->HasUses()) {
417 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
418 }
419 if (!shl->HasUses()) {
420 shl->GetBlock()->RemoveInstruction(shl);
421 }
422 if (!shl->GetRight()->HasUses()) {
423 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
424 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100425 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000426 return true;
427}
428
429// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
430bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000431 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
432 HInstruction* left = op->GetLeft();
433 HInstruction* right = op->GetRight();
434 // If we have an UShr and a Shl (in either order).
435 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
436 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
437 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100438 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000439 if (ushr->GetType() == shl->GetType() &&
440 ushr->GetLeft() == shl->GetLeft()) {
441 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
442 // Shift distances are both constant, try replacing with Ror if they
443 // add up to the register size.
444 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
445 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
446 // Shift distances are potentially of the form x and (reg_size - x).
447 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
448 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
449 // Shift distances are potentially of the form d and -d.
450 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
451 }
452 }
453 }
454 return false;
455}
456
457// Try replacing code looking like (x >>> #rdist OP x << #ldist):
458// UShr dst, x, #rdist
459// Shl tmp, x, #ldist
460// OP dst, dst, tmp
461// or like (x >>> #rdist OP x << #-ldist):
462// UShr dst, x, #rdist
463// Shl tmp, x, #-ldist
464// OP dst, dst, tmp
465// with
466// Ror dst, x, #rdist
467bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
468 HUShr* ushr,
469 HShl* shl) {
470 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100471 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000472 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
473 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
474 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
475 ReplaceRotateWithRor(op, ushr, shl);
476 return true;
477 }
478 return false;
479}
480
481// Replace code looking like (x >>> -d OP x << d):
482// Neg neg, d
483// UShr dst, x, neg
484// Shl tmp, x, d
485// OP dst, dst, tmp
486// with
487// Neg neg, d
488// Ror dst, x, neg
489// *** OR ***
490// Replace code looking like (x >>> d OP x << -d):
491// UShr dst, x, d
492// Neg neg, d
493// Shl tmp, x, neg
494// OP dst, dst, tmp
495// with
496// Ror dst, x, d
497bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
498 HUShr* ushr,
499 HShl* shl) {
500 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
501 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
502 bool neg_is_left = shl->GetRight()->IsNeg();
503 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
504 // And the shift distance being negated is the distance being shifted the other way.
505 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
506 ReplaceRotateWithRor(op, ushr, shl);
507 }
508 return false;
509}
510
511// Try replacing code looking like (x >>> d OP x << (#bits - d)):
512// UShr dst, x, d
513// Sub ld, #bits, d
514// Shl tmp, x, ld
515// OP dst, dst, tmp
516// with
517// Ror dst, x, d
518// *** OR ***
519// Replace code looking like (x >>> (#bits - d) OP x << d):
520// Sub rd, #bits, d
521// UShr dst, x, rd
522// Shl tmp, x, d
523// OP dst, dst, tmp
524// with
525// Neg neg, d
526// Ror dst, x, neg
527bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
528 HUShr* ushr,
529 HShl* shl) {
530 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
531 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100532 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000533 HInstruction* shl_shift = shl->GetRight();
534 HInstruction* ushr_shift = ushr->GetRight();
535 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
536 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
537 return ReplaceRotateWithRor(op, ushr, shl);
538 }
539 return false;
540}
541
Calin Juravle10e244f2015-01-26 18:54:32 +0000542void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
543 HInstruction* obj = null_check->InputAt(0);
544 if (!obj->CanBeNull()) {
545 null_check->ReplaceWith(obj);
546 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000547 if (stats_ != nullptr) {
548 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
549 }
550 }
551}
552
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100553bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
554 if (!input->CanBeNull()) {
555 return true;
556 }
557
Vladimir Marko46817b82016-03-29 12:21:58 +0100558 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
559 HInstruction* user = use.GetUser();
560 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100561 return true;
562 }
563 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100564
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100565 return false;
566}
567
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100568// Returns whether doing a type test between the class of `object` against `klass` has
569// a statically known outcome. The result of the test is stored in `outcome`.
570static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000571 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
572 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
573 ScopedObjectAccess soa(Thread::Current());
574 if (!obj_rti.IsValid()) {
575 // We run the simplifier before the reference type propagation so type info might not be
576 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100577 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000578 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100579
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100580 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100581 if (!class_rti.IsValid()) {
582 // Happens when the loaded class is unresolved.
583 return false;
584 }
585 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000586 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100587 *outcome = true;
588 return true;
589 } else if (obj_rti.IsExact()) {
590 // The test failed at compile time so will also fail at runtime.
591 *outcome = false;
592 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100593 } else if (!class_rti.IsInterface()
594 && !obj_rti.IsInterface()
595 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100596 // Different type hierarchy. The test will fail.
597 *outcome = false;
598 return true;
599 }
600 return false;
601}
602
603void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
604 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100605 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
606 if (load_class->NeedsAccessCheck()) {
607 // If we need to perform an access check we cannot remove the instruction.
608 return;
609 }
610
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100611 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100612 check_cast->ClearMustDoNullCheck();
613 }
614
615 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000616 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700617 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100618 return;
619 }
620
Vladimir Markoa65ed302016-03-14 21:21:29 +0000621 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
622 // the return value check with the `outcome` check, b/27651442 .
623 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700624 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100625 if (outcome) {
626 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700627 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700628 if (!load_class->HasUses()) {
629 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
630 // However, here we know that it cannot because the checkcast was successfull, hence
631 // the class was already loaded.
632 load_class->GetBlock()->RemoveInstruction(load_class);
633 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100634 } else {
635 // Don't do anything for exceptional cases for now. Ideally we should remove
636 // all instructions and blocks this instruction dominates.
637 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000638 }
639}
640
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100641void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100642 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100643 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
644 if (load_class->NeedsAccessCheck()) {
645 // If we need to perform an access check we cannot remove the instruction.
646 return;
647 }
648
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100649 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100650 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100651 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100652 instruction->ClearMustDoNullCheck();
653 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100654
655 HGraph* graph = GetGraph();
656 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700657 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100658 instruction->ReplaceWith(graph->GetIntConstant(0));
659 instruction->GetBlock()->RemoveInstruction(instruction);
660 RecordSimplification();
661 return;
662 }
663
Vladimir Marko24bd8952016-03-15 10:40:33 +0000664 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
665 // the return value check with the `outcome` check, b/27651442 .
666 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700667 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700668 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100669 if (outcome && can_be_null) {
670 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100671 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
673 instruction->ReplaceWith(test);
674 } else {
675 // We've statically determined the result of the instanceof.
676 instruction->ReplaceWith(graph->GetIntConstant(outcome));
677 }
678 RecordSimplification();
679 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700680 if (outcome && !load_class->HasUses()) {
681 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
682 // However, here we know that it cannot because the instanceof check was successfull, hence
683 // the class was already loaded.
684 load_class->GetBlock()->RemoveInstruction(load_class);
685 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100686 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100687}
688
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100689void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100690 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100691 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100692 instruction->ClearValueCanBeNull();
693 }
694}
695
696void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100697 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100698 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100699 instruction->ClearValueCanBeNull();
700 }
701}
702
Anton Shaminbdd79352016-02-15 12:48:36 +0600703static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
704 HInstruction *lhs = cond->InputAt(0);
705 HInstruction *rhs = cond->InputAt(1);
706 switch (cond->GetKind()) {
707 case HInstruction::kEqual:
708 return new (arena) HEqual(rhs, lhs);
709 case HInstruction::kNotEqual:
710 return new (arena) HNotEqual(rhs, lhs);
711 case HInstruction::kLessThan:
712 return new (arena) HGreaterThan(rhs, lhs);
713 case HInstruction::kLessThanOrEqual:
714 return new (arena) HGreaterThanOrEqual(rhs, lhs);
715 case HInstruction::kGreaterThan:
716 return new (arena) HLessThan(rhs, lhs);
717 case HInstruction::kGreaterThanOrEqual:
718 return new (arena) HLessThanOrEqual(rhs, lhs);
719 case HInstruction::kBelow:
720 return new (arena) HAbove(rhs, lhs);
721 case HInstruction::kBelowOrEqual:
722 return new (arena) HAboveOrEqual(rhs, lhs);
723 case HInstruction::kAbove:
724 return new (arena) HBelow(rhs, lhs);
725 case HInstruction::kAboveOrEqual:
726 return new (arena) HBelowOrEqual(rhs, lhs);
727 default:
728 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
729 }
730 return nullptr;
731}
732
Aart Bik2767f4b2016-10-28 15:03:53 -0700733static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100734 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700735 return true; // input has direct boolean type
736 } else if (cmp->GetUses().HasExactlyOneElement()) {
737 // Comparison also has boolean type if both its input and the instruction
738 // itself feed into the same phi node.
739 HInstruction* user = cmp->GetUses().front().GetUser();
740 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
741 }
742 return false;
743}
744
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000745void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100746 HInstruction* input_const = equal->GetConstantRight();
747 if (input_const != nullptr) {
748 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700749 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100750 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100751 // We are comparing the boolean to a constant which is of type int and can
752 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000753 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100754 // Replace (bool_value == true) with bool_value
755 equal->ReplaceWith(input_value);
756 block->RemoveInstruction(equal);
757 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000758 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700759 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500760 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
761 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100762 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100763 } else {
764 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
765 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
766 block->RemoveInstruction(equal);
767 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100768 }
Mark Mendellc4701932015-04-10 13:18:51 -0400769 } else {
770 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100771 }
Mark Mendellc4701932015-04-10 13:18:51 -0400772 } else {
773 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100774 }
775}
776
David Brazdil0d13fee2015-04-17 14:52:19 +0100777void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
778 HInstruction* input_const = not_equal->GetConstantRight();
779 if (input_const != nullptr) {
780 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700781 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100782 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100783 // We are comparing the boolean to a constant which is of type int and can
784 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000785 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700786 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500787 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
788 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000790 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100791 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100792 not_equal->ReplaceWith(input_value);
793 block->RemoveInstruction(not_equal);
794 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100795 } else {
796 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
797 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
798 block->RemoveInstruction(not_equal);
799 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100800 }
Mark Mendellc4701932015-04-10 13:18:51 -0400801 } else {
802 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100803 }
Mark Mendellc4701932015-04-10 13:18:51 -0400804 } else {
805 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100806 }
807}
808
809void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000810 HInstruction* input = bool_not->InputAt(0);
811 HInstruction* replace_with = nullptr;
812
813 if (input->IsIntConstant()) {
814 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000815 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000816 replace_with = GetGraph()->GetIntConstant(0);
817 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000818 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000819 replace_with = GetGraph()->GetIntConstant(1);
820 }
821 } else if (input->IsBooleanNot()) {
822 // Replace (!(!bool_value)) with bool_value.
823 replace_with = input->InputAt(0);
824 } else if (input->IsCondition() &&
825 // Don't change FP compares. The definition of compares involving
826 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100827 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000828 // Replace condition with its opposite.
829 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
830 }
831
832 if (replace_with != nullptr) {
833 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100834 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000835 RecordSimplification();
836 }
837}
838
Aart Bik4f7dd342017-09-12 13:12:57 -0700839// Constructs a new ABS(x) node in the HIR.
840static HInstruction* NewIntegralAbs(ArenaAllocator* arena, HInstruction* x, HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100841 DataType::Type type = x->GetType();
842 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700843 // Construct a fake intrinsic with as much context as is needed to allocate one.
844 // The intrinsic will always be lowered into code later anyway.
845 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
846 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
847 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
848 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
849 0u
850 };
851 HInvokeStaticOrDirect* invoke = new (arena) HInvokeStaticOrDirect(
852 arena,
853 1,
854 type,
855 x->GetDexPc(),
856 /*method_idx*/ -1,
857 /*resolved_method*/ nullptr,
858 dispatch_info,
859 kStatic,
860 MethodReference(nullptr, dex::kDexNoIndex),
861 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
862 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100863 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
864 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700865 kNoEnvironmentOrCache,
866 kNoSideEffects,
867 kNoThrow);
868 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
869 return invoke;
870}
871
872// Returns true if operands a and b consists of widening type conversions
873// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100874static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700875 if (a->IsTypeConversion() && a->GetType() == to_type) {
876 a = a->InputAt(0);
877 }
878 if (b->IsTypeConversion() && b->GetType() == to_type) {
879 b = b->InputAt(0);
880 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100881 DataType::Type type1 = a->GetType();
882 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100883 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
884 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
885 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
886 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
887 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100888 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700889}
890
David Brazdil74eb1b22015-12-14 11:44:01 +0000891void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
892 HInstruction* replace_with = nullptr;
893 HInstruction* condition = select->GetCondition();
894 HInstruction* true_value = select->GetTrueValue();
895 HInstruction* false_value = select->GetFalseValue();
896
897 if (condition->IsBooleanNot()) {
898 // Change ((!cond) ? x : y) to (cond ? y : x).
899 condition = condition->InputAt(0);
900 std::swap(true_value, false_value);
901 select->ReplaceInput(false_value, 0);
902 select->ReplaceInput(true_value, 1);
903 select->ReplaceInput(condition, 2);
904 RecordSimplification();
905 }
906
907 if (true_value == false_value) {
908 // Replace (cond ? x : x) with (x).
909 replace_with = true_value;
910 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000911 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000912 // Replace (true ? x : y) with (x).
913 replace_with = true_value;
914 } else {
915 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000916 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000917 replace_with = false_value;
918 }
919 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000920 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000921 // Replace (cond ? true : false) with (cond).
922 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000923 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000924 // Replace (cond ? false : true) with (!cond).
925 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
926 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700927 } else if (condition->IsCondition()) {
928 IfCondition cmp = condition->AsCondition()->GetCondition();
929 HInstruction* a = condition->InputAt(0);
930 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100931 DataType::Type t_type = true_value->GetType();
932 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700933 // Here we have a <cmp> b ? true_value : false_value.
934 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100935 if (t_type == f_type &&
936 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700937 // Try to replace typical integral ABS constructs.
938 if (true_value->IsNeg()) {
939 HInstruction* negated = true_value->InputAt(0);
940 if ((cmp == kCondLT || cmp == kCondLE) &&
941 (a == negated && a == false_value && IsInt64Value(b, 0))) {
942 // Found a < 0 ? -a : a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100943 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), false_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700944 }
945 } else if (false_value->IsNeg()) {
946 HInstruction* negated = false_value->InputAt(0);
947 if ((cmp == kCondGT || cmp == kCondGE) &&
948 (a == true_value && a == negated && IsInt64Value(b, 0))) {
949 // Found a > 0 ? a : -a which can be replaced by ABS(a).
Vladimir Markoca6fff82017-10-03 14:49:14 +0100950 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700951 }
952 } else if (true_value->IsSub() && false_value->IsSub()) {
953 HInstruction* true_sub1 = true_value->InputAt(0);
954 HInstruction* true_sub2 = true_value->InputAt(1);
955 HInstruction* false_sub1 = false_value->InputAt(0);
956 HInstruction* false_sub2 = false_value->InputAt(1);
957 if ((((cmp == kCondGT || cmp == kCondGE) &&
958 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
959 ((cmp == kCondLT || cmp == kCondLE) &&
960 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
961 AreLowerPrecisionArgs(t_type, a, b)) {
962 // Found a > b ? a - b : b - a or
963 // a < b ? b - a : a - b
964 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100965 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700966 }
967 }
968 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000969 }
970
971 if (replace_with != nullptr) {
972 select->ReplaceWith(replace_with);
973 select->GetBlock()->RemoveInstruction(select);
974 RecordSimplification();
975 }
976}
977
978void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
979 HInstruction* condition = instruction->InputAt(0);
980 if (condition->IsBooleanNot()) {
981 // Swap successors if input is negated.
982 instruction->ReplaceInput(condition->InputAt(0), 0);
983 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100984 RecordSimplification();
985 }
986}
987
Mingyao Yang0304e182015-01-30 16:41:29 -0800988void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
989 HInstruction* input = instruction->InputAt(0);
990 // If the array is a NewArray with constant size, replace the array length
991 // with the constant instruction. This helps the bounds check elimination phase.
992 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000993 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800994 if (input->IsIntConstant()) {
995 instruction->ReplaceWith(input);
996 }
997 }
998}
999
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001000void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001001 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001002 if (value->GetType() != DataType::Type::kReference) {
1003 return;
1004 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001005
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001006 if (CanEnsureNotNullAt(value, instruction)) {
1007 instruction->ClearValueCanBeNull();
1008 }
1009
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001010 if (value->IsArrayGet()) {
1011 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1012 // If the code is just swapping elements in the array, no need for a type check.
1013 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001014 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001015 }
1016 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001017
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001018 if (value->IsNullConstant()) {
1019 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001020 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001021 }
1022
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001023 ScopedObjectAccess soa(Thread::Current());
1024 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1025 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1026 if (!array_rti.IsValid()) {
1027 return;
1028 }
1029
1030 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1031 instruction->ClearNeedsTypeCheck();
1032 return;
1033 }
1034
1035 if (array_rti.IsObjectArray()) {
1036 if (array_rti.IsExact()) {
1037 instruction->ClearNeedsTypeCheck();
1038 return;
1039 }
1040 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001041 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001042}
1043
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001044static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001045 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001046 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001047 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1048 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001049 // Note: The size check excludes Uint8 as the result type.
1050 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001051 return DataType::Size(result_type) > DataType::Size(input_type) &&
1052 result_type != DataType::Type::kUint16 &&
1053 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001054}
1055
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001056void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001057 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001058 DataType::Type input_type = input->GetType();
1059 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001060 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001061 // Remove the implicit conversion; this includes conversion to the same type.
1062 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001063 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001064 RecordSimplification();
1065 return;
1066 }
1067
1068 if (input->IsTypeConversion()) {
1069 HTypeConversion* input_conversion = input->AsTypeConversion();
1070 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001071 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001072
1073 // When the first conversion is lossless, a direct conversion from the original type
1074 // to the final type yields the same result, even for a lossy second conversion, for
1075 // example float->double->int or int->double->float.
1076 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1077
1078 // For integral conversions, see if the first conversion loses only bits that the second
1079 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1080 // conversion yields the same result, for example long->int->short or int->char->short.
1081 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001082 DataType::IsIntegralType(input_type) &&
1083 DataType::IsIntegralType(original_type) &&
1084 DataType::IsIntegralType(result_type) &&
1085 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001086
1087 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1088 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001089 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001090 instruction->ReplaceWith(original_input);
1091 instruction->GetBlock()->RemoveInstruction(instruction);
1092 if (!input_conversion->HasUses()) {
1093 // Don't wait for DCE.
1094 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1095 }
1096 RecordSimplification();
1097 return;
1098 }
1099 // Otherwise simplify only if the first conversion has no other use.
1100 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1101 input_conversion->ReplaceWith(original_input);
1102 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1103 RecordSimplification();
1104 return;
1105 }
1106 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001107 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1108 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001109 HAnd* input_and = input->AsAnd();
1110 HConstant* constant = input_and->GetConstantRight();
1111 if (constant != nullptr) {
1112 int64_t value = Int64FromConstant(constant);
1113 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1114 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001115 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001116 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001117 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001118 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001119 instruction->ReplaceWith(original_input);
1120 instruction->GetBlock()->RemoveInstruction(instruction);
1121 RecordSimplification();
1122 return;
1123 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1124 input_and->ReplaceWith(original_input);
1125 input_and->GetBlock()->RemoveInstruction(input_and);
1126 RecordSimplification();
1127 return;
1128 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001129 }
1130 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001131 }
1132}
1133
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001134void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1135 HConstant* input_cst = instruction->GetConstantRight();
1136 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001137 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001138 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001139 // Replace code looking like
1140 // ADD dst, src, 0
1141 // with
1142 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001143 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1144 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1145 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001146 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001147 instruction->ReplaceWith(input_other);
1148 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001149 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001150 return;
1151 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001152 }
1153
1154 HInstruction* left = instruction->GetLeft();
1155 HInstruction* right = instruction->GetRight();
1156 bool left_is_neg = left->IsNeg();
1157 bool right_is_neg = right->IsNeg();
1158
1159 if (left_is_neg && right_is_neg) {
1160 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1161 return;
1162 }
1163 }
1164
1165 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1166 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1167 // Replace code looking like
1168 // NEG tmp, b
1169 // ADD dst, a, tmp
1170 // with
1171 // SUB dst, a, b
1172 // We do not perform the optimization if the input negation has environment
1173 // uses or multiple non-environment uses as it could lead to worse code. In
1174 // particular, we do not want the live range of `b` to be extended if we are
1175 // not sure the initial 'NEG' instruction can be removed.
1176 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001177 HSub* sub =
1178 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001179 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1180 RecordSimplification();
1181 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001182 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001183 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001184
Anton Kirilove14dc862016-05-13 17:56:15 +01001185 if (TryReplaceWithRotate(instruction)) {
1186 return;
1187 }
1188
1189 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1190 // so no need to return.
1191 TryHandleAssociativeAndCommutativeOperation(instruction);
1192
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001193 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001194 TrySubtractionChainSimplification(instruction)) {
1195 return;
1196 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001197
1198 if (integral_type) {
1199 // Replace code patterns looking like
1200 // SUB dst1, x, y SUB dst1, x, y
1201 // ADD dst2, dst1, y ADD dst2, y, dst1
1202 // with
1203 // SUB dst1, x, y
1204 // ADD instruction is not needed in this case, we may use
1205 // one of inputs of SUB instead.
1206 if (left->IsSub() && left->InputAt(1) == right) {
1207 instruction->ReplaceWith(left->InputAt(0));
1208 RecordSimplification();
1209 instruction->GetBlock()->RemoveInstruction(instruction);
1210 return;
1211 } else if (right->IsSub() && right->InputAt(1) == left) {
1212 instruction->ReplaceWith(right->InputAt(0));
1213 RecordSimplification();
1214 instruction->GetBlock()->RemoveInstruction(instruction);
1215 return;
1216 }
1217 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001218}
1219
1220void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1221 HConstant* input_cst = instruction->GetConstantRight();
1222 HInstruction* input_other = instruction->GetLeastConstantLeft();
1223
Vladimir Marko452c1b62015-09-25 14:44:17 +01001224 if (input_cst != nullptr) {
1225 int64_t value = Int64FromConstant(input_cst);
1226 if (value == -1) {
1227 // Replace code looking like
1228 // AND dst, src, 0xFFF...FF
1229 // with
1230 // src
1231 instruction->ReplaceWith(input_other);
1232 instruction->GetBlock()->RemoveInstruction(instruction);
1233 RecordSimplification();
1234 return;
1235 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001236 if (input_other->IsTypeConversion() &&
1237 input_other->GetType() == DataType::Type::kInt64 &&
1238 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1239 IsInt<32>(value) &&
1240 input_other->HasOnlyOneNonEnvironmentUse()) {
1241 // The AND can be reordered before the TypeConversion. Replace
1242 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1243 // TypeConversion<Int64> tmp, src
1244 // AND dst, tmp, cst
1245 // with
1246 // IntConstant cst, <32-bit-constant>
1247 // AND tmp, src, cst
1248 // TypeConversion<Int64> dst, tmp
1249 // This helps 32-bit targets and does not hurt 64-bit targets.
1250 // This also simplifies detection of other patterns, such as Uint8 loads.
1251 HInstruction* new_and_input = input_other->InputAt(0);
1252 // Implicit conversion Int64->Int64 would have been removed previously.
1253 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1254 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1255 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001256 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001257 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1258 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001259 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001260 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1261 input_other->GetBlock()->RemoveInstruction(input_other);
1262 RecordSimplification();
1263 // Try to process the new And now, do not wait for the next round of simplifications.
1264 instruction = new_and;
1265 input_other = new_and_input;
1266 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001267 // Eliminate And from UShr+And if the And-mask contains all the bits that
1268 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1269 // precisely clears the shifted-in sign bits.
1270 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001271 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001272 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1273 size_t num_tail_bits_set = CTZ(value + 1);
1274 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1275 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1276 instruction->ReplaceWith(input_other);
1277 instruction->GetBlock()->RemoveInstruction(instruction);
1278 RecordSimplification();
1279 return;
1280 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1281 input_other->HasOnlyOneNonEnvironmentUse()) {
1282 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1283 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001284 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko452c1b62015-09-25 14:44:17 +01001285 input_other->InputAt(0),
1286 input_other->InputAt(1),
1287 input_other->GetDexPc());
1288 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1289 input_other->GetBlock()->RemoveInstruction(input_other);
1290 RecordSimplification();
1291 return;
1292 }
1293 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001294 }
1295
1296 // We assume that GVN has run before, so we only perform a pointer comparison.
1297 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001298 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001299 if (instruction->GetLeft() == instruction->GetRight()) {
1300 // Replace code looking like
1301 // AND dst, src, src
1302 // with
1303 // src
1304 instruction->ReplaceWith(instruction->GetLeft());
1305 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001306 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001307 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001308 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001309
Anton Kirilove14dc862016-05-13 17:56:15 +01001310 if (TryDeMorganNegationFactoring(instruction)) {
1311 return;
1312 }
1313
1314 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1315 // so no need to return.
1316 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001317}
1318
Mark Mendellc4701932015-04-10 13:18:51 -04001319void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1320 VisitCondition(condition);
1321}
1322
1323void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1324 VisitCondition(condition);
1325}
1326
1327void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1328 VisitCondition(condition);
1329}
1330
1331void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1332 VisitCondition(condition);
1333}
1334
Anton Shaminbdd79352016-02-15 12:48:36 +06001335void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1336 VisitCondition(condition);
1337}
1338
1339void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1340 VisitCondition(condition);
1341}
1342
1343void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1344 VisitCondition(condition);
1345}
1346
1347void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1348 VisitCondition(condition);
1349}
Aart Bike9f37602015-10-09 11:15:55 -07001350
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001351// Recognize the following pattern:
1352// obj.getClass() ==/!= Foo.class
1353// And replace it with a constant value if the type of `obj` is statically known.
1354static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1355 HInstruction* input_one = condition->InputAt(0);
1356 HInstruction* input_two = condition->InputAt(1);
1357 HLoadClass* load_class = input_one->IsLoadClass()
1358 ? input_one->AsLoadClass()
1359 : input_two->AsLoadClass();
1360 if (load_class == nullptr) {
1361 return false;
1362 }
1363
1364 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1365 if (!class_rti.IsValid()) {
1366 // Unresolved class.
1367 return false;
1368 }
1369
1370 HInstanceFieldGet* field_get = (load_class == input_one)
1371 ? input_two->AsInstanceFieldGet()
1372 : input_one->AsInstanceFieldGet();
1373 if (field_get == nullptr) {
1374 return false;
1375 }
1376
1377 HInstruction* receiver = field_get->InputAt(0);
1378 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1379 if (!receiver_type.IsExact()) {
1380 return false;
1381 }
1382
1383 {
1384 ScopedObjectAccess soa(Thread::Current());
1385 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1386 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1387 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1388 if (field_get->GetFieldInfo().GetField() != field) {
1389 return false;
1390 }
1391
1392 // We can replace the compare.
1393 int value = 0;
1394 if (receiver_type.IsEqual(class_rti)) {
1395 value = condition->IsEqual() ? 1 : 0;
1396 } else {
1397 value = condition->IsNotEqual() ? 1 : 0;
1398 }
1399 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1400 return true;
1401 }
1402}
1403
Mark Mendellc4701932015-04-10 13:18:51 -04001404void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001405 if (condition->IsEqual() || condition->IsNotEqual()) {
1406 if (RecognizeAndSimplifyClassCheck(condition)) {
1407 return;
1408 }
1409 }
1410
Anton Shaminbdd79352016-02-15 12:48:36 +06001411 // Reverse condition if left is constant. Our code generators prefer constant
1412 // on the right hand side.
1413 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1414 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001415 HCondition* replacement =
1416 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001417 // If it is a fp we must set the opposite bias.
1418 if (replacement != nullptr) {
1419 if (condition->IsLtBias()) {
1420 replacement->SetBias(ComparisonBias::kGtBias);
1421 } else if (condition->IsGtBias()) {
1422 replacement->SetBias(ComparisonBias::kLtBias);
1423 }
1424 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1425 RecordSimplification();
1426
1427 condition = replacement;
1428 }
1429 }
Mark Mendellc4701932015-04-10 13:18:51 -04001430
Mark Mendellc4701932015-04-10 13:18:51 -04001431 HInstruction* left = condition->GetLeft();
1432 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001433
1434 // Try to fold an HCompare into this HCondition.
1435
Mark Mendellc4701932015-04-10 13:18:51 -04001436 // We can only replace an HCondition which compares a Compare to 0.
1437 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1438 // condition with a long, float or double comparison as input.
1439 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1440 // Conversion is not possible.
1441 return;
1442 }
1443
1444 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001445 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001446 // Someone else also wants the result of the compare.
1447 return;
1448 }
1449
Vladimir Marko46817b82016-03-29 12:21:58 +01001450 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001451 // There is a reference to the compare result in an environment. Do we really need it?
1452 if (GetGraph()->IsDebuggable()) {
1453 return;
1454 }
1455
1456 // We have to ensure that there are no deopt points in the sequence.
1457 if (left->HasAnyEnvironmentUseBefore(condition)) {
1458 return;
1459 }
1460 }
1461
1462 // Clean up any environment uses from the HCompare, if any.
1463 left->RemoveEnvironmentUsers();
1464
1465 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1466 condition->SetBias(left->AsCompare()->GetBias());
1467
1468 // Replace the operands of the HCondition.
1469 condition->ReplaceInput(left->InputAt(0), 0);
1470 condition->ReplaceInput(left->InputAt(1), 1);
1471
1472 // Remove the HCompare.
1473 left->GetBlock()->RemoveInstruction(left);
1474
1475 RecordSimplification();
1476}
1477
Andreas Gampe9186ced2016-12-12 14:28:21 -08001478// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1479static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1480 // True, if the most significant bits of divisor are 0.
1481 return ((divisor & 0x7fffff) == 0);
1482}
1483
1484// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1485static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1486 // True, if the most significant bits of divisor are 0.
1487 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1488}
1489
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001490void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1491 HConstant* input_cst = instruction->GetConstantRight();
1492 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001493 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001494
1495 if ((input_cst != nullptr) && input_cst->IsOne()) {
1496 // Replace code looking like
1497 // DIV dst, src, 1
1498 // with
1499 // src
1500 instruction->ReplaceWith(input_other);
1501 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001502 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001503 return;
1504 }
1505
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001506 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001507 // Replace code looking like
1508 // DIV dst, src, -1
1509 // with
1510 // NEG dst, src
1511 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001512 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001513 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001514 return;
1515 }
1516
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001518 // Try replacing code looking like
1519 // DIV dst, src, constant
1520 // with
1521 // MUL dst, src, 1 / constant
1522 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001523 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001524 double value = input_cst->AsDoubleConstant()->GetValue();
1525 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1526 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1527 }
1528 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001529 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001530 float value = input_cst->AsFloatConstant()->GetValue();
1531 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1532 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1533 }
1534 }
1535
1536 if (reciprocal != nullptr) {
1537 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001538 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001539 RecordSimplification();
1540 return;
1541 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001542 }
1543}
1544
1545void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1546 HConstant* input_cst = instruction->GetConstantRight();
1547 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001548 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001549 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001550 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001551
1552 if (input_cst == nullptr) {
1553 return;
1554 }
1555
1556 if (input_cst->IsOne()) {
1557 // Replace code looking like
1558 // MUL dst, src, 1
1559 // with
1560 // src
1561 instruction->ReplaceWith(input_other);
1562 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001563 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001564 return;
1565 }
1566
1567 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001568 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001569 // Replace code looking like
1570 // MUL dst, src, -1
1571 // with
1572 // NEG dst, src
1573 HNeg* neg = new (allocator) HNeg(type, input_other);
1574 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001575 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001576 return;
1577 }
1578
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001580 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1581 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1582 // Replace code looking like
1583 // FP_MUL dst, src, 2.0
1584 // with
1585 // FP_ADD dst, src, src
1586 // The 'int' and 'long' cases are handled below.
1587 block->ReplaceAndRemoveInstructionWith(instruction,
1588 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001589 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001590 return;
1591 }
1592
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001594 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001595 // Even though constant propagation also takes care of the zero case, other
1596 // optimizations can lead to having a zero multiplication.
1597 if (factor == 0) {
1598 // Replace code looking like
1599 // MUL dst, src, 0
1600 // with
1601 // 0
1602 instruction->ReplaceWith(input_cst);
1603 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001604 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001605 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001606 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001607 // Replace code looking like
1608 // MUL dst, src, pow_of_2
1609 // with
1610 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001611 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001612 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001613 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001614 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001615 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001616 } else if (IsPowerOfTwo(factor - 1)) {
1617 // Transform code looking like
1618 // MUL dst, src, (2^n + 1)
1619 // into
1620 // SHL tmp, src, n
1621 // ADD dst, src, tmp
1622 HShl* shl = new (allocator) HShl(type,
1623 input_other,
1624 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1625 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1626
1627 block->InsertInstructionBefore(shl, instruction);
1628 block->ReplaceAndRemoveInstructionWith(instruction, add);
1629 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001630 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001631 } else if (IsPowerOfTwo(factor + 1)) {
1632 // Transform code looking like
1633 // MUL dst, src, (2^n - 1)
1634 // into
1635 // SHL tmp, src, n
1636 // SUB dst, tmp, src
1637 HShl* shl = new (allocator) HShl(type,
1638 input_other,
1639 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1640 HSub* sub = new (allocator) HSub(type, shl, input_other);
1641
1642 block->InsertInstructionBefore(shl, instruction);
1643 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1644 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001645 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001646 }
1647 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001648
1649 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1650 // so no need to return.
1651 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001652}
1653
Alexandre Rames188d4312015-04-09 18:30:21 +01001654void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1655 HInstruction* input = instruction->GetInput();
1656 if (input->IsNeg()) {
1657 // Replace code looking like
1658 // NEG tmp, src
1659 // NEG dst, tmp
1660 // with
1661 // src
1662 HNeg* previous_neg = input->AsNeg();
1663 instruction->ReplaceWith(previous_neg->GetInput());
1664 instruction->GetBlock()->RemoveInstruction(instruction);
1665 // We perform the optimization even if the input negation has environment
1666 // uses since it allows removing the current instruction. But we only delete
1667 // the input negation only if it is does not have any uses left.
1668 if (!previous_neg->HasUses()) {
1669 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1670 }
1671 RecordSimplification();
1672 return;
1673 }
1674
Serguei Katkov339dfc22015-04-20 12:29:32 +06001675 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001676 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001677 // Replace code looking like
1678 // SUB tmp, a, b
1679 // NEG dst, tmp
1680 // with
1681 // SUB dst, b, a
1682 // We do not perform the optimization if the input subtraction has
1683 // environment uses or multiple non-environment uses as it could lead to
1684 // worse code. In particular, we do not want the live ranges of `a` and `b`
1685 // to be extended if we are not sure the initial 'SUB' instruction can be
1686 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001687 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001688 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001689 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1690 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001691 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1692 if (!sub->HasUses()) {
1693 sub->GetBlock()->RemoveInstruction(sub);
1694 }
1695 RecordSimplification();
1696 }
1697}
1698
1699void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1700 HInstruction* input = instruction->GetInput();
1701 if (input->IsNot()) {
1702 // Replace code looking like
1703 // NOT tmp, src
1704 // NOT dst, tmp
1705 // with
1706 // src
1707 // We perform the optimization even if the input negation has environment
1708 // uses since it allows removing the current instruction. But we only delete
1709 // the input negation only if it is does not have any uses left.
1710 HNot* previous_not = input->AsNot();
1711 instruction->ReplaceWith(previous_not->GetInput());
1712 instruction->GetBlock()->RemoveInstruction(instruction);
1713 if (!previous_not->HasUses()) {
1714 previous_not->GetBlock()->RemoveInstruction(previous_not);
1715 }
1716 RecordSimplification();
1717 }
1718}
1719
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001720void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1721 HConstant* input_cst = instruction->GetConstantRight();
1722 HInstruction* input_other = instruction->GetLeastConstantLeft();
1723
Roland Levillain1a653882016-03-18 18:05:57 +00001724 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001725 // Replace code looking like
1726 // OR dst, src, 0
1727 // with
1728 // src
1729 instruction->ReplaceWith(input_other);
1730 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001731 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001732 return;
1733 }
1734
1735 // We assume that GVN has run before, so we only perform a pointer comparison.
1736 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001737 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001738 if (instruction->GetLeft() == instruction->GetRight()) {
1739 // Replace code looking like
1740 // OR dst, src, src
1741 // with
1742 // src
1743 instruction->ReplaceWith(instruction->GetLeft());
1744 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001745 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001746 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001747 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001748
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001749 if (TryDeMorganNegationFactoring(instruction)) return;
1750
Anton Kirilove14dc862016-05-13 17:56:15 +01001751 if (TryReplaceWithRotate(instruction)) {
1752 return;
1753 }
1754
1755 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1756 // so no need to return.
1757 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001758}
1759
1760void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1761 VisitShift(instruction);
1762}
1763
1764void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1765 VisitShift(instruction);
1766}
1767
1768void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1769 HConstant* input_cst = instruction->GetConstantRight();
1770 HInstruction* input_other = instruction->GetLeastConstantLeft();
1771
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001772 DataType::Type type = instruction->GetType();
1773 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001774 return;
1775 }
1776
Roland Levillain1a653882016-03-18 18:05:57 +00001777 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001778 // Replace code looking like
1779 // SUB dst, src, 0
1780 // with
1781 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001782 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1783 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1784 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001785 instruction->ReplaceWith(input_other);
1786 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001787 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001788 return;
1789 }
1790
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001791 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001792 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001793
Alexandre Rames188d4312015-04-09 18:30:21 +01001794 HInstruction* left = instruction->GetLeft();
1795 HInstruction* right = instruction->GetRight();
1796 if (left->IsConstant()) {
1797 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001798 // Replace code looking like
1799 // SUB dst, 0, src
1800 // with
1801 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001802 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001803 // `x` is `0.0`, the former expression yields `0.0`, while the later
1804 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001805 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001806 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001807 RecordSimplification();
1808 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001809 }
1810 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001811
1812 if (left->IsNeg() && right->IsNeg()) {
1813 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1814 return;
1815 }
1816 }
1817
1818 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1819 // Replace code looking like
1820 // NEG tmp, b
1821 // SUB dst, a, tmp
1822 // with
1823 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01001824 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001825 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1826 RecordSimplification();
1827 right->GetBlock()->RemoveInstruction(right);
1828 return;
1829 }
1830
1831 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1832 // Replace code looking like
1833 // NEG tmp, a
1834 // SUB dst, tmp, b
1835 // with
1836 // ADD tmp, a, b
1837 // NEG dst, tmp
1838 // The second version is not intrinsically better, but enables more
1839 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001840 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01001841 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001842 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01001843 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1844 instruction->ReplaceWith(neg);
1845 instruction->GetBlock()->RemoveInstruction(instruction);
1846 RecordSimplification();
1847 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001848 return;
1849 }
1850
1851 if (TrySubtractionChainSimplification(instruction)) {
1852 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001853 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001854
1855 if (left->IsAdd()) {
1856 // Replace code patterns looking like
1857 // ADD dst1, x, y ADD dst1, x, y
1858 // SUB dst2, dst1, y SUB dst2, dst1, x
1859 // with
1860 // ADD dst1, x, y
1861 // SUB instruction is not needed in this case, we may use
1862 // one of inputs of ADD instead.
1863 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001864 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001865 if (left->InputAt(1) == right) {
1866 instruction->ReplaceWith(left->InputAt(0));
1867 RecordSimplification();
1868 instruction->GetBlock()->RemoveInstruction(instruction);
1869 return;
1870 } else if (left->InputAt(0) == right) {
1871 instruction->ReplaceWith(left->InputAt(1));
1872 RecordSimplification();
1873 instruction->GetBlock()->RemoveInstruction(instruction);
1874 return;
1875 }
1876 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001877}
1878
1879void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1880 VisitShift(instruction);
1881}
1882
1883void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1884 HConstant* input_cst = instruction->GetConstantRight();
1885 HInstruction* input_other = instruction->GetLeastConstantLeft();
1886
Roland Levillain1a653882016-03-18 18:05:57 +00001887 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001888 // Replace code looking like
1889 // XOR dst, src, 0
1890 // with
1891 // src
1892 instruction->ReplaceWith(input_other);
1893 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001894 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001895 return;
1896 }
1897
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001898 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001899 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001900 // Replace code looking like
1901 // XOR dst, src, 1
1902 // with
1903 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01001904 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001905 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1906 RecordSimplification();
1907 return;
1908 }
1909
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001910 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1911 // Replace code looking like
1912 // XOR dst, src, 0xFFF...FF
1913 // with
1914 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01001915 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001916 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001917 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001918 return;
1919 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001920
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001921 HInstruction* left = instruction->GetLeft();
1922 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001923 if (((left->IsNot() && right->IsNot()) ||
1924 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001925 left->HasOnlyOneNonEnvironmentUse() &&
1926 right->HasOnlyOneNonEnvironmentUse()) {
1927 // Replace code looking like
1928 // NOT nota, a
1929 // NOT notb, b
1930 // XOR dst, nota, notb
1931 // with
1932 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001933 instruction->ReplaceInput(left->InputAt(0), 0);
1934 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001935 left->GetBlock()->RemoveInstruction(left);
1936 right->GetBlock()->RemoveInstruction(right);
1937 RecordSimplification();
1938 return;
1939 }
1940
Anton Kirilove14dc862016-05-13 17:56:15 +01001941 if (TryReplaceWithRotate(instruction)) {
1942 return;
1943 }
1944
1945 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1946 // so no need to return.
1947 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001948}
1949
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001950void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1951 HInstruction* argument = instruction->InputAt(1);
1952 HInstruction* receiver = instruction->InputAt(0);
1953 if (receiver == argument) {
1954 // Because String.equals is an instance call, the receiver is
1955 // a null check if we don't know it's null. The argument however, will
1956 // be the actual object. So we cannot end up in a situation where both
1957 // are equal but could be null.
1958 DCHECK(CanEnsureNotNullAt(argument, instruction));
1959 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1960 instruction->GetBlock()->RemoveInstruction(instruction);
1961 } else {
1962 StringEqualsOptimizations optimizations(instruction);
1963 if (CanEnsureNotNullAt(argument, instruction)) {
1964 optimizations.SetArgumentNotNull();
1965 }
1966 ScopedObjectAccess soa(Thread::Current());
1967 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1968 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1969 optimizations.SetArgumentIsString();
1970 }
1971 }
1972}
1973
Roland Levillain22c49222016-03-18 14:04:28 +00001974void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1975 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001976 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001977 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001978 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001979 HInstruction* value = invoke->InputAt(0);
1980 HInstruction* distance = invoke->InputAt(1);
1981 // Replace the invoke with an HRor.
1982 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001983 // Unconditionally set the type of the negated distance to `int`,
1984 // as shift and rotate operations expect a 32-bit (or narrower)
1985 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001986 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001987 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1988 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001989 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001990 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1991 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001992 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001993 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1994 clinit->GetBlock()->RemoveInstruction(clinit);
1995 HInstruction* ldclass = clinit->InputAt(0);
1996 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1997 ldclass->GetBlock()->RemoveInstruction(ldclass);
1998 }
1999 }
2000}
2001
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002002static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2003 if (potential_length->IsArrayLength()) {
2004 return potential_length->InputAt(0) == potential_array;
2005 }
2006
2007 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002008 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002009 }
2010
2011 return false;
2012}
2013
2014void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2015 HInstruction* source = instruction->InputAt(0);
2016 HInstruction* destination = instruction->InputAt(2);
2017 HInstruction* count = instruction->InputAt(4);
2018 SystemArrayCopyOptimizations optimizations(instruction);
2019 if (CanEnsureNotNullAt(source, instruction)) {
2020 optimizations.SetSourceIsNotNull();
2021 }
2022 if (CanEnsureNotNullAt(destination, instruction)) {
2023 optimizations.SetDestinationIsNotNull();
2024 }
2025 if (destination == source) {
2026 optimizations.SetDestinationIsSource();
2027 }
2028
2029 if (IsArrayLengthOf(count, source)) {
2030 optimizations.SetCountIsSourceLength();
2031 }
2032
2033 if (IsArrayLengthOf(count, destination)) {
2034 optimizations.SetCountIsDestinationLength();
2035 }
2036
2037 {
2038 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002039 DataType::Type source_component_type = DataType::Type::kVoid;
2040 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002041 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2042 if (destination_rti.IsValid()) {
2043 if (destination_rti.IsObjectArray()) {
2044 if (destination_rti.IsExact()) {
2045 optimizations.SetDoesNotNeedTypeCheck();
2046 }
2047 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002048 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002049 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002050 destination_component_type = DataTypeFromPrimitive(
2051 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002052 optimizations.SetDestinationIsPrimitiveArray();
2053 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2054 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002055 }
2056 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002057 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2058 if (source_rti.IsValid()) {
2059 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2060 optimizations.SetDoesNotNeedTypeCheck();
2061 }
2062 if (source_rti.IsPrimitiveArrayClass()) {
2063 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002064 source_component_type = DataTypeFromPrimitive(
2065 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002066 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2067 optimizations.SetSourceIsNonPrimitiveArray();
2068 }
2069 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002070 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002071 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002072 (source_component_type == destination_component_type)) {
2073 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2074 PointerSize image_size = class_linker->GetImagePointerSize();
2075 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2076 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2077 ArtMethod* method = nullptr;
2078 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002079 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002080 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002081 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002082 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002083 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002084 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002085 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002086 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002087 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002088 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002089 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002090 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002091 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002092 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002093 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002094 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002095 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002096 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002097 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002098 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002099 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002100 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002101 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002102 break;
2103 default:
2104 LOG(FATAL) << "Unreachable";
2105 }
2106 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002107 DCHECK(method->IsStatic());
2108 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002109 invoke->SetResolvedMethod(method);
2110 // Sharpen the new invoke. Note that we do not update the dex method index of
2111 // the invoke, as we would need to look it up in the current dex file, and it
2112 // is unlikely that it exists. The most usual situation for such typed
2113 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002114 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002115 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002116 }
2117}
2118
Roland Levillaina5c4a402016-03-15 15:02:50 +00002119void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2120 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002121 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002122 DCHECK(invoke->IsInvokeStaticOrDirect());
2123 uint32_t dex_pc = invoke->GetDexPc();
2124 HInstruction* left = invoke->InputAt(0);
2125 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002126 if (!is_signum) {
2127 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002128 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002129 right = GetGraph()->GetLongConstant(0);
2130 } else {
2131 right = GetGraph()->GetIntConstant(0);
2132 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002133 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002134 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2135 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2136}
2137
Aart Bik75a38b22016-02-17 10:41:50 -08002138void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2139 DCHECK(invoke->IsInvokeStaticOrDirect());
2140 uint32_t dex_pc = invoke->GetDexPc();
2141 // IsNaN(x) is the same as x != x.
2142 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002143 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002144 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002145 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2146}
2147
Aart Bik2a6aad92016-02-25 11:32:32 -08002148void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2149 DCHECK(invoke->IsInvokeStaticOrDirect());
2150 uint32_t dex_pc = invoke->GetDexPc();
2151 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002152 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002153 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2154 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002155 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002156 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2157 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2158 kNeedsEnvironmentOrCache,
2159 kNoSideEffects,
2160 kNoThrow);
2161 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002162 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002163 nan = GetGraph()->GetIntConstant(0x7fc00000);
2164 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2165 kNeedsEnvironmentOrCache,
2166 kNoSideEffects,
2167 kNoThrow);
2168 }
2169 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002170 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002171 condition->SetBias(ComparisonBias::kLtBias);
2172 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2173 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002174 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002175 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2176 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2177}
2178
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002179void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2180 HInstruction* str = invoke->InputAt(0);
2181 HInstruction* index = invoke->InputAt(1);
2182 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002183 ArenaAllocator* arena = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002184 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2185 // so create the HArrayLength, HBoundsCheck and HArrayGet.
2186 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
2187 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002188 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
2189 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002190 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002191 HArrayGet* array_get = new (arena) HArrayGet(str,
2192 bounds_check,
2193 DataType::Type::kUint16,
2194 SideEffects::None(), // Strings are immutable.
2195 dex_pc,
2196 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002197 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2198 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2199 GetGraph()->SetHasBoundsChecks(true);
2200}
2201
Vladimir Markodce016e2016-04-28 13:10:02 +01002202void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2203 HInstruction* str = invoke->InputAt(0);
2204 uint32_t dex_pc = invoke->GetDexPc();
2205 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2206 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002207 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002208 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002209 HInstruction* replacement;
2210 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2211 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2212 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2213 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002214 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002215 replacement = equal;
2216 } else {
2217 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2218 replacement = length;
2219 }
2220 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2221}
2222
Aart Bikff7d89c2016-11-07 08:49:28 -08002223// This method should only be used on intrinsics whose sole way of throwing an
2224// exception is raising a NPE when the nth argument is null. If that argument
2225// is provably non-null, we can clear the flag.
2226void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2227 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002228 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002229 invoke->SetCanThrow(false);
2230 }
2231}
2232
Aart Bik71bf7b42016-11-16 10:17:46 -08002233// Methods that return "this" can replace the returned value with the receiver.
2234void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2235 if (invoke->HasUses()) {
2236 HInstruction* receiver = invoke->InputAt(0);
2237 invoke->ReplaceWith(receiver);
2238 RecordSimplification();
2239 }
2240}
2241
2242// Helper method for StringBuffer escape analysis.
2243static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2244 if (user->IsInvokeStaticOrDirect()) {
2245 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002246 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2247 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002248 user->InputAt(0) == reference;
2249 } else if (user->IsInvokeVirtual()) {
2250 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2251 case Intrinsics::kStringBufferLength:
2252 case Intrinsics::kStringBufferToString:
2253 DCHECK_EQ(user->InputAt(0), reference);
2254 return true;
2255 case Intrinsics::kStringBufferAppend:
2256 // Returns "this", so only okay if no further uses.
2257 DCHECK_EQ(user->InputAt(0), reference);
2258 DCHECK_NE(user->InputAt(1), reference);
2259 return !user->HasUses();
2260 default:
2261 break;
2262 }
2263 }
2264 return false;
2265}
2266
2267// Certain allocation intrinsics are not removed by dead code elimination
2268// because of potentially throwing an OOM exception or other side effects.
2269// This method removes such intrinsics when special circumstances allow.
2270void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2271 if (!invoke->HasUses()) {
2272 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2273 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2274 // call does not escape since only thread-local synchronization may be removed.
2275 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2276 HInstruction* receiver = invoke->InputAt(0);
2277 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2278 invoke->GetBlock()->RemoveInstruction(invoke);
2279 RecordSimplification();
2280 }
2281 }
2282}
2283
Vladimir Markoca6fff82017-10-03 14:49:14 +01002284void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2285 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002286 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002287 HMemoryBarrier* mem_barrier =
2288 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002289 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2290}
2291
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002292void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002293 switch (instruction->GetIntrinsic()) {
2294 case Intrinsics::kStringEquals:
2295 SimplifyStringEquals(instruction);
2296 break;
2297 case Intrinsics::kSystemArrayCopy:
2298 SimplifySystemArrayCopy(instruction);
2299 break;
2300 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002301 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002302 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002303 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002304 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002305 break;
2306 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002307 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002308 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002309 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002310 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002311 break;
2312 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002313 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002314 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002315 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002316 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002317 break;
2318 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002319 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002320 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002321 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002322 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002323 break;
2324 case Intrinsics::kFloatIsNaN:
2325 case Intrinsics::kDoubleIsNaN:
2326 SimplifyIsNaN(instruction);
2327 break;
2328 case Intrinsics::kFloatFloatToIntBits:
2329 case Intrinsics::kDoubleDoubleToLongBits:
2330 SimplifyFP2Int(instruction);
2331 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002332 case Intrinsics::kStringCharAt:
2333 SimplifyStringCharAt(instruction);
2334 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002335 case Intrinsics::kStringIsEmpty:
2336 case Intrinsics::kStringLength:
2337 SimplifyStringIsEmptyOrLength(instruction);
2338 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002339 case Intrinsics::kStringStringIndexOf:
2340 case Intrinsics::kStringStringIndexOfAfter:
2341 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2342 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002343 case Intrinsics::kStringBufferAppend:
2344 case Intrinsics::kStringBuilderAppend:
2345 SimplifyReturnThis(instruction);
2346 break;
2347 case Intrinsics::kStringBufferToString:
2348 case Intrinsics::kStringBuilderToString:
2349 SimplifyAllocationIntrinsic(instruction);
2350 break;
Aart Bik11932592016-03-08 12:42:25 -08002351 case Intrinsics::kUnsafeLoadFence:
2352 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2353 break;
2354 case Intrinsics::kUnsafeStoreFence:
2355 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2356 break;
2357 case Intrinsics::kUnsafeFullFence:
2358 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2359 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002360 case Intrinsics::kVarHandleFullFence:
2361 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2362 break;
2363 case Intrinsics::kVarHandleAcquireFence:
2364 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2365 break;
2366 case Intrinsics::kVarHandleReleaseFence:
2367 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2368 break;
2369 case Intrinsics::kVarHandleLoadLoadFence:
2370 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2371 break;
2372 case Intrinsics::kVarHandleStoreStoreFence:
2373 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2374 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002375 default:
2376 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002377 }
2378}
2379
Aart Bikbb245d12015-10-19 11:05:03 -07002380void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2381 HInstruction* cond = deoptimize->InputAt(0);
2382 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002383 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002384 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002385 if (deoptimize->GuardsAnInput()) {
2386 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2387 }
Aart Bikbb245d12015-10-19 11:05:03 -07002388 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2389 } else {
2390 // Always deopt.
2391 }
2392 }
2393}
2394
Anton Kirilove14dc862016-05-13 17:56:15 +01002395// Replace code looking like
2396// OP y, x, const1
2397// OP z, y, const2
2398// with
2399// OP z, x, const3
2400// where OP is both an associative and a commutative operation.
2401bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2402 HBinaryOperation* instruction) {
2403 DCHECK(instruction->IsCommutative());
2404
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002405 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002406 return false;
2407 }
2408
2409 HInstruction* left = instruction->GetLeft();
2410 HInstruction* right = instruction->GetRight();
2411 // Variable names as described above.
2412 HConstant* const2;
2413 HBinaryOperation* y;
2414
2415 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2416 const2 = right->AsConstant();
2417 y = left->AsBinaryOperation();
2418 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2419 const2 = left->AsConstant();
2420 y = right->AsBinaryOperation();
2421 } else {
2422 // The node does not match the pattern.
2423 return false;
2424 }
2425
2426 // If `y` has more than one use, we do not perform the optimization
2427 // because it might increase code size (e.g. if the new constant is
2428 // no longer encodable as an immediate operand in the target ISA).
2429 if (!y->HasOnlyOneNonEnvironmentUse()) {
2430 return false;
2431 }
2432
2433 // GetConstantRight() can return both left and right constants
2434 // for commutative operations.
2435 HConstant* const1 = y->GetConstantRight();
2436 if (const1 == nullptr) {
2437 return false;
2438 }
2439
2440 instruction->ReplaceInput(const1, 0);
2441 instruction->ReplaceInput(const2, 1);
2442 HConstant* const3 = instruction->TryStaticEvaluation();
2443 DCHECK(const3 != nullptr);
2444 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2445 instruction->ReplaceInput(const3, 1);
2446 RecordSimplification();
2447 return true;
2448}
2449
2450static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2451 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2452}
2453
2454// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002455static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002456 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002457 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002458 return HAdd::Compute<int32_t>(x, y);
2459 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002460 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002461 return HAdd::Compute<int64_t>(x, y);
2462 }
2463}
2464
2465// Helper function that handles the child classes of HConstant
2466// and returns an integer with the appropriate sign.
2467static int64_t GetValue(HConstant* constant, bool is_negated) {
2468 int64_t ret = Int64FromConstant(constant);
2469 return is_negated ? -ret : ret;
2470}
2471
2472// Replace code looking like
2473// OP1 y, x, const1
2474// OP2 z, y, const2
2475// with
2476// OP3 z, x, const3
2477// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2478bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2479 HBinaryOperation* instruction) {
2480 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2481
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002482 DataType::Type type = instruction->GetType();
2483 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002484 return false;
2485 }
2486
2487 HInstruction* left = instruction->GetLeft();
2488 HInstruction* right = instruction->GetRight();
2489 // Variable names as described above.
2490 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2491 if (const2 == nullptr) {
2492 return false;
2493 }
2494
2495 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2496 ? left->AsBinaryOperation()
2497 : AsAddOrSub(right);
2498 // If y has more than one use, we do not perform the optimization because
2499 // it might increase code size (e.g. if the new constant is no longer
2500 // encodable as an immediate operand in the target ISA).
2501 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2502 return false;
2503 }
2504
2505 left = y->GetLeft();
2506 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2507 if (const1 == nullptr) {
2508 return false;
2509 }
2510
2511 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2512 // If both inputs are constants, let the constant folding pass deal with it.
2513 if (x->IsConstant()) {
2514 return false;
2515 }
2516
2517 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2518 int64_t const2_val = GetValue(const2, is_const2_negated);
2519 bool is_y_negated = (y == right) && instruction->IsSub();
2520 right = y->GetRight();
2521 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2522 int64_t const1_val = GetValue(const1, is_const1_negated);
2523 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2524 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2525 HBasicBlock* block = instruction->GetBlock();
2526 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002527 ArenaAllocator* arena = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002528 HInstruction* z;
2529
2530 if (is_x_negated) {
2531 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2532 } else {
2533 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2534 }
2535
2536 block->ReplaceAndRemoveInstructionWith(instruction, z);
2537 RecordSimplification();
2538 return true;
2539}
2540
Lena Djokicbc5460b2017-07-20 16:07:36 +02002541void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2542 if (TryCombineVecMultiplyAccumulate(instruction)) {
2543 RecordSimplification();
2544 }
2545}
2546
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002547} // namespace art