blob: d3cf9568c2db513111351464c7043e20202636d4 [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
Artem Serovcced8ba2017-07-19 18:18:09 +010030// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
31// is replaced with its copy if it is clonable.
32static constexpr bool kTestInstructionClonerExhaustively = false;
33
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010034class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000035 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000036 InstructionSimplifierVisitor(HGraph* graph,
37 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010038 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000039 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010040 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000041 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010042 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010043 stats_(stats) {}
44
45 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000046
47 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010048 void RecordSimplification() {
49 simplification_occurred_ = true;
50 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000051 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010052 }
53
Scott Wakeling40a04bf2015-12-11 09:50:36 +000054 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55 bool TryReplaceWithRotate(HBinaryOperation* instruction);
56 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
57 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
59
Alexandre Rames188d4312015-04-09 18:30:21 +010060 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000061 // `op` should be either HOr or HAnd.
62 // De Morgan's laws:
63 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
64 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010065 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
66 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020067 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010068
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000069 void VisitShift(HBinaryOperation* shift);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000070 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010071 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
72 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010073 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
74 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000075 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000076 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000077 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080078 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000079 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Aart Bikc6eec4b2018-03-29 17:22:00 -070080 void VisitAbs(HAbs* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000081 void VisitAdd(HAdd* instruction) OVERRIDE;
82 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040083 void VisitCondition(HCondition* instruction) OVERRIDE;
84 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
85 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
86 void VisitLessThan(HLessThan* condition) OVERRIDE;
87 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060088 void VisitBelow(HBelow* condition) OVERRIDE;
89 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
90 void VisitAbove(HAbove* condition) OVERRIDE;
91 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitDiv(HDiv* instruction) OVERRIDE;
93 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010094 void VisitNeg(HNeg* instruction) OVERRIDE;
95 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000096 void VisitOr(HOr* instruction) OVERRIDE;
97 void VisitShl(HShl* instruction) OVERRIDE;
98 void VisitShr(HShr* instruction) OVERRIDE;
99 void VisitSub(HSub* instruction) OVERRIDE;
100 void VisitUShr(HUShr* instruction) OVERRIDE;
101 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +0000102 void VisitSelect(HSelect* select) OVERRIDE;
103 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100104 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100105 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700106 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200107 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100108
109 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000110
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100111 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100112 void SimplifySystemArrayCopy(HInvoke* invoke);
113 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100114 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800115 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800116 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100117 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100118 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800119 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800120 void SimplifyReturnThis(HInvoke* invoke);
121 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800122 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Aart Bik1f8d51b2018-02-15 10:42:37 -0800123 void SimplifyMin(HInvoke* invoke, DataType::Type type);
124 void SimplifyMax(HInvoke* invoke, DataType::Type type);
Aart Bik3dad3412018-02-28 12:01:46 -0800125 void SimplifyAbs(HInvoke* invoke, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100126
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000127 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100128 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000129 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100130 bool simplification_occurred_ = false;
131 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700132 // We ensure we do not loop infinitely. The value should not be too high, since that
133 // would allow looping around the same basic block too many times. The value should
134 // not be too low either, however, since we want to allow revisiting a basic block
135 // with many statements and simplifications at least once.
136 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000137};
138
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100139void InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100140 if (kTestInstructionClonerExhaustively) {
141 CloneAndReplaceInstructionVisitor visitor(graph_);
142 visitor.VisitReversePostOrder();
143 }
144
Vladimir Marko65979462017-05-19 17:25:12 +0100145 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100146 visitor.Run();
147}
148
149void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100150 // Iterate in reverse post order to open up more simplifications to users
151 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100152 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100153 // The simplification of an instruction to another instruction may yield
154 // possibilities for other simplifications. So although we perform a reverse
155 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100156 do {
157 simplification_occurred_ = false;
158 VisitBasicBlock(block);
159 } while (simplification_occurred_ &&
160 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100161 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100162 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100163}
164
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000165namespace {
166
167bool AreAllBitsSet(HConstant* constant) {
168 return Int64FromConstant(constant) == -1;
169}
170
171} // namespace
172
Alexandre Rames188d4312015-04-09 18:30:21 +0100173// Returns true if the code was simplified to use only one negation operation
174// after the binary operation instead of one on each of the inputs.
175bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
176 DCHECK(binop->IsAdd() || binop->IsSub());
177 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
178 HNeg* left_neg = binop->GetLeft()->AsNeg();
179 HNeg* right_neg = binop->GetRight()->AsNeg();
180 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
181 !right_neg->HasOnlyOneNonEnvironmentUse()) {
182 return false;
183 }
184 // Replace code looking like
185 // NEG tmp1, a
186 // NEG tmp2, b
187 // ADD dst, tmp1, tmp2
188 // with
189 // ADD tmp, a, b
190 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600191 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
192 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
193 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100194 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600195 return false;
196 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100197 binop->ReplaceInput(left_neg->GetInput(), 0);
198 binop->ReplaceInput(right_neg->GetInput(), 1);
199 left_neg->GetBlock()->RemoveInstruction(left_neg);
200 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100201 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100202 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
203 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
204 RecordSimplification();
205 return true;
206}
207
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000208bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
209 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100210 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000211 HInstruction* left = op->GetLeft();
212 HInstruction* right = op->GetRight();
213
214 // We can apply De Morgan's laws if both inputs are Not's and are only used
215 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000216 if (((left->IsNot() && right->IsNot()) ||
217 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000218 left->HasOnlyOneNonEnvironmentUse() &&
219 right->HasOnlyOneNonEnvironmentUse()) {
220 // Replace code looking like
221 // NOT nota, a
222 // NOT notb, b
223 // AND dst, nota, notb (respectively OR)
224 // with
225 // OR or, a, b (respectively AND)
226 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000227 HInstruction* src_left = left->InputAt(0);
228 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000229 uint32_t dex_pc = op->GetDexPc();
230
231 // Remove the negations on the inputs.
232 left->ReplaceWith(src_left);
233 right->ReplaceWith(src_right);
234 left->GetBlock()->RemoveInstruction(left);
235 right->GetBlock()->RemoveInstruction(right);
236
237 // Replace the `HAnd` or `HOr`.
238 HBinaryOperation* hbin;
239 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100240 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000241 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100242 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000243 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000244 HInstruction* hnot;
245 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100246 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000247 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100248 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000249 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000250
251 op->GetBlock()->InsertInstructionBefore(hbin, op);
252 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
253
254 RecordSimplification();
255 return true;
256 }
257
258 return false;
259}
260
Lena Djokicbc5460b2017-07-20 16:07:36 +0200261bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100262 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200263 InstructionSet isa = codegen_->GetInstructionSet();
264 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000265 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100266 if (!(type == DataType::Type::kUint8 ||
267 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100268 type == DataType::Type::kUint16 ||
269 type == DataType::Type::kInt16 ||
270 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200271 return false;
272 }
273 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000274 case InstructionSet::kMips:
275 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100276 if (!(type == DataType::Type::kUint8 ||
277 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100278 type == DataType::Type::kUint16 ||
279 type == DataType::Type::kInt16 ||
280 type == DataType::Type::kInt32 ||
281 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200282 return false;
283 }
284 break;
285 default:
286 return false;
287 }
288
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100289 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200290
291 if (mul->HasOnlyOneNonEnvironmentUse()) {
292 HInstruction* use = mul->GetUses().front().GetUser();
293 if (use->IsVecAdd() || use->IsVecSub()) {
294 // Replace code looking like
295 // VECMUL tmp, x, y
296 // VECADD/SUB dst, acc, tmp
297 // with
298 // VECMULACC dst, acc, x, y
299 // Note that we do not want to (unconditionally) perform the merge when the
300 // multiplication has multiple uses and it can be merged in all of them.
301 // Multiple uses could happen on the same control-flow path, and we would
302 // then increase the amount of work. In the future we could try to evaluate
303 // whether all uses are on different control-flow paths (using dominance and
304 // reverse-dominance information) and only perform the merge when they are.
305 HInstruction* accumulator = nullptr;
306 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
307 HInstruction* binop_left = binop->GetLeft();
308 HInstruction* binop_right = binop->GetRight();
309 // This is always true since the `HVecMul` has only one use (which is checked above).
310 DCHECK_NE(binop_left, binop_right);
311 if (binop_right == mul) {
312 accumulator = binop_left;
313 } else if (use->IsVecAdd()) {
314 DCHECK_EQ(binop_left, mul);
315 accumulator = binop_right;
316 }
317
318 HInstruction::InstructionKind kind =
319 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
320 if (accumulator != nullptr) {
321 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100322 new (allocator) HVecMultiplyAccumulate(allocator,
323 kind,
324 accumulator,
325 mul->GetLeft(),
326 mul->GetRight(),
327 binop->GetPackedType(),
328 binop->GetVectorLength(),
329 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200330
331 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
332 DCHECK(!mul->HasUses());
333 mul->GetBlock()->RemoveInstruction(mul);
334 return true;
335 }
336 }
337 }
338
339 return false;
340}
341
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000342void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
343 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100344 HInstruction* shift_amount = instruction->GetRight();
345 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000346
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100347 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100348 ? kMaxLongShiftDistance
349 : kMaxIntShiftDistance;
350
351 if (shift_amount->IsConstant()) {
352 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700353 int64_t masked_cst = cst & implicit_mask;
354 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400355 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100356 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400357 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100358 // value
359 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400360 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100361 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100362 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700363 } else if (masked_cst != cst) {
364 // Replace code looking like
365 // SHL dst, value, cst
366 // where cst exceeds maximum distance with the equivalent
367 // SHL dst, value, cst & implicit_mask
368 // (as defined by shift semantics). This ensures other
369 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100370 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700371 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
372 RecordSimplification();
373 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100374 }
375 }
376
377 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100378 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
379 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100380 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100381 // AND adjusted_shift, shift, <superset of implicit mask>
382 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
383 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
384 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100385 // with
386 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100387 if (shift_amount->IsAnd() ||
388 shift_amount->IsOr() ||
389 shift_amount->IsXor() ||
390 shift_amount->IsAdd() ||
391 shift_amount->IsSub()) {
392 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
393 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
394 HConstant* mask = bin_op->GetConstantRight();
395 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
396 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100397 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100398 return;
399 }
400 } else if (shift_amount->IsTypeConversion()) {
401 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
402 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
403 // Non-integral and 64-bit source types require an explicit type conversion.
404 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
405 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
406 RecordSimplification();
407 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400408 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000409 }
410}
411
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000412static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
413 return (sub->GetRight() == other &&
414 sub->GetLeft()->IsConstant() &&
415 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
416}
417
418bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
419 HUShr* ushr,
420 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000421 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100422 HRor* ror =
423 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000424 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
425 if (!ushr->HasUses()) {
426 ushr->GetBlock()->RemoveInstruction(ushr);
427 }
428 if (!ushr->GetRight()->HasUses()) {
429 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
430 }
431 if (!shl->HasUses()) {
432 shl->GetBlock()->RemoveInstruction(shl);
433 }
434 if (!shl->GetRight()->HasUses()) {
435 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
436 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100437 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000438 return true;
439}
440
441// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
442bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000443 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
444 HInstruction* left = op->GetLeft();
445 HInstruction* right = op->GetRight();
446 // If we have an UShr and a Shl (in either order).
447 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
448 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
449 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100450 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000451 if (ushr->GetType() == shl->GetType() &&
452 ushr->GetLeft() == shl->GetLeft()) {
453 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
454 // Shift distances are both constant, try replacing with Ror if they
455 // add up to the register size.
456 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
457 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
458 // Shift distances are potentially of the form x and (reg_size - x).
459 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
460 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
461 // Shift distances are potentially of the form d and -d.
462 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
463 }
464 }
465 }
466 return false;
467}
468
469// Try replacing code looking like (x >>> #rdist OP x << #ldist):
470// UShr dst, x, #rdist
471// Shl tmp, x, #ldist
472// OP dst, dst, tmp
473// or like (x >>> #rdist OP x << #-ldist):
474// UShr dst, x, #rdist
475// Shl tmp, x, #-ldist
476// OP dst, dst, tmp
477// with
478// Ror dst, x, #rdist
479bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
480 HUShr* ushr,
481 HShl* shl) {
482 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100483 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000484 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
485 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
486 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
487 ReplaceRotateWithRor(op, ushr, shl);
488 return true;
489 }
490 return false;
491}
492
493// Replace code looking like (x >>> -d OP x << d):
494// Neg neg, d
495// UShr dst, x, neg
496// Shl tmp, x, d
497// OP dst, dst, tmp
498// with
499// Neg neg, d
500// Ror dst, x, neg
501// *** OR ***
502// Replace code looking like (x >>> d OP x << -d):
503// UShr dst, x, d
504// Neg neg, d
505// Shl tmp, x, neg
506// OP dst, dst, tmp
507// with
508// Ror dst, x, d
509bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
510 HUShr* ushr,
511 HShl* shl) {
512 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
513 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
514 bool neg_is_left = shl->GetRight()->IsNeg();
515 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
516 // And the shift distance being negated is the distance being shifted the other way.
517 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
518 ReplaceRotateWithRor(op, ushr, shl);
519 }
520 return false;
521}
522
523// Try replacing code looking like (x >>> d OP x << (#bits - d)):
524// UShr dst, x, d
525// Sub ld, #bits, d
526// Shl tmp, x, ld
527// OP dst, dst, tmp
528// with
529// Ror dst, x, d
530// *** OR ***
531// Replace code looking like (x >>> (#bits - d) OP x << d):
532// Sub rd, #bits, d
533// UShr dst, x, rd
534// Shl tmp, x, d
535// OP dst, dst, tmp
536// with
537// Neg neg, d
538// Ror dst, x, neg
539bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
540 HUShr* ushr,
541 HShl* shl) {
542 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
543 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100544 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000545 HInstruction* shl_shift = shl->GetRight();
546 HInstruction* ushr_shift = ushr->GetRight();
547 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
548 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
549 return ReplaceRotateWithRor(op, ushr, shl);
550 }
551 return false;
552}
553
Calin Juravle10e244f2015-01-26 18:54:32 +0000554void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
555 HInstruction* obj = null_check->InputAt(0);
556 if (!obj->CanBeNull()) {
557 null_check->ReplaceWith(obj);
558 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000559 if (stats_ != nullptr) {
560 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
561 }
562 }
563}
564
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100565bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
566 if (!input->CanBeNull()) {
567 return true;
568 }
569
Vladimir Marko46817b82016-03-29 12:21:58 +0100570 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
571 HInstruction* user = use.GetUser();
572 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100573 return true;
574 }
575 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100576
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100577 return false;
578}
579
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100580// Returns whether doing a type test between the class of `object` against `klass` has
581// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000582static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
583 HInstruction* object,
584 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000585 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
586 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
587 ScopedObjectAccess soa(Thread::Current());
588 if (!obj_rti.IsValid()) {
589 // We run the simplifier before the reference type propagation so type info might not be
590 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100591 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000592 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100593
Calin Juravle98893e12015-10-02 21:05:03 +0100594 if (!class_rti.IsValid()) {
595 // Happens when the loaded class is unresolved.
596 return false;
597 }
598 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000599 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100600 *outcome = true;
601 return true;
602 } else if (obj_rti.IsExact()) {
603 // The test failed at compile time so will also fail at runtime.
604 *outcome = false;
605 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100606 } else if (!class_rti.IsInterface()
607 && !obj_rti.IsInterface()
608 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100609 // Different type hierarchy. The test will fail.
610 *outcome = false;
611 return true;
612 }
613 return false;
614}
615
616void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
617 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000618 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
619 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100620 // If we need to perform an access check we cannot remove the instruction.
621 return;
622 }
623
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100624 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100625 check_cast->ClearMustDoNullCheck();
626 }
627
628 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000629 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700630 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100631 return;
632 }
633
Vladimir Markoa65ed302016-03-14 21:21:29 +0000634 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
635 // the return value check with the `outcome` check, b/27651442 .
636 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000637 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100638 if (outcome) {
639 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700640 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000641 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
642 HLoadClass* load_class = check_cast->GetTargetClass();
643 if (!load_class->HasUses()) {
644 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
645 // However, here we know that it cannot because the checkcast was successfull, hence
646 // the class was already loaded.
647 load_class->GetBlock()->RemoveInstruction(load_class);
648 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700649 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100650 } else {
651 // Don't do anything for exceptional cases for now. Ideally we should remove
652 // all instructions and blocks this instruction dominates.
653 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000654 }
655}
656
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100657void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100658 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000659 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
660 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100661 // If we need to perform an access check we cannot remove the instruction.
662 return;
663 }
664
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100665 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100666 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100667 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100668 instruction->ClearMustDoNullCheck();
669 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100670
671 HGraph* graph = GetGraph();
672 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000673 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100674 instruction->ReplaceWith(graph->GetIntConstant(0));
675 instruction->GetBlock()->RemoveInstruction(instruction);
676 RecordSimplification();
677 return;
678 }
679
Vladimir Marko24bd8952016-03-15 10:40:33 +0000680 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
681 // the return value check with the `outcome` check, b/27651442 .
682 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000683 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000684 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100685 if (outcome && can_be_null) {
686 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100687 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100688 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
689 instruction->ReplaceWith(test);
690 } else {
691 // We've statically determined the result of the instanceof.
692 instruction->ReplaceWith(graph->GetIntConstant(outcome));
693 }
694 RecordSimplification();
695 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000696 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
697 HLoadClass* load_class = instruction->GetTargetClass();
698 if (!load_class->HasUses()) {
699 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
700 // However, here we know that it cannot because the instanceof check was successfull, hence
701 // the class was already loaded.
702 load_class->GetBlock()->RemoveInstruction(load_class);
703 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700704 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100705 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100706}
707
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100708void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100709 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100710 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100711 instruction->ClearValueCanBeNull();
712 }
713}
714
715void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100716 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100717 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100718 instruction->ClearValueCanBeNull();
719 }
720}
721
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100722static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600723 HInstruction *lhs = cond->InputAt(0);
724 HInstruction *rhs = cond->InputAt(1);
725 switch (cond->GetKind()) {
726 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100727 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600728 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100729 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600730 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100731 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600732 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100733 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600734 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100735 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600736 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100737 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600738 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100739 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600740 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100741 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600742 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100743 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600744 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100745 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600746 default:
747 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
748 }
749 return nullptr;
750}
751
Aart Bik2767f4b2016-10-28 15:03:53 -0700752static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100753 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700754 return true; // input has direct boolean type
755 } else if (cmp->GetUses().HasExactlyOneElement()) {
756 // Comparison also has boolean type if both its input and the instruction
757 // itself feed into the same phi node.
758 HInstruction* user = cmp->GetUses().front().GetUser();
759 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
760 }
761 return false;
762}
763
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000764void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100765 HInstruction* input_const = equal->GetConstantRight();
766 if (input_const != nullptr) {
767 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700768 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100769 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100770 // We are comparing the boolean to a constant which is of type int and can
771 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000772 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100773 // Replace (bool_value == true) with bool_value
774 equal->ReplaceWith(input_value);
775 block->RemoveInstruction(equal);
776 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000777 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700778 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500779 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
780 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100781 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100782 } else {
783 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
784 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
785 block->RemoveInstruction(equal);
786 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100787 }
Mark Mendellc4701932015-04-10 13:18:51 -0400788 } else {
789 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100790 }
Mark Mendellc4701932015-04-10 13:18:51 -0400791 } else {
792 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100793 }
794}
795
David Brazdil0d13fee2015-04-17 14:52:19 +0100796void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
797 HInstruction* input_const = not_equal->GetConstantRight();
798 if (input_const != nullptr) {
799 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700800 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100801 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100802 // We are comparing the boolean to a constant which is of type int and can
803 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000804 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700805 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500806 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
807 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100808 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000809 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100810 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100811 not_equal->ReplaceWith(input_value);
812 block->RemoveInstruction(not_equal);
813 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100814 } else {
815 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
816 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
817 block->RemoveInstruction(not_equal);
818 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100819 }
Mark Mendellc4701932015-04-10 13:18:51 -0400820 } else {
821 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100822 }
Mark Mendellc4701932015-04-10 13:18:51 -0400823 } else {
824 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100825 }
826}
827
828void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000829 HInstruction* input = bool_not->InputAt(0);
830 HInstruction* replace_with = nullptr;
831
832 if (input->IsIntConstant()) {
833 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000834 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000835 replace_with = GetGraph()->GetIntConstant(0);
836 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000837 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000838 replace_with = GetGraph()->GetIntConstant(1);
839 }
840 } else if (input->IsBooleanNot()) {
841 // Replace (!(!bool_value)) with bool_value.
842 replace_with = input->InputAt(0);
843 } else if (input->IsCondition() &&
844 // Don't change FP compares. The definition of compares involving
845 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100846 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000847 // Replace condition with its opposite.
848 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
849 }
850
851 if (replace_with != nullptr) {
852 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100853 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000854 RecordSimplification();
855 }
856}
857
Aart Bik4f7dd342017-09-12 13:12:57 -0700858// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100859static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
860 HInstruction* x,
861 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700862 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800863 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700864 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800865 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
866 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700867}
868
Aart Bik142b9132018-03-14 15:12:59 -0700869// Constructs a new MIN/MAX(x, y) node in the HIR.
870static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
871 HInstruction* x,
872 HInstruction* y,
873 HInstruction* cursor,
874 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700875 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700876 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
877 HBinaryOperation* minmax = nullptr;
878 if (is_min) {
879 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
880 } else {
881 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
882 }
883 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
884 return minmax;
885}
886
Aart Bik4f7dd342017-09-12 13:12:57 -0700887// Returns true if operands a and b consists of widening type conversions
888// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100889static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700890 if (a->IsTypeConversion() && a->GetType() == to_type) {
891 a = a->InputAt(0);
892 }
893 if (b->IsTypeConversion() && b->GetType() == to_type) {
894 b = b->InputAt(0);
895 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100896 DataType::Type type1 = a->GetType();
897 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100898 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
899 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
900 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
901 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
902 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100903 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700904}
905
Aart Bik1d746de2018-03-28 16:30:02 -0700906// Returns an acceptable substitution for "a" on the select
907// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
908static HInstruction* AllowInMinMax(IfCondition cmp,
909 HInstruction* a,
910 HInstruction* b,
911 HInstruction* c) {
912 int64_t value = 0;
913 if (IsInt64AndGet(b, /*out*/ &value) &&
914 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
915 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
916 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
917 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
918 int64_t other_value = Int64FromConstant(other);
919 bool is_max = (cmp == kCondLT || cmp == kCondLE);
920 // Allow the max for a < 100 ? max(a, -100) : ..
921 // or the min for a > -100 ? min(a, 100) : ..
922 if (is_max ? (value >= other_value) : (value <= other_value)) {
923 return c;
924 }
925 }
926 }
927 return nullptr;
928}
929
David Brazdil74eb1b22015-12-14 11:44:01 +0000930void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
931 HInstruction* replace_with = nullptr;
932 HInstruction* condition = select->GetCondition();
933 HInstruction* true_value = select->GetTrueValue();
934 HInstruction* false_value = select->GetFalseValue();
935
936 if (condition->IsBooleanNot()) {
937 // Change ((!cond) ? x : y) to (cond ? y : x).
938 condition = condition->InputAt(0);
939 std::swap(true_value, false_value);
940 select->ReplaceInput(false_value, 0);
941 select->ReplaceInput(true_value, 1);
942 select->ReplaceInput(condition, 2);
943 RecordSimplification();
944 }
945
946 if (true_value == false_value) {
947 // Replace (cond ? x : x) with (x).
948 replace_with = true_value;
949 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000950 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000951 // Replace (true ? x : y) with (x).
952 replace_with = true_value;
953 } else {
954 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000955 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000956 replace_with = false_value;
957 }
958 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000959 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000960 // Replace (cond ? true : false) with (cond).
961 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000962 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000963 // Replace (cond ? false : true) with (!cond).
964 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
965 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700966 } else if (condition->IsCondition()) {
967 IfCondition cmp = condition->AsCondition()->GetCondition();
968 HInstruction* a = condition->InputAt(0);
969 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100970 DataType::Type t_type = true_value->GetType();
971 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700972 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700973 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
974 // type will be int or long, like the condition). Replacements are general,
975 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700976 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700977 // Allow a < 100 ? max(a, -100) : ..
978 // or a > -100 ? min(a, 100) : ..
979 // to use min/max instead of a to detect nested min/max expressions.
980 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
981 if (new_a != nullptr) {
982 a = new_a;
983 }
Aart Bik142b9132018-03-14 15:12:59 -0700984 // Try to replace typical integral MIN/MAX/ABS constructs.
985 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
986 ((a == true_value && b == false_value) ||
987 (b == true_value && a == false_value))) {
988 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
989 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
990 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
991 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700992 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
993 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
994 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
995 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
996 HInstruction* not_negated = negLeft ? false_value : true_value;
997 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
998 // Found a < 0 ? -a : a
999 // or a > 0 ? a : -a
1000 // which can be replaced by ABS(a).
1001 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001002 }
1003 } else if (true_value->IsSub() && false_value->IsSub()) {
1004 HInstruction* true_sub1 = true_value->InputAt(0);
1005 HInstruction* true_sub2 = true_value->InputAt(1);
1006 HInstruction* false_sub1 = false_value->InputAt(0);
1007 HInstruction* false_sub2 = false_value->InputAt(1);
1008 if ((((cmp == kCondGT || cmp == kCondGE) &&
1009 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1010 ((cmp == kCondLT || cmp == kCondLE) &&
1011 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1012 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001013 // Found a > b ? a - b : b - a
1014 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001015 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001016 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001017 }
1018 }
1019 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001020 }
1021
1022 if (replace_with != nullptr) {
1023 select->ReplaceWith(replace_with);
1024 select->GetBlock()->RemoveInstruction(select);
1025 RecordSimplification();
1026 }
1027}
1028
1029void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1030 HInstruction* condition = instruction->InputAt(0);
1031 if (condition->IsBooleanNot()) {
1032 // Swap successors if input is negated.
1033 instruction->ReplaceInput(condition->InputAt(0), 0);
1034 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001035 RecordSimplification();
1036 }
1037}
1038
Mingyao Yang0304e182015-01-30 16:41:29 -08001039void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1040 HInstruction* input = instruction->InputAt(0);
1041 // If the array is a NewArray with constant size, replace the array length
1042 // with the constant instruction. This helps the bounds check elimination phase.
1043 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001044 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001045 if (input->IsIntConstant()) {
1046 instruction->ReplaceWith(input);
1047 }
1048 }
1049}
1050
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001051void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001052 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001053 if (value->GetType() != DataType::Type::kReference) {
1054 return;
1055 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001056
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001057 if (CanEnsureNotNullAt(value, instruction)) {
1058 instruction->ClearValueCanBeNull();
1059 }
1060
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001061 if (value->IsArrayGet()) {
1062 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1063 // If the code is just swapping elements in the array, no need for a type check.
1064 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001065 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001066 }
1067 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001068
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001069 if (value->IsNullConstant()) {
1070 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001071 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001072 }
1073
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001074 ScopedObjectAccess soa(Thread::Current());
1075 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1076 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1077 if (!array_rti.IsValid()) {
1078 return;
1079 }
1080
1081 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1082 instruction->ClearNeedsTypeCheck();
1083 return;
1084 }
1085
1086 if (array_rti.IsObjectArray()) {
1087 if (array_rti.IsExact()) {
1088 instruction->ClearNeedsTypeCheck();
1089 return;
1090 }
1091 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001092 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001093}
1094
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001095static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001096 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1097 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1098 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001099 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001100 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001101 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1102 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001103 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001104 return DataType::Size(result_type) > DataType::Size(input_type) &&
1105 result_type != DataType::Type::kUint16 &&
1106 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001107}
1108
Vladimir Marko61b92282017-10-11 13:23:17 +01001109static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1110 if (maybe_get->IsInstanceFieldGet()) {
1111 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1112 return true;
1113 } else if (maybe_get->IsStaticFieldGet()) {
1114 maybe_get->AsStaticFieldGet()->SetType(new_type);
1115 return true;
1116 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1117 maybe_get->AsArrayGet()->SetType(new_type);
1118 return true;
1119 } else {
1120 return false;
1121 }
1122}
1123
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001124// The type conversion is only used for storing into a field/element of the
1125// same/narrower size.
1126static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1127 if (type_conversion->HasEnvironmentUses()) {
1128 return false;
1129 }
1130 DataType::Type input_type = type_conversion->GetInputType();
1131 DataType::Type result_type = type_conversion->GetResultType();
1132 if (!DataType::IsIntegralType(input_type) ||
1133 !DataType::IsIntegralType(result_type) ||
1134 input_type == DataType::Type::kInt64 ||
1135 result_type == DataType::Type::kInt64) {
1136 // Type conversion is needed if non-integer types are involved, or 64-bit
1137 // types are involved, which may use different number of registers.
1138 return false;
1139 }
1140 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1141 // Type conversion is not necessary when storing to a field/element of the
1142 // same/smaller size.
1143 } else {
1144 // We do not handle this case here.
1145 return false;
1146 }
1147
1148 // Check if the converted value is only used for storing into heap.
1149 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1150 HInstruction* instruction = use.GetUser();
1151 if (instruction->IsInstanceFieldSet() &&
1152 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1153 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1154 continue;
1155 }
1156 if (instruction->IsStaticFieldSet() &&
1157 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1158 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1159 continue;
1160 }
1161 if (instruction->IsArraySet() &&
1162 instruction->AsArraySet()->GetComponentType() == result_type &&
1163 // not index use.
1164 instruction->AsArraySet()->GetIndex() != type_conversion) {
1165 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1166 continue;
1167 }
1168 // The use is not as a store value, or the field/element type is not the
1169 // same as the result_type, keep the type conversion.
1170 return false;
1171 }
1172 // Codegen automatically handles the type conversion during the store.
1173 return true;
1174}
1175
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001176void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001177 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001178 DataType::Type input_type = input->GetType();
1179 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001180 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001181 // Remove the implicit conversion; this includes conversion to the same type.
1182 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001183 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001184 RecordSimplification();
1185 return;
1186 }
1187
1188 if (input->IsTypeConversion()) {
1189 HTypeConversion* input_conversion = input->AsTypeConversion();
1190 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001191 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001192
1193 // When the first conversion is lossless, a direct conversion from the original type
1194 // to the final type yields the same result, even for a lossy second conversion, for
1195 // example float->double->int or int->double->float.
1196 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1197
1198 // For integral conversions, see if the first conversion loses only bits that the second
1199 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1200 // conversion yields the same result, for example long->int->short or int->char->short.
1201 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001202 DataType::IsIntegralType(input_type) &&
1203 DataType::IsIntegralType(original_type) &&
1204 DataType::IsIntegralType(result_type) &&
1205 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001206
1207 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1208 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001209 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001210 instruction->ReplaceWith(original_input);
1211 instruction->GetBlock()->RemoveInstruction(instruction);
1212 if (!input_conversion->HasUses()) {
1213 // Don't wait for DCE.
1214 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1215 }
1216 RecordSimplification();
1217 return;
1218 }
1219 // Otherwise simplify only if the first conversion has no other use.
1220 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1221 input_conversion->ReplaceWith(original_input);
1222 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1223 RecordSimplification();
1224 return;
1225 }
1226 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001227 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1228 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001229 HAnd* input_and = input->AsAnd();
1230 HConstant* constant = input_and->GetConstantRight();
1231 if (constant != nullptr) {
1232 int64_t value = Int64FromConstant(constant);
1233 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1234 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001235 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001236 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001237 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001238 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001239 instruction->ReplaceWith(original_input);
1240 instruction->GetBlock()->RemoveInstruction(instruction);
1241 RecordSimplification();
1242 return;
1243 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1244 input_and->ReplaceWith(original_input);
1245 input_and->GetBlock()->RemoveInstruction(input_and);
1246 RecordSimplification();
1247 return;
1248 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001249 }
1250 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001251 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1252 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1253 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1254 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1255 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1256 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1257 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1258 instruction->ReplaceWith(input);
1259 instruction->GetBlock()->RemoveInstruction(instruction);
1260 RecordSimplification();
1261 return;
1262 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001263 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001264
1265 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1266 instruction->ReplaceWith(input);
1267 instruction->GetBlock()->RemoveInstruction(instruction);
1268 RecordSimplification();
1269 return;
1270 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001271}
1272
Aart Bikc6eec4b2018-03-29 17:22:00 -07001273void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1274 HInstruction* input = instruction->GetInput();
1275 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1276 // Zero extension from narrow to wide can never set sign bit in the wider
1277 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1278 instruction->ReplaceWith(input);
1279 instruction->GetBlock()->RemoveInstruction(instruction);
1280 RecordSimplification();
1281 }
1282}
1283
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001284void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1285 HConstant* input_cst = instruction->GetConstantRight();
1286 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001287 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001288 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001289 // Replace code looking like
1290 // ADD dst, src, 0
1291 // with
1292 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001293 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1294 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1295 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001296 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001297 instruction->ReplaceWith(input_other);
1298 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001299 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001300 return;
1301 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001302 }
1303
1304 HInstruction* left = instruction->GetLeft();
1305 HInstruction* right = instruction->GetRight();
1306 bool left_is_neg = left->IsNeg();
1307 bool right_is_neg = right->IsNeg();
1308
1309 if (left_is_neg && right_is_neg) {
1310 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1311 return;
1312 }
1313 }
1314
1315 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1316 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1317 // Replace code looking like
1318 // NEG tmp, b
1319 // ADD dst, a, tmp
1320 // with
1321 // SUB dst, a, b
1322 // We do not perform the optimization if the input negation has environment
1323 // uses or multiple non-environment uses as it could lead to worse code. In
1324 // particular, we do not want the live range of `b` to be extended if we are
1325 // not sure the initial 'NEG' instruction can be removed.
1326 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001327 HSub* sub =
1328 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001329 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1330 RecordSimplification();
1331 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001332 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001333 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001334
Anton Kirilove14dc862016-05-13 17:56:15 +01001335 if (TryReplaceWithRotate(instruction)) {
1336 return;
1337 }
1338
1339 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1340 // so no need to return.
1341 TryHandleAssociativeAndCommutativeOperation(instruction);
1342
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001343 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001344 TrySubtractionChainSimplification(instruction)) {
1345 return;
1346 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001347
1348 if (integral_type) {
1349 // Replace code patterns looking like
1350 // SUB dst1, x, y SUB dst1, x, y
1351 // ADD dst2, dst1, y ADD dst2, y, dst1
1352 // with
1353 // SUB dst1, x, y
1354 // ADD instruction is not needed in this case, we may use
1355 // one of inputs of SUB instead.
1356 if (left->IsSub() && left->InputAt(1) == right) {
1357 instruction->ReplaceWith(left->InputAt(0));
1358 RecordSimplification();
1359 instruction->GetBlock()->RemoveInstruction(instruction);
1360 return;
1361 } else if (right->IsSub() && right->InputAt(1) == left) {
1362 instruction->ReplaceWith(right->InputAt(0));
1363 RecordSimplification();
1364 instruction->GetBlock()->RemoveInstruction(instruction);
1365 return;
1366 }
1367 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001368}
1369
1370void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001371 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001372 HConstant* input_cst = instruction->GetConstantRight();
1373 HInstruction* input_other = instruction->GetLeastConstantLeft();
1374
Vladimir Marko452c1b62015-09-25 14:44:17 +01001375 if (input_cst != nullptr) {
1376 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001377 if (value == -1 ||
1378 // Similar cases under zero extension.
1379 (DataType::IsUnsignedType(input_other->GetType()) &&
1380 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001381 // Replace code looking like
1382 // AND dst, src, 0xFFF...FF
1383 // with
1384 // src
1385 instruction->ReplaceWith(input_other);
1386 instruction->GetBlock()->RemoveInstruction(instruction);
1387 RecordSimplification();
1388 return;
1389 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001390 if (input_other->IsTypeConversion() &&
1391 input_other->GetType() == DataType::Type::kInt64 &&
1392 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1393 IsInt<32>(value) &&
1394 input_other->HasOnlyOneNonEnvironmentUse()) {
1395 // The AND can be reordered before the TypeConversion. Replace
1396 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1397 // TypeConversion<Int64> tmp, src
1398 // AND dst, tmp, cst
1399 // with
1400 // IntConstant cst, <32-bit-constant>
1401 // AND tmp, src, cst
1402 // TypeConversion<Int64> dst, tmp
1403 // This helps 32-bit targets and does not hurt 64-bit targets.
1404 // This also simplifies detection of other patterns, such as Uint8 loads.
1405 HInstruction* new_and_input = input_other->InputAt(0);
1406 // Implicit conversion Int64->Int64 would have been removed previously.
1407 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1408 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1409 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001410 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001411 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1412 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001413 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001414 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1415 input_other->GetBlock()->RemoveInstruction(input_other);
1416 RecordSimplification();
1417 // Try to process the new And now, do not wait for the next round of simplifications.
1418 instruction = new_and;
1419 input_other = new_and_input;
1420 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001421 // Eliminate And from UShr+And if the And-mask contains all the bits that
1422 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1423 // precisely clears the shifted-in sign bits.
1424 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001425 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001426 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1427 size_t num_tail_bits_set = CTZ(value + 1);
1428 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1429 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1430 instruction->ReplaceWith(input_other);
1431 instruction->GetBlock()->RemoveInstruction(instruction);
1432 RecordSimplification();
1433 return;
1434 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1435 input_other->HasOnlyOneNonEnvironmentUse()) {
1436 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1437 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001438 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001439 input_other->InputAt(0),
1440 input_other->InputAt(1),
1441 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001442 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1443 input_other->GetBlock()->RemoveInstruction(input_other);
1444 RecordSimplification();
1445 return;
1446 }
1447 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001448 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1449 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1450 // or array Get with only a single use, short-circuit the subsequent simplification
1451 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1452 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1453 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1454 if (input_other->GetType() == find_type &&
1455 input_other->HasOnlyOneNonEnvironmentUse() &&
1456 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1457 instruction->ReplaceWith(input_other);
1458 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001459 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1460 instruction->ReplaceWith(input_other);
1461 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001462 } else {
1463 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1464 new_type, input_other, instruction->GetDexPc());
1465 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1466 }
1467 RecordSimplification();
1468 return;
1469 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001470 }
1471
1472 // We assume that GVN has run before, so we only perform a pointer comparison.
1473 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001474 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001475 if (instruction->GetLeft() == instruction->GetRight()) {
1476 // Replace code looking like
1477 // AND dst, src, src
1478 // with
1479 // src
1480 instruction->ReplaceWith(instruction->GetLeft());
1481 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001482 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001483 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001484 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001485
Anton Kirilove14dc862016-05-13 17:56:15 +01001486 if (TryDeMorganNegationFactoring(instruction)) {
1487 return;
1488 }
1489
1490 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1491 // so no need to return.
1492 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001493}
1494
Mark Mendellc4701932015-04-10 13:18:51 -04001495void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1496 VisitCondition(condition);
1497}
1498
1499void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1500 VisitCondition(condition);
1501}
1502
1503void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1504 VisitCondition(condition);
1505}
1506
1507void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1508 VisitCondition(condition);
1509}
1510
Anton Shaminbdd79352016-02-15 12:48:36 +06001511void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1512 VisitCondition(condition);
1513}
1514
1515void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1516 VisitCondition(condition);
1517}
1518
1519void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1520 VisitCondition(condition);
1521}
1522
1523void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1524 VisitCondition(condition);
1525}
Aart Bike9f37602015-10-09 11:15:55 -07001526
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001527// Recognize the following pattern:
1528// obj.getClass() ==/!= Foo.class
1529// And replace it with a constant value if the type of `obj` is statically known.
1530static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1531 HInstruction* input_one = condition->InputAt(0);
1532 HInstruction* input_two = condition->InputAt(1);
1533 HLoadClass* load_class = input_one->IsLoadClass()
1534 ? input_one->AsLoadClass()
1535 : input_two->AsLoadClass();
1536 if (load_class == nullptr) {
1537 return false;
1538 }
1539
1540 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1541 if (!class_rti.IsValid()) {
1542 // Unresolved class.
1543 return false;
1544 }
1545
1546 HInstanceFieldGet* field_get = (load_class == input_one)
1547 ? input_two->AsInstanceFieldGet()
1548 : input_one->AsInstanceFieldGet();
1549 if (field_get == nullptr) {
1550 return false;
1551 }
1552
1553 HInstruction* receiver = field_get->InputAt(0);
1554 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1555 if (!receiver_type.IsExact()) {
1556 return false;
1557 }
1558
1559 {
1560 ScopedObjectAccess soa(Thread::Current());
1561 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1562 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1563 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1564 if (field_get->GetFieldInfo().GetField() != field) {
1565 return false;
1566 }
1567
1568 // We can replace the compare.
1569 int value = 0;
1570 if (receiver_type.IsEqual(class_rti)) {
1571 value = condition->IsEqual() ? 1 : 0;
1572 } else {
1573 value = condition->IsNotEqual() ? 1 : 0;
1574 }
1575 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1576 return true;
1577 }
1578}
1579
Mark Mendellc4701932015-04-10 13:18:51 -04001580void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001581 if (condition->IsEqual() || condition->IsNotEqual()) {
1582 if (RecognizeAndSimplifyClassCheck(condition)) {
1583 return;
1584 }
1585 }
1586
Anton Shaminbdd79352016-02-15 12:48:36 +06001587 // Reverse condition if left is constant. Our code generators prefer constant
1588 // on the right hand side.
1589 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1590 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001591 HCondition* replacement =
1592 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001593 // If it is a fp we must set the opposite bias.
1594 if (replacement != nullptr) {
1595 if (condition->IsLtBias()) {
1596 replacement->SetBias(ComparisonBias::kGtBias);
1597 } else if (condition->IsGtBias()) {
1598 replacement->SetBias(ComparisonBias::kLtBias);
1599 }
1600 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1601 RecordSimplification();
1602
1603 condition = replacement;
1604 }
1605 }
Mark Mendellc4701932015-04-10 13:18:51 -04001606
Mark Mendellc4701932015-04-10 13:18:51 -04001607 HInstruction* left = condition->GetLeft();
1608 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001609
1610 // Try to fold an HCompare into this HCondition.
1611
Mark Mendellc4701932015-04-10 13:18:51 -04001612 // We can only replace an HCondition which compares a Compare to 0.
1613 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1614 // condition with a long, float or double comparison as input.
1615 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1616 // Conversion is not possible.
1617 return;
1618 }
1619
1620 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001621 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001622 // Someone else also wants the result of the compare.
1623 return;
1624 }
1625
Vladimir Marko46817b82016-03-29 12:21:58 +01001626 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001627 // There is a reference to the compare result in an environment. Do we really need it?
1628 if (GetGraph()->IsDebuggable()) {
1629 return;
1630 }
1631
1632 // We have to ensure that there are no deopt points in the sequence.
1633 if (left->HasAnyEnvironmentUseBefore(condition)) {
1634 return;
1635 }
1636 }
1637
1638 // Clean up any environment uses from the HCompare, if any.
1639 left->RemoveEnvironmentUsers();
1640
1641 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1642 condition->SetBias(left->AsCompare()->GetBias());
1643
1644 // Replace the operands of the HCondition.
1645 condition->ReplaceInput(left->InputAt(0), 0);
1646 condition->ReplaceInput(left->InputAt(1), 1);
1647
1648 // Remove the HCompare.
1649 left->GetBlock()->RemoveInstruction(left);
1650
1651 RecordSimplification();
1652}
1653
Andreas Gampe9186ced2016-12-12 14:28:21 -08001654// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1655static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1656 // True, if the most significant bits of divisor are 0.
1657 return ((divisor & 0x7fffff) == 0);
1658}
1659
1660// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1661static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1662 // True, if the most significant bits of divisor are 0.
1663 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1664}
1665
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001666void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1667 HConstant* input_cst = instruction->GetConstantRight();
1668 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001669 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001670
1671 if ((input_cst != nullptr) && input_cst->IsOne()) {
1672 // Replace code looking like
1673 // DIV dst, src, 1
1674 // with
1675 // src
1676 instruction->ReplaceWith(input_other);
1677 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001678 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001679 return;
1680 }
1681
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001682 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001683 // Replace code looking like
1684 // DIV dst, src, -1
1685 // with
1686 // NEG dst, src
1687 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001688 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001689 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001690 return;
1691 }
1692
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001693 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001694 // Try replacing code looking like
1695 // DIV dst, src, constant
1696 // with
1697 // MUL dst, src, 1 / constant
1698 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001699 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001700 double value = input_cst->AsDoubleConstant()->GetValue();
1701 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1702 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1703 }
1704 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001705 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001706 float value = input_cst->AsFloatConstant()->GetValue();
1707 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1708 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1709 }
1710 }
1711
1712 if (reciprocal != nullptr) {
1713 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001714 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001715 RecordSimplification();
1716 return;
1717 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001718 }
1719}
1720
1721void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1722 HConstant* input_cst = instruction->GetConstantRight();
1723 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001724 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001725 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001726 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001727
1728 if (input_cst == nullptr) {
1729 return;
1730 }
1731
1732 if (input_cst->IsOne()) {
1733 // Replace code looking like
1734 // MUL dst, src, 1
1735 // with
1736 // src
1737 instruction->ReplaceWith(input_other);
1738 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001739 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001740 return;
1741 }
1742
1743 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001744 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001745 // Replace code looking like
1746 // MUL dst, src, -1
1747 // with
1748 // NEG dst, src
1749 HNeg* neg = new (allocator) HNeg(type, input_other);
1750 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001751 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001752 return;
1753 }
1754
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001755 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001756 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1757 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1758 // Replace code looking like
1759 // FP_MUL dst, src, 2.0
1760 // with
1761 // FP_ADD dst, src, src
1762 // The 'int' and 'long' cases are handled below.
1763 block->ReplaceAndRemoveInstructionWith(instruction,
1764 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001765 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001766 return;
1767 }
1768
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001769 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001770 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001771 // Even though constant propagation also takes care of the zero case, other
1772 // optimizations can lead to having a zero multiplication.
1773 if (factor == 0) {
1774 // Replace code looking like
1775 // MUL dst, src, 0
1776 // with
1777 // 0
1778 instruction->ReplaceWith(input_cst);
1779 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001780 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001781 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001782 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001783 // Replace code looking like
1784 // MUL dst, src, pow_of_2
1785 // with
1786 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001787 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001788 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001789 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001790 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001791 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001792 } else if (IsPowerOfTwo(factor - 1)) {
1793 // Transform code looking like
1794 // MUL dst, src, (2^n + 1)
1795 // into
1796 // SHL tmp, src, n
1797 // ADD dst, src, tmp
1798 HShl* shl = new (allocator) HShl(type,
1799 input_other,
1800 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1801 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1802
1803 block->InsertInstructionBefore(shl, instruction);
1804 block->ReplaceAndRemoveInstructionWith(instruction, add);
1805 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001806 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001807 } else if (IsPowerOfTwo(factor + 1)) {
1808 // Transform code looking like
1809 // MUL dst, src, (2^n - 1)
1810 // into
1811 // SHL tmp, src, n
1812 // SUB dst, tmp, src
1813 HShl* shl = new (allocator) HShl(type,
1814 input_other,
1815 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1816 HSub* sub = new (allocator) HSub(type, shl, input_other);
1817
1818 block->InsertInstructionBefore(shl, instruction);
1819 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1820 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001821 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001822 }
1823 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001824
1825 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1826 // so no need to return.
1827 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001828}
1829
Alexandre Rames188d4312015-04-09 18:30:21 +01001830void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1831 HInstruction* input = instruction->GetInput();
1832 if (input->IsNeg()) {
1833 // Replace code looking like
1834 // NEG tmp, src
1835 // NEG dst, tmp
1836 // with
1837 // src
1838 HNeg* previous_neg = input->AsNeg();
1839 instruction->ReplaceWith(previous_neg->GetInput());
1840 instruction->GetBlock()->RemoveInstruction(instruction);
1841 // We perform the optimization even if the input negation has environment
1842 // uses since it allows removing the current instruction. But we only delete
1843 // the input negation only if it is does not have any uses left.
1844 if (!previous_neg->HasUses()) {
1845 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1846 }
1847 RecordSimplification();
1848 return;
1849 }
1850
Serguei Katkov339dfc22015-04-20 12:29:32 +06001851 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001852 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001853 // Replace code looking like
1854 // SUB tmp, a, b
1855 // NEG dst, tmp
1856 // with
1857 // SUB dst, b, a
1858 // We do not perform the optimization if the input subtraction has
1859 // environment uses or multiple non-environment uses as it could lead to
1860 // worse code. In particular, we do not want the live ranges of `a` and `b`
1861 // to be extended if we are not sure the initial 'SUB' instruction can be
1862 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001863 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001864 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001865 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1866 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001867 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1868 if (!sub->HasUses()) {
1869 sub->GetBlock()->RemoveInstruction(sub);
1870 }
1871 RecordSimplification();
1872 }
1873}
1874
1875void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1876 HInstruction* input = instruction->GetInput();
1877 if (input->IsNot()) {
1878 // Replace code looking like
1879 // NOT tmp, src
1880 // NOT dst, tmp
1881 // with
1882 // src
1883 // We perform the optimization even if the input negation has environment
1884 // uses since it allows removing the current instruction. But we only delete
1885 // the input negation only if it is does not have any uses left.
1886 HNot* previous_not = input->AsNot();
1887 instruction->ReplaceWith(previous_not->GetInput());
1888 instruction->GetBlock()->RemoveInstruction(instruction);
1889 if (!previous_not->HasUses()) {
1890 previous_not->GetBlock()->RemoveInstruction(previous_not);
1891 }
1892 RecordSimplification();
1893 }
1894}
1895
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001896void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1897 HConstant* input_cst = instruction->GetConstantRight();
1898 HInstruction* input_other = instruction->GetLeastConstantLeft();
1899
Roland Levillain1a653882016-03-18 18:05:57 +00001900 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001901 // Replace code looking like
1902 // OR dst, src, 0
1903 // with
1904 // src
1905 instruction->ReplaceWith(input_other);
1906 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001907 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001908 return;
1909 }
1910
1911 // We assume that GVN has run before, so we only perform a pointer comparison.
1912 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001913 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001914 if (instruction->GetLeft() == instruction->GetRight()) {
1915 // Replace code looking like
1916 // OR dst, src, src
1917 // with
1918 // src
1919 instruction->ReplaceWith(instruction->GetLeft());
1920 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001921 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001922 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001923 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001924
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001925 if (TryDeMorganNegationFactoring(instruction)) return;
1926
Anton Kirilove14dc862016-05-13 17:56:15 +01001927 if (TryReplaceWithRotate(instruction)) {
1928 return;
1929 }
1930
1931 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1932 // so no need to return.
1933 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001934}
1935
1936void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1937 VisitShift(instruction);
1938}
1939
1940void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1941 VisitShift(instruction);
1942}
1943
1944void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1945 HConstant* input_cst = instruction->GetConstantRight();
1946 HInstruction* input_other = instruction->GetLeastConstantLeft();
1947
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001948 DataType::Type type = instruction->GetType();
1949 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001950 return;
1951 }
1952
Roland Levillain1a653882016-03-18 18:05:57 +00001953 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001954 // Replace code looking like
1955 // SUB dst, src, 0
1956 // with
1957 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001958 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1959 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1960 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001961 instruction->ReplaceWith(input_other);
1962 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001963 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001964 return;
1965 }
1966
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001967 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001968 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001969
Alexandre Rames188d4312015-04-09 18:30:21 +01001970 HInstruction* left = instruction->GetLeft();
1971 HInstruction* right = instruction->GetRight();
1972 if (left->IsConstant()) {
1973 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001974 // Replace code looking like
1975 // SUB dst, 0, src
1976 // with
1977 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001978 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001979 // `x` is `0.0`, the former expression yields `0.0`, while the later
1980 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001981 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001982 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001983 RecordSimplification();
1984 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001985 }
1986 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001987
1988 if (left->IsNeg() && right->IsNeg()) {
1989 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1990 return;
1991 }
1992 }
1993
1994 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1995 // Replace code looking like
1996 // NEG tmp, b
1997 // SUB dst, a, tmp
1998 // with
1999 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01002000 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002001 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2002 RecordSimplification();
2003 right->GetBlock()->RemoveInstruction(right);
2004 return;
2005 }
2006
2007 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2008 // Replace code looking like
2009 // NEG tmp, a
2010 // SUB dst, tmp, b
2011 // with
2012 // ADD tmp, a, b
2013 // NEG dst, tmp
2014 // The second version is not intrinsically better, but enables more
2015 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002016 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002017 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002018 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002019 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2020 instruction->ReplaceWith(neg);
2021 instruction->GetBlock()->RemoveInstruction(instruction);
2022 RecordSimplification();
2023 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002024 return;
2025 }
2026
2027 if (TrySubtractionChainSimplification(instruction)) {
2028 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002029 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002030
2031 if (left->IsAdd()) {
2032 // Replace code patterns looking like
2033 // ADD dst1, x, y ADD dst1, x, y
2034 // SUB dst2, dst1, y SUB dst2, dst1, x
2035 // with
2036 // ADD dst1, x, y
2037 // SUB instruction is not needed in this case, we may use
2038 // one of inputs of ADD instead.
2039 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002040 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002041 if (left->InputAt(1) == right) {
2042 instruction->ReplaceWith(left->InputAt(0));
2043 RecordSimplification();
2044 instruction->GetBlock()->RemoveInstruction(instruction);
2045 return;
2046 } else if (left->InputAt(0) == right) {
2047 instruction->ReplaceWith(left->InputAt(1));
2048 RecordSimplification();
2049 instruction->GetBlock()->RemoveInstruction(instruction);
2050 return;
2051 }
2052 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002053}
2054
2055void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2056 VisitShift(instruction);
2057}
2058
2059void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2060 HConstant* input_cst = instruction->GetConstantRight();
2061 HInstruction* input_other = instruction->GetLeastConstantLeft();
2062
Roland Levillain1a653882016-03-18 18:05:57 +00002063 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002064 // Replace code looking like
2065 // XOR dst, src, 0
2066 // with
2067 // src
2068 instruction->ReplaceWith(input_other);
2069 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002070 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002071 return;
2072 }
2073
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002074 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002075 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002076 // Replace code looking like
2077 // XOR dst, src, 1
2078 // with
2079 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002080 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002081 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2082 RecordSimplification();
2083 return;
2084 }
2085
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002086 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2087 // Replace code looking like
2088 // XOR dst, src, 0xFFF...FF
2089 // with
2090 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002091 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002092 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002093 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002094 return;
2095 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002096
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002097 HInstruction* left = instruction->GetLeft();
2098 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002099 if (((left->IsNot() && right->IsNot()) ||
2100 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002101 left->HasOnlyOneNonEnvironmentUse() &&
2102 right->HasOnlyOneNonEnvironmentUse()) {
2103 // Replace code looking like
2104 // NOT nota, a
2105 // NOT notb, b
2106 // XOR dst, nota, notb
2107 // with
2108 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002109 instruction->ReplaceInput(left->InputAt(0), 0);
2110 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002111 left->GetBlock()->RemoveInstruction(left);
2112 right->GetBlock()->RemoveInstruction(right);
2113 RecordSimplification();
2114 return;
2115 }
2116
Anton Kirilove14dc862016-05-13 17:56:15 +01002117 if (TryReplaceWithRotate(instruction)) {
2118 return;
2119 }
2120
2121 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2122 // so no need to return.
2123 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002124}
2125
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002126void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2127 HInstruction* argument = instruction->InputAt(1);
2128 HInstruction* receiver = instruction->InputAt(0);
2129 if (receiver == argument) {
2130 // Because String.equals is an instance call, the receiver is
2131 // a null check if we don't know it's null. The argument however, will
2132 // be the actual object. So we cannot end up in a situation where both
2133 // are equal but could be null.
2134 DCHECK(CanEnsureNotNullAt(argument, instruction));
2135 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2136 instruction->GetBlock()->RemoveInstruction(instruction);
2137 } else {
2138 StringEqualsOptimizations optimizations(instruction);
2139 if (CanEnsureNotNullAt(argument, instruction)) {
2140 optimizations.SetArgumentNotNull();
2141 }
2142 ScopedObjectAccess soa(Thread::Current());
2143 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2144 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2145 optimizations.SetArgumentIsString();
Vladimir Markoda283052017-11-07 21:17:24 +00002146 } else if (kUseReadBarrier) {
2147 DCHECK(instruction->GetResolvedMethod() != nullptr);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08002148 DCHECK(instruction->GetResolvedMethod()->GetDeclaringClass()->IsStringClass() ||
2149 // Object.equals() can be devirtualized to String.equals().
2150 instruction->GetResolvedMethod()->GetDeclaringClass()->IsObjectClass());
Vladimir Markoda283052017-11-07 21:17:24 +00002151 Runtime* runtime = Runtime::Current();
2152 // For AOT, we always assume that the boot image shall contain the String.class and
2153 // we do not need a read barrier for boot image classes as they are non-moveable.
2154 // For JIT, check if we actually have a boot image; if we do, the String.class
2155 // should also be non-moveable.
2156 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2157 DCHECK(runtime->IsAotCompiler() ||
2158 !runtime->GetHeap()->IsMovableObject(
2159 instruction->GetResolvedMethod()->GetDeclaringClass()));
2160 optimizations.SetNoReadBarrierForStringClass();
2161 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002162 }
2163 }
2164}
2165
Roland Levillain22c49222016-03-18 14:04:28 +00002166void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2167 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002168 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002169 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002170 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002171 HInstruction* value = invoke->InputAt(0);
2172 HInstruction* distance = invoke->InputAt(1);
2173 // Replace the invoke with an HRor.
2174 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002175 // Unconditionally set the type of the negated distance to `int`,
2176 // as shift and rotate operations expect a 32-bit (or narrower)
2177 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002178 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002179 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2180 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002181 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002182 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2183 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002184 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002185 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2186 clinit->GetBlock()->RemoveInstruction(clinit);
2187 HInstruction* ldclass = clinit->InputAt(0);
2188 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2189 ldclass->GetBlock()->RemoveInstruction(ldclass);
2190 }
2191 }
2192}
2193
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002194static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2195 if (potential_length->IsArrayLength()) {
2196 return potential_length->InputAt(0) == potential_array;
2197 }
2198
2199 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002200 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002201 }
2202
2203 return false;
2204}
2205
2206void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2207 HInstruction* source = instruction->InputAt(0);
2208 HInstruction* destination = instruction->InputAt(2);
2209 HInstruction* count = instruction->InputAt(4);
2210 SystemArrayCopyOptimizations optimizations(instruction);
2211 if (CanEnsureNotNullAt(source, instruction)) {
2212 optimizations.SetSourceIsNotNull();
2213 }
2214 if (CanEnsureNotNullAt(destination, instruction)) {
2215 optimizations.SetDestinationIsNotNull();
2216 }
2217 if (destination == source) {
2218 optimizations.SetDestinationIsSource();
2219 }
2220
2221 if (IsArrayLengthOf(count, source)) {
2222 optimizations.SetCountIsSourceLength();
2223 }
2224
2225 if (IsArrayLengthOf(count, destination)) {
2226 optimizations.SetCountIsDestinationLength();
2227 }
2228
2229 {
2230 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002231 DataType::Type source_component_type = DataType::Type::kVoid;
2232 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002233 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2234 if (destination_rti.IsValid()) {
2235 if (destination_rti.IsObjectArray()) {
2236 if (destination_rti.IsExact()) {
2237 optimizations.SetDoesNotNeedTypeCheck();
2238 }
2239 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002240 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002241 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002242 destination_component_type = DataTypeFromPrimitive(
2243 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002244 optimizations.SetDestinationIsPrimitiveArray();
2245 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2246 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002247 }
2248 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002249 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2250 if (source_rti.IsValid()) {
2251 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2252 optimizations.SetDoesNotNeedTypeCheck();
2253 }
2254 if (source_rti.IsPrimitiveArrayClass()) {
2255 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002256 source_component_type = DataTypeFromPrimitive(
2257 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002258 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2259 optimizations.SetSourceIsNonPrimitiveArray();
2260 }
2261 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002262 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002263 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002264 (source_component_type == destination_component_type)) {
2265 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2266 PointerSize image_size = class_linker->GetImagePointerSize();
2267 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2268 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2269 ArtMethod* method = nullptr;
2270 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002271 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002272 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002273 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002274 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002275 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002276 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002277 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002278 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002279 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002280 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002281 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002282 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002283 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002284 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002285 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002286 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002287 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002288 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002289 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002290 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002291 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002292 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002293 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002294 break;
2295 default:
2296 LOG(FATAL) << "Unreachable";
2297 }
2298 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002299 DCHECK(method->IsStatic());
2300 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002301 invoke->SetResolvedMethod(method);
2302 // Sharpen the new invoke. Note that we do not update the dex method index of
2303 // the invoke, as we would need to look it up in the current dex file, and it
2304 // is unlikely that it exists. The most usual situation for such typed
2305 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002306 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002307 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002308 }
2309}
2310
Roland Levillaina5c4a402016-03-15 15:02:50 +00002311void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2312 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002313 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002314 DCHECK(invoke->IsInvokeStaticOrDirect());
2315 uint32_t dex_pc = invoke->GetDexPc();
2316 HInstruction* left = invoke->InputAt(0);
2317 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002318 if (!is_signum) {
2319 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002320 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002321 right = GetGraph()->GetLongConstant(0);
2322 } else {
2323 right = GetGraph()->GetIntConstant(0);
2324 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002325 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002326 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2327 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2328}
2329
Aart Bik75a38b22016-02-17 10:41:50 -08002330void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2331 DCHECK(invoke->IsInvokeStaticOrDirect());
2332 uint32_t dex_pc = invoke->GetDexPc();
2333 // IsNaN(x) is the same as x != x.
2334 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002335 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002336 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002337 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2338}
2339
Aart Bik2a6aad92016-02-25 11:32:32 -08002340void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2341 DCHECK(invoke->IsInvokeStaticOrDirect());
2342 uint32_t dex_pc = invoke->GetDexPc();
2343 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002344 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002345 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2346 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002347 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002348 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2349 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2350 kNeedsEnvironmentOrCache,
2351 kNoSideEffects,
2352 kNoThrow);
2353 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002354 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002355 nan = GetGraph()->GetIntConstant(0x7fc00000);
2356 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2357 kNeedsEnvironmentOrCache,
2358 kNoSideEffects,
2359 kNoThrow);
2360 }
2361 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002362 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002363 condition->SetBias(ComparisonBias::kLtBias);
2364 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2365 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002366 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002367 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2368 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2369}
2370
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002371void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2372 HInstruction* str = invoke->InputAt(0);
2373 HInstruction* index = invoke->InputAt(1);
2374 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002375 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002376 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2377 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002378 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002379 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002380 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Vladimir Marko0259c242017-12-04 11:27:47 +00002381 index, length, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002382 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002383 HArrayGet* array_get = new (allocator) HArrayGet(str,
2384 bounds_check,
2385 DataType::Type::kUint16,
2386 SideEffects::None(), // Strings are immutable.
2387 dex_pc,
2388 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002389 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2390 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2391 GetGraph()->SetHasBoundsChecks(true);
2392}
2393
Vladimir Markodce016e2016-04-28 13:10:02 +01002394void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2395 HInstruction* str = invoke->InputAt(0);
2396 uint32_t dex_pc = invoke->GetDexPc();
2397 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2398 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002399 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002400 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002401 HInstruction* replacement;
2402 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2403 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2404 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2405 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002406 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002407 replacement = equal;
2408 } else {
2409 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2410 replacement = length;
2411 }
2412 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2413}
2414
Aart Bikff7d89c2016-11-07 08:49:28 -08002415// This method should only be used on intrinsics whose sole way of throwing an
2416// exception is raising a NPE when the nth argument is null. If that argument
2417// is provably non-null, we can clear the flag.
2418void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2419 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002420 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002421 invoke->SetCanThrow(false);
2422 }
2423}
2424
Aart Bik71bf7b42016-11-16 10:17:46 -08002425// Methods that return "this" can replace the returned value with the receiver.
2426void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2427 if (invoke->HasUses()) {
2428 HInstruction* receiver = invoke->InputAt(0);
2429 invoke->ReplaceWith(receiver);
2430 RecordSimplification();
2431 }
2432}
2433
2434// Helper method for StringBuffer escape analysis.
2435static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2436 if (user->IsInvokeStaticOrDirect()) {
2437 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002438 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2439 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002440 user->InputAt(0) == reference;
2441 } else if (user->IsInvokeVirtual()) {
2442 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2443 case Intrinsics::kStringBufferLength:
2444 case Intrinsics::kStringBufferToString:
2445 DCHECK_EQ(user->InputAt(0), reference);
2446 return true;
2447 case Intrinsics::kStringBufferAppend:
2448 // Returns "this", so only okay if no further uses.
2449 DCHECK_EQ(user->InputAt(0), reference);
2450 DCHECK_NE(user->InputAt(1), reference);
2451 return !user->HasUses();
2452 default:
2453 break;
2454 }
2455 }
2456 return false;
2457}
2458
2459// Certain allocation intrinsics are not removed by dead code elimination
2460// because of potentially throwing an OOM exception or other side effects.
2461// This method removes such intrinsics when special circumstances allow.
2462void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2463 if (!invoke->HasUses()) {
2464 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2465 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2466 // call does not escape since only thread-local synchronization may be removed.
2467 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2468 HInstruction* receiver = invoke->InputAt(0);
2469 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2470 invoke->GetBlock()->RemoveInstruction(invoke);
2471 RecordSimplification();
2472 }
2473 }
2474}
2475
Vladimir Markoca6fff82017-10-03 14:49:14 +01002476void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2477 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002478 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002479 HMemoryBarrier* mem_barrier =
2480 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002481 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2482}
2483
Aart Bik1f8d51b2018-02-15 10:42:37 -08002484void InstructionSimplifierVisitor::SimplifyMin(HInvoke* invoke, DataType::Type type) {
2485 DCHECK(invoke->IsInvokeStaticOrDirect());
2486 HMin* min = new (GetGraph()->GetAllocator())
2487 HMin(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2488 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, min);
2489}
2490
2491void InstructionSimplifierVisitor::SimplifyMax(HInvoke* invoke, DataType::Type type) {
2492 DCHECK(invoke->IsInvokeStaticOrDirect());
2493 HMax* max = new (GetGraph()->GetAllocator())
2494 HMax(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2495 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, max);
2496}
2497
Aart Bik3dad3412018-02-28 12:01:46 -08002498void InstructionSimplifierVisitor::SimplifyAbs(HInvoke* invoke, DataType::Type type) {
2499 DCHECK(invoke->IsInvokeStaticOrDirect());
2500 HAbs* abs = new (GetGraph()->GetAllocator())
2501 HAbs(type, invoke->InputAt(0), invoke->GetDexPc());
2502 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, abs);
2503}
2504
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002505void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002506 switch (instruction->GetIntrinsic()) {
2507 case Intrinsics::kStringEquals:
2508 SimplifyStringEquals(instruction);
2509 break;
2510 case Intrinsics::kSystemArrayCopy:
2511 SimplifySystemArrayCopy(instruction);
2512 break;
2513 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002514 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002515 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002516 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002517 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002518 break;
2519 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002520 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002521 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002522 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002523 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002524 break;
2525 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002526 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002527 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002528 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002529 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002530 break;
2531 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002532 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002533 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002534 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002535 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002536 break;
2537 case Intrinsics::kFloatIsNaN:
2538 case Intrinsics::kDoubleIsNaN:
2539 SimplifyIsNaN(instruction);
2540 break;
2541 case Intrinsics::kFloatFloatToIntBits:
2542 case Intrinsics::kDoubleDoubleToLongBits:
2543 SimplifyFP2Int(instruction);
2544 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002545 case Intrinsics::kStringCharAt:
2546 SimplifyStringCharAt(instruction);
2547 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002548 case Intrinsics::kStringIsEmpty:
2549 case Intrinsics::kStringLength:
2550 SimplifyStringIsEmptyOrLength(instruction);
2551 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002552 case Intrinsics::kStringStringIndexOf:
2553 case Intrinsics::kStringStringIndexOfAfter:
2554 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2555 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002556 case Intrinsics::kStringBufferAppend:
2557 case Intrinsics::kStringBuilderAppend:
2558 SimplifyReturnThis(instruction);
2559 break;
2560 case Intrinsics::kStringBufferToString:
2561 case Intrinsics::kStringBuilderToString:
2562 SimplifyAllocationIntrinsic(instruction);
2563 break;
Aart Bik11932592016-03-08 12:42:25 -08002564 case Intrinsics::kUnsafeLoadFence:
2565 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2566 break;
2567 case Intrinsics::kUnsafeStoreFence:
2568 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2569 break;
2570 case Intrinsics::kUnsafeFullFence:
2571 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2572 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002573 case Intrinsics::kVarHandleFullFence:
2574 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2575 break;
2576 case Intrinsics::kVarHandleAcquireFence:
2577 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2578 break;
2579 case Intrinsics::kVarHandleReleaseFence:
2580 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2581 break;
2582 case Intrinsics::kVarHandleLoadLoadFence:
2583 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2584 break;
2585 case Intrinsics::kVarHandleStoreStoreFence:
2586 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2587 break;
Aart Bik1f8d51b2018-02-15 10:42:37 -08002588 case Intrinsics::kMathMinIntInt:
2589 SimplifyMin(instruction, DataType::Type::kInt32);
2590 break;
2591 case Intrinsics::kMathMinLongLong:
2592 SimplifyMin(instruction, DataType::Type::kInt64);
2593 break;
2594 case Intrinsics::kMathMinFloatFloat:
2595 SimplifyMin(instruction, DataType::Type::kFloat32);
2596 break;
2597 case Intrinsics::kMathMinDoubleDouble:
2598 SimplifyMin(instruction, DataType::Type::kFloat64);
2599 break;
2600 case Intrinsics::kMathMaxIntInt:
2601 SimplifyMax(instruction, DataType::Type::kInt32);
2602 break;
2603 case Intrinsics::kMathMaxLongLong:
2604 SimplifyMax(instruction, DataType::Type::kInt64);
2605 break;
2606 case Intrinsics::kMathMaxFloatFloat:
2607 SimplifyMax(instruction, DataType::Type::kFloat32);
2608 break;
2609 case Intrinsics::kMathMaxDoubleDouble:
2610 SimplifyMax(instruction, DataType::Type::kFloat64);
2611 break;
Aart Bik3dad3412018-02-28 12:01:46 -08002612 case Intrinsics::kMathAbsInt:
2613 SimplifyAbs(instruction, DataType::Type::kInt32);
2614 break;
2615 case Intrinsics::kMathAbsLong:
2616 SimplifyAbs(instruction, DataType::Type::kInt64);
2617 break;
2618 case Intrinsics::kMathAbsFloat:
2619 SimplifyAbs(instruction, DataType::Type::kFloat32);
2620 break;
2621 case Intrinsics::kMathAbsDouble:
2622 SimplifyAbs(instruction, DataType::Type::kFloat64);
2623 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002624 default:
2625 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002626 }
2627}
2628
Aart Bikbb245d12015-10-19 11:05:03 -07002629void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2630 HInstruction* cond = deoptimize->InputAt(0);
2631 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002632 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002633 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002634 if (deoptimize->GuardsAnInput()) {
2635 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2636 }
Aart Bikbb245d12015-10-19 11:05:03 -07002637 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2638 } else {
2639 // Always deopt.
2640 }
2641 }
2642}
2643
Anton Kirilove14dc862016-05-13 17:56:15 +01002644// Replace code looking like
2645// OP y, x, const1
2646// OP z, y, const2
2647// with
2648// OP z, x, const3
2649// where OP is both an associative and a commutative operation.
2650bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2651 HBinaryOperation* instruction) {
2652 DCHECK(instruction->IsCommutative());
2653
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002654 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002655 return false;
2656 }
2657
2658 HInstruction* left = instruction->GetLeft();
2659 HInstruction* right = instruction->GetRight();
2660 // Variable names as described above.
2661 HConstant* const2;
2662 HBinaryOperation* y;
2663
2664 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2665 const2 = right->AsConstant();
2666 y = left->AsBinaryOperation();
2667 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2668 const2 = left->AsConstant();
2669 y = right->AsBinaryOperation();
2670 } else {
2671 // The node does not match the pattern.
2672 return false;
2673 }
2674
2675 // If `y` has more than one use, we do not perform the optimization
2676 // because it might increase code size (e.g. if the new constant is
2677 // no longer encodable as an immediate operand in the target ISA).
2678 if (!y->HasOnlyOneNonEnvironmentUse()) {
2679 return false;
2680 }
2681
2682 // GetConstantRight() can return both left and right constants
2683 // for commutative operations.
2684 HConstant* const1 = y->GetConstantRight();
2685 if (const1 == nullptr) {
2686 return false;
2687 }
2688
2689 instruction->ReplaceInput(const1, 0);
2690 instruction->ReplaceInput(const2, 1);
2691 HConstant* const3 = instruction->TryStaticEvaluation();
2692 DCHECK(const3 != nullptr);
2693 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2694 instruction->ReplaceInput(const3, 1);
2695 RecordSimplification();
2696 return true;
2697}
2698
2699static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2700 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2701}
2702
2703// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002704static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002705 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002706 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002707 return HAdd::Compute<int32_t>(x, y);
2708 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002709 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002710 return HAdd::Compute<int64_t>(x, y);
2711 }
2712}
2713
2714// Helper function that handles the child classes of HConstant
2715// and returns an integer with the appropriate sign.
2716static int64_t GetValue(HConstant* constant, bool is_negated) {
2717 int64_t ret = Int64FromConstant(constant);
2718 return is_negated ? -ret : ret;
2719}
2720
2721// Replace code looking like
2722// OP1 y, x, const1
2723// OP2 z, y, const2
2724// with
2725// OP3 z, x, const3
2726// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2727bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2728 HBinaryOperation* instruction) {
2729 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2730
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002731 DataType::Type type = instruction->GetType();
2732 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002733 return false;
2734 }
2735
2736 HInstruction* left = instruction->GetLeft();
2737 HInstruction* right = instruction->GetRight();
2738 // Variable names as described above.
2739 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2740 if (const2 == nullptr) {
2741 return false;
2742 }
2743
2744 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2745 ? left->AsBinaryOperation()
2746 : AsAddOrSub(right);
2747 // If y has more than one use, we do not perform the optimization because
2748 // it might increase code size (e.g. if the new constant is no longer
2749 // encodable as an immediate operand in the target ISA).
2750 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2751 return false;
2752 }
2753
2754 left = y->GetLeft();
2755 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2756 if (const1 == nullptr) {
2757 return false;
2758 }
2759
2760 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2761 // If both inputs are constants, let the constant folding pass deal with it.
2762 if (x->IsConstant()) {
2763 return false;
2764 }
2765
2766 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2767 int64_t const2_val = GetValue(const2, is_const2_negated);
2768 bool is_y_negated = (y == right) && instruction->IsSub();
2769 right = y->GetRight();
2770 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2771 int64_t const1_val = GetValue(const1, is_const1_negated);
2772 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2773 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2774 HBasicBlock* block = instruction->GetBlock();
2775 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002776 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002777 HInstruction* z;
2778
2779 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002780 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002781 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002782 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002783 }
2784
2785 block->ReplaceAndRemoveInstructionWith(instruction, z);
2786 RecordSimplification();
2787 return true;
2788}
2789
Lena Djokicbc5460b2017-07-20 16:07:36 +02002790void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2791 if (TryCombineVecMultiplyAccumulate(instruction)) {
2792 RecordSimplification();
2793 }
2794}
2795
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002796} // namespace art