blob: d532eeeb52b15b8f0416d507425d93a13d06d06d [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 Markob4eb1b12018-05-24 11:09:38 +010021#include "class_root.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010022#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080023#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000025#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070026#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070027#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028
Nicolas Geoffray3c049742014-09-24 18:10:46 +010029namespace art {
30
Artem Serovcced8ba2017-07-19 18:18:09 +010031// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
32// is replaced with its copy if it is clonable.
33static constexpr bool kTestInstructionClonerExhaustively = false;
34
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010035class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000036 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 InstructionSimplifierVisitor(HGraph* graph,
38 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010039 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000040 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010041 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000042 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010043 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010044 stats_(stats) {}
45
Aart Bik24773202018-04-26 10:28:51 -070046 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000047
48 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010049 void RecordSimplification() {
50 simplification_occurred_ = true;
51 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000052 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010053 }
54
Scott Wakeling40a04bf2015-12-11 09:50:36 +000055 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
56 bool TryReplaceWithRotate(HBinaryOperation* instruction);
57 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
59 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
60
Alexandre Rames188d4312015-04-09 18:30:21 +010061 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000062 // `op` should be either HOr or HAnd.
63 // De Morgan's laws:
64 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
65 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010066 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
67 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020068 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010069
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000070 void VisitShift(HBinaryOperation* shift);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000071 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010072 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
73 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010074 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
75 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000076 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000077 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000078 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080079 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000080 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Aart Bikc6eec4b2018-03-29 17:22:00 -070081 void VisitAbs(HAbs* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000082 void VisitAdd(HAdd* instruction) OVERRIDE;
83 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040084 void VisitCondition(HCondition* instruction) OVERRIDE;
85 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
86 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
87 void VisitLessThan(HLessThan* condition) OVERRIDE;
88 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060089 void VisitBelow(HBelow* condition) OVERRIDE;
90 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
91 void VisitAbove(HAbove* condition) OVERRIDE;
92 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000093 void VisitDiv(HDiv* instruction) OVERRIDE;
94 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010095 void VisitNeg(HNeg* instruction) OVERRIDE;
96 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000097 void VisitOr(HOr* instruction) OVERRIDE;
98 void VisitShl(HShl* instruction) OVERRIDE;
99 void VisitShr(HShr* instruction) OVERRIDE;
100 void VisitSub(HSub* instruction) OVERRIDE;
101 void VisitUShr(HUShr* instruction) OVERRIDE;
102 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +0000103 void VisitSelect(HSelect* select) OVERRIDE;
104 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100105 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100106 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700107 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200108 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100109
110 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000111
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100113 void SimplifySystemArrayCopy(HInvoke* invoke);
114 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100115 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800116 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800117 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100118 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100119 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800120 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800121 void SimplifyReturnThis(HInvoke* invoke);
122 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800123 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Aart Bik1f8d51b2018-02-15 10:42:37 -0800124 void SimplifyMin(HInvoke* invoke, DataType::Type type);
125 void SimplifyMax(HInvoke* invoke, DataType::Type type);
Aart Bik3dad3412018-02-28 12:01:46 -0800126 void SimplifyAbs(HInvoke* invoke, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100127
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000128 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100129 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000130 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100131 bool simplification_occurred_ = false;
132 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700133 // We ensure we do not loop infinitely. The value should not be too high, since that
134 // would allow looping around the same basic block too many times. The value should
135 // not be too low either, however, since we want to allow revisiting a basic block
136 // with many statements and simplifications at least once.
137 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000138};
139
Aart Bik24773202018-04-26 10:28:51 -0700140bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100141 if (kTestInstructionClonerExhaustively) {
142 CloneAndReplaceInstructionVisitor visitor(graph_);
143 visitor.VisitReversePostOrder();
144 }
145
Vladimir Marko65979462017-05-19 17:25:12 +0100146 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Aart Bik24773202018-04-26 10:28:51 -0700147 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100148}
149
Aart Bik24773202018-04-26 10:28:51 -0700150bool InstructionSimplifierVisitor::Run() {
151 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100152 // Iterate in reverse post order to open up more simplifications to users
153 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100154 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100155 // The simplification of an instruction to another instruction may yield
156 // possibilities for other simplifications. So although we perform a reverse
157 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100158 do {
159 simplification_occurred_ = false;
160 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700161 if (simplification_occurred_) {
162 didSimplify = true;
163 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100164 } while (simplification_occurred_ &&
165 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100166 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100167 }
Aart Bik24773202018-04-26 10:28:51 -0700168 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100169}
170
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000171namespace {
172
173bool AreAllBitsSet(HConstant* constant) {
174 return Int64FromConstant(constant) == -1;
175}
176
177} // namespace
178
Alexandre Rames188d4312015-04-09 18:30:21 +0100179// Returns true if the code was simplified to use only one negation operation
180// after the binary operation instead of one on each of the inputs.
181bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
182 DCHECK(binop->IsAdd() || binop->IsSub());
183 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
184 HNeg* left_neg = binop->GetLeft()->AsNeg();
185 HNeg* right_neg = binop->GetRight()->AsNeg();
186 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
187 !right_neg->HasOnlyOneNonEnvironmentUse()) {
188 return false;
189 }
190 // Replace code looking like
191 // NEG tmp1, a
192 // NEG tmp2, b
193 // ADD dst, tmp1, tmp2
194 // with
195 // ADD tmp, a, b
196 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600197 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
198 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
199 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100200 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600201 return false;
202 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100203 binop->ReplaceInput(left_neg->GetInput(), 0);
204 binop->ReplaceInput(right_neg->GetInput(), 1);
205 left_neg->GetBlock()->RemoveInstruction(left_neg);
206 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100207 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100208 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
209 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
210 RecordSimplification();
211 return true;
212}
213
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000214bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
215 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100216 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000217 HInstruction* left = op->GetLeft();
218 HInstruction* right = op->GetRight();
219
220 // We can apply De Morgan's laws if both inputs are Not's and are only used
221 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000222 if (((left->IsNot() && right->IsNot()) ||
223 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000224 left->HasOnlyOneNonEnvironmentUse() &&
225 right->HasOnlyOneNonEnvironmentUse()) {
226 // Replace code looking like
227 // NOT nota, a
228 // NOT notb, b
229 // AND dst, nota, notb (respectively OR)
230 // with
231 // OR or, a, b (respectively AND)
232 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000233 HInstruction* src_left = left->InputAt(0);
234 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000235 uint32_t dex_pc = op->GetDexPc();
236
237 // Remove the negations on the inputs.
238 left->ReplaceWith(src_left);
239 right->ReplaceWith(src_right);
240 left->GetBlock()->RemoveInstruction(left);
241 right->GetBlock()->RemoveInstruction(right);
242
243 // Replace the `HAnd` or `HOr`.
244 HBinaryOperation* hbin;
245 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100246 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000247 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100248 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000249 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000250 HInstruction* hnot;
251 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100252 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000253 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100254 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000255 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000256
257 op->GetBlock()->InsertInstructionBefore(hbin, op);
258 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
259
260 RecordSimplification();
261 return true;
262 }
263
264 return false;
265}
266
Lena Djokicbc5460b2017-07-20 16:07:36 +0200267bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100268 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200269 InstructionSet isa = codegen_->GetInstructionSet();
270 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000271 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100272 if (!(type == DataType::Type::kUint8 ||
273 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100274 type == DataType::Type::kUint16 ||
275 type == DataType::Type::kInt16 ||
276 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200277 return false;
278 }
279 break;
Vladimir Marko33bff252017-11-01 14:35:42 +0000280 case InstructionSet::kMips:
281 case InstructionSet::kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100282 if (!(type == DataType::Type::kUint8 ||
283 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100284 type == DataType::Type::kUint16 ||
285 type == DataType::Type::kInt16 ||
286 type == DataType::Type::kInt32 ||
287 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200288 return false;
289 }
290 break;
291 default:
292 return false;
293 }
294
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100295 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200296
297 if (mul->HasOnlyOneNonEnvironmentUse()) {
298 HInstruction* use = mul->GetUses().front().GetUser();
299 if (use->IsVecAdd() || use->IsVecSub()) {
300 // Replace code looking like
301 // VECMUL tmp, x, y
302 // VECADD/SUB dst, acc, tmp
303 // with
304 // VECMULACC dst, acc, x, y
305 // Note that we do not want to (unconditionally) perform the merge when the
306 // multiplication has multiple uses and it can be merged in all of them.
307 // Multiple uses could happen on the same control-flow path, and we would
308 // then increase the amount of work. In the future we could try to evaluate
309 // whether all uses are on different control-flow paths (using dominance and
310 // reverse-dominance information) and only perform the merge when they are.
311 HInstruction* accumulator = nullptr;
312 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
313 HInstruction* binop_left = binop->GetLeft();
314 HInstruction* binop_right = binop->GetRight();
315 // This is always true since the `HVecMul` has only one use (which is checked above).
316 DCHECK_NE(binop_left, binop_right);
317 if (binop_right == mul) {
318 accumulator = binop_left;
319 } else if (use->IsVecAdd()) {
320 DCHECK_EQ(binop_left, mul);
321 accumulator = binop_right;
322 }
323
324 HInstruction::InstructionKind kind =
325 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
326 if (accumulator != nullptr) {
327 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100328 new (allocator) HVecMultiplyAccumulate(allocator,
329 kind,
330 accumulator,
331 mul->GetLeft(),
332 mul->GetRight(),
333 binop->GetPackedType(),
334 binop->GetVectorLength(),
335 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200336
337 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
338 DCHECK(!mul->HasUses());
339 mul->GetBlock()->RemoveInstruction(mul);
340 return true;
341 }
342 }
343 }
344
345 return false;
346}
347
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000348void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
349 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100350 HInstruction* shift_amount = instruction->GetRight();
351 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000352
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100353 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100354 ? kMaxLongShiftDistance
355 : kMaxIntShiftDistance;
356
357 if (shift_amount->IsConstant()) {
358 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700359 int64_t masked_cst = cst & implicit_mask;
360 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400361 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100362 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400363 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100364 // value
365 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400366 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100367 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100368 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700369 } else if (masked_cst != cst) {
370 // Replace code looking like
371 // SHL dst, value, cst
372 // where cst exceeds maximum distance with the equivalent
373 // SHL dst, value, cst & implicit_mask
374 // (as defined by shift semantics). This ensures other
375 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100376 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700377 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
378 RecordSimplification();
379 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100380 }
381 }
382
383 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100384 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
385 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100386 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100387 // AND adjusted_shift, shift, <superset of implicit mask>
388 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
389 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
390 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100391 // with
392 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100393 if (shift_amount->IsAnd() ||
394 shift_amount->IsOr() ||
395 shift_amount->IsXor() ||
396 shift_amount->IsAdd() ||
397 shift_amount->IsSub()) {
398 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
399 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
400 HConstant* mask = bin_op->GetConstantRight();
401 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
402 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100403 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100404 return;
405 }
406 } else if (shift_amount->IsTypeConversion()) {
407 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
408 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
409 // Non-integral and 64-bit source types require an explicit type conversion.
410 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
411 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
412 RecordSimplification();
413 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400414 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000415 }
416}
417
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000418static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
419 return (sub->GetRight() == other &&
420 sub->GetLeft()->IsConstant() &&
421 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
422}
423
424bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
425 HUShr* ushr,
426 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000427 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100428 HRor* ror =
429 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000430 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
431 if (!ushr->HasUses()) {
432 ushr->GetBlock()->RemoveInstruction(ushr);
433 }
434 if (!ushr->GetRight()->HasUses()) {
435 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
436 }
437 if (!shl->HasUses()) {
438 shl->GetBlock()->RemoveInstruction(shl);
439 }
440 if (!shl->GetRight()->HasUses()) {
441 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
442 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100443 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000444 return true;
445}
446
447// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
448bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000449 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
450 HInstruction* left = op->GetLeft();
451 HInstruction* right = op->GetRight();
452 // If we have an UShr and a Shl (in either order).
453 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
454 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
455 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100456 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000457 if (ushr->GetType() == shl->GetType() &&
458 ushr->GetLeft() == shl->GetLeft()) {
459 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
460 // Shift distances are both constant, try replacing with Ror if they
461 // add up to the register size.
462 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
463 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
464 // Shift distances are potentially of the form x and (reg_size - x).
465 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
466 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
467 // Shift distances are potentially of the form d and -d.
468 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
469 }
470 }
471 }
472 return false;
473}
474
475// Try replacing code looking like (x >>> #rdist OP x << #ldist):
476// UShr dst, x, #rdist
477// Shl tmp, x, #ldist
478// OP dst, dst, tmp
479// or like (x >>> #rdist OP x << #-ldist):
480// UShr dst, x, #rdist
481// Shl tmp, x, #-ldist
482// OP dst, dst, tmp
483// with
484// Ror dst, x, #rdist
485bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
486 HUShr* ushr,
487 HShl* shl) {
488 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100489 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000490 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
491 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
492 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
493 ReplaceRotateWithRor(op, ushr, shl);
494 return true;
495 }
496 return false;
497}
498
499// Replace code looking like (x >>> -d OP x << d):
500// Neg neg, d
501// UShr dst, x, neg
502// Shl tmp, x, d
503// OP dst, dst, tmp
504// with
505// Neg neg, d
506// Ror dst, x, neg
507// *** OR ***
508// Replace code looking like (x >>> d OP x << -d):
509// UShr dst, x, d
510// Neg neg, d
511// Shl tmp, x, neg
512// OP dst, dst, tmp
513// with
514// Ror dst, x, d
515bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
516 HUShr* ushr,
517 HShl* shl) {
518 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
519 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
520 bool neg_is_left = shl->GetRight()->IsNeg();
521 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
522 // And the shift distance being negated is the distance being shifted the other way.
523 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
524 ReplaceRotateWithRor(op, ushr, shl);
525 }
526 return false;
527}
528
529// Try replacing code looking like (x >>> d OP x << (#bits - d)):
530// UShr dst, x, d
531// Sub ld, #bits, d
532// Shl tmp, x, ld
533// OP dst, dst, tmp
534// with
535// Ror dst, x, d
536// *** OR ***
537// Replace code looking like (x >>> (#bits - d) OP x << d):
538// Sub rd, #bits, d
539// UShr dst, x, rd
540// Shl tmp, x, d
541// OP dst, dst, tmp
542// with
543// Neg neg, d
544// Ror dst, x, neg
545bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
546 HUShr* ushr,
547 HShl* shl) {
548 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
549 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100550 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000551 HInstruction* shl_shift = shl->GetRight();
552 HInstruction* ushr_shift = ushr->GetRight();
553 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
554 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
555 return ReplaceRotateWithRor(op, ushr, shl);
556 }
557 return false;
558}
559
Calin Juravle10e244f2015-01-26 18:54:32 +0000560void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
561 HInstruction* obj = null_check->InputAt(0);
562 if (!obj->CanBeNull()) {
563 null_check->ReplaceWith(obj);
564 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000565 if (stats_ != nullptr) {
566 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
567 }
568 }
569}
570
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100571bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
572 if (!input->CanBeNull()) {
573 return true;
574 }
575
Vladimir Marko46817b82016-03-29 12:21:58 +0100576 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
577 HInstruction* user = use.GetUser();
578 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100579 return true;
580 }
581 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100582
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100583 return false;
584}
585
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100586// Returns whether doing a type test between the class of `object` against `klass` has
587// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000588static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
589 HInstruction* object,
590 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000591 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
592 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
593 ScopedObjectAccess soa(Thread::Current());
594 if (!obj_rti.IsValid()) {
595 // We run the simplifier before the reference type propagation so type info might not be
596 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100597 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000598 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100599
Calin Juravle98893e12015-10-02 21:05:03 +0100600 if (!class_rti.IsValid()) {
601 // Happens when the loaded class is unresolved.
602 return false;
603 }
604 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000605 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100606 *outcome = true;
607 return true;
608 } else if (obj_rti.IsExact()) {
609 // The test failed at compile time so will also fail at runtime.
610 *outcome = false;
611 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100612 } else if (!class_rti.IsInterface()
613 && !obj_rti.IsInterface()
614 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100615 // Different type hierarchy. The test will fail.
616 *outcome = false;
617 return true;
618 }
619 return false;
620}
621
622void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
623 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000624 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
625 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100626 // If we need to perform an access check we cannot remove the instruction.
627 return;
628 }
629
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100630 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100631 check_cast->ClearMustDoNullCheck();
632 }
633
634 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000635 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700636 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100637 return;
638 }
639
Roland Levillain05e34f42018-05-24 13:19:05 +0000640 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
641 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000642 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000643 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100644 if (outcome) {
645 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700646 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000647 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
648 HLoadClass* load_class = check_cast->GetTargetClass();
649 if (!load_class->HasUses()) {
650 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
651 // However, here we know that it cannot because the checkcast was successfull, hence
652 // the class was already loaded.
653 load_class->GetBlock()->RemoveInstruction(load_class);
654 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700655 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100656 } else {
657 // Don't do anything for exceptional cases for now. Ideally we should remove
658 // all instructions and blocks this instruction dominates.
659 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000660 }
661}
662
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100663void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100664 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000665 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
666 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100667 // If we need to perform an access check we cannot remove the instruction.
668 return;
669 }
670
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100671 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100672 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100673 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100674 instruction->ClearMustDoNullCheck();
675 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100676
677 HGraph* graph = GetGraph();
678 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000679 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100680 instruction->ReplaceWith(graph->GetIntConstant(0));
681 instruction->GetBlock()->RemoveInstruction(instruction);
682 RecordSimplification();
683 return;
684 }
685
Roland Levillain05e34f42018-05-24 13:19:05 +0000686 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
687 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000688 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000689 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000690 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100691 if (outcome && can_be_null) {
692 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100693 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100694 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
695 instruction->ReplaceWith(test);
696 } else {
697 // We've statically determined the result of the instanceof.
698 instruction->ReplaceWith(graph->GetIntConstant(outcome));
699 }
700 RecordSimplification();
701 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000702 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
703 HLoadClass* load_class = instruction->GetTargetClass();
704 if (!load_class->HasUses()) {
705 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
706 // However, here we know that it cannot because the instanceof check was successfull, hence
707 // the class was already loaded.
708 load_class->GetBlock()->RemoveInstruction(load_class);
709 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700710 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100711 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100712}
713
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100714void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100715 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100716 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100717 instruction->ClearValueCanBeNull();
718 }
719}
720
721void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100722 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100723 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100724 instruction->ClearValueCanBeNull();
725 }
726}
727
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100728static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600729 HInstruction *lhs = cond->InputAt(0);
730 HInstruction *rhs = cond->InputAt(1);
731 switch (cond->GetKind()) {
732 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100733 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600734 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100735 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600736 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100737 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600738 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100739 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600740 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100741 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600742 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100743 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600744 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100745 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600746 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100747 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600748 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100749 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600750 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100751 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600752 default:
753 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
754 }
755 return nullptr;
756}
757
Aart Bik2767f4b2016-10-28 15:03:53 -0700758static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100759 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700760 return true; // input has direct boolean type
761 } else if (cmp->GetUses().HasExactlyOneElement()) {
762 // Comparison also has boolean type if both its input and the instruction
763 // itself feed into the same phi node.
764 HInstruction* user = cmp->GetUses().front().GetUser();
765 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
766 }
767 return false;
768}
769
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000770void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100771 HInstruction* input_const = equal->GetConstantRight();
772 if (input_const != nullptr) {
773 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700774 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100775 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100776 // We are comparing the boolean to a constant which is of type int and can
777 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000778 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100779 // Replace (bool_value == true) with bool_value
780 equal->ReplaceWith(input_value);
781 block->RemoveInstruction(equal);
782 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000783 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700784 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500785 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
786 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100787 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100788 } else {
789 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
790 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
791 block->RemoveInstruction(equal);
792 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100793 }
Mark Mendellc4701932015-04-10 13:18:51 -0400794 } else {
795 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100796 }
Mark Mendellc4701932015-04-10 13:18:51 -0400797 } else {
798 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100799 }
800}
801
David Brazdil0d13fee2015-04-17 14:52:19 +0100802void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
803 HInstruction* input_const = not_equal->GetConstantRight();
804 if (input_const != nullptr) {
805 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700806 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100807 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100808 // We are comparing the boolean to a constant which is of type int and can
809 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000810 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700811 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500812 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
813 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100814 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000815 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100816 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100817 not_equal->ReplaceWith(input_value);
818 block->RemoveInstruction(not_equal);
819 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100820 } else {
821 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
822 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
823 block->RemoveInstruction(not_equal);
824 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100825 }
Mark Mendellc4701932015-04-10 13:18:51 -0400826 } else {
827 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100828 }
Mark Mendellc4701932015-04-10 13:18:51 -0400829 } else {
830 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100831 }
832}
833
834void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000835 HInstruction* input = bool_not->InputAt(0);
836 HInstruction* replace_with = nullptr;
837
838 if (input->IsIntConstant()) {
839 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000840 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000841 replace_with = GetGraph()->GetIntConstant(0);
842 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000843 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000844 replace_with = GetGraph()->GetIntConstant(1);
845 }
846 } else if (input->IsBooleanNot()) {
847 // Replace (!(!bool_value)) with bool_value.
848 replace_with = input->InputAt(0);
849 } else if (input->IsCondition() &&
850 // Don't change FP compares. The definition of compares involving
851 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100852 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000853 // Replace condition with its opposite.
854 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
855 }
856
857 if (replace_with != nullptr) {
858 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100859 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000860 RecordSimplification();
861 }
862}
863
Aart Bik4f7dd342017-09-12 13:12:57 -0700864// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100865static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
866 HInstruction* x,
867 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700868 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800869 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700870 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800871 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
872 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700873}
874
Aart Bik142b9132018-03-14 15:12:59 -0700875// Constructs a new MIN/MAX(x, y) node in the HIR.
876static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
877 HInstruction* x,
878 HInstruction* y,
879 HInstruction* cursor,
880 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700881 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700882 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
883 HBinaryOperation* minmax = nullptr;
884 if (is_min) {
885 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
886 } else {
887 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
888 }
889 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
890 return minmax;
891}
892
Aart Bik4f7dd342017-09-12 13:12:57 -0700893// Returns true if operands a and b consists of widening type conversions
894// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100895static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700896 if (a->IsTypeConversion() && a->GetType() == to_type) {
897 a = a->InputAt(0);
898 }
899 if (b->IsTypeConversion() && b->GetType() == to_type) {
900 b = b->InputAt(0);
901 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100902 DataType::Type type1 = a->GetType();
903 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100904 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
905 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
906 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
907 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
908 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100909 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700910}
911
Aart Bik1d746de2018-03-28 16:30:02 -0700912// Returns an acceptable substitution for "a" on the select
913// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
914static HInstruction* AllowInMinMax(IfCondition cmp,
915 HInstruction* a,
916 HInstruction* b,
917 HInstruction* c) {
918 int64_t value = 0;
919 if (IsInt64AndGet(b, /*out*/ &value) &&
920 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
921 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
922 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
923 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
924 int64_t other_value = Int64FromConstant(other);
925 bool is_max = (cmp == kCondLT || cmp == kCondLE);
926 // Allow the max for a < 100 ? max(a, -100) : ..
927 // or the min for a > -100 ? min(a, 100) : ..
928 if (is_max ? (value >= other_value) : (value <= other_value)) {
929 return c;
930 }
931 }
932 }
933 return nullptr;
934}
935
David Brazdil74eb1b22015-12-14 11:44:01 +0000936void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
937 HInstruction* replace_with = nullptr;
938 HInstruction* condition = select->GetCondition();
939 HInstruction* true_value = select->GetTrueValue();
940 HInstruction* false_value = select->GetFalseValue();
941
942 if (condition->IsBooleanNot()) {
943 // Change ((!cond) ? x : y) to (cond ? y : x).
944 condition = condition->InputAt(0);
945 std::swap(true_value, false_value);
946 select->ReplaceInput(false_value, 0);
947 select->ReplaceInput(true_value, 1);
948 select->ReplaceInput(condition, 2);
949 RecordSimplification();
950 }
951
952 if (true_value == false_value) {
953 // Replace (cond ? x : x) with (x).
954 replace_with = true_value;
955 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000956 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000957 // Replace (true ? x : y) with (x).
958 replace_with = true_value;
959 } else {
960 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000961 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000962 replace_with = false_value;
963 }
964 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000965 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000966 // Replace (cond ? true : false) with (cond).
967 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000968 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000969 // Replace (cond ? false : true) with (!cond).
970 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
971 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700972 } else if (condition->IsCondition()) {
973 IfCondition cmp = condition->AsCondition()->GetCondition();
974 HInstruction* a = condition->InputAt(0);
975 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100976 DataType::Type t_type = true_value->GetType();
977 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700978 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700979 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
980 // type will be int or long, like the condition). Replacements are general,
981 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700982 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700983 // Allow a < 100 ? max(a, -100) : ..
984 // or a > -100 ? min(a, 100) : ..
985 // to use min/max instead of a to detect nested min/max expressions.
986 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
987 if (new_a != nullptr) {
988 a = new_a;
989 }
Aart Bik142b9132018-03-14 15:12:59 -0700990 // Try to replace typical integral MIN/MAX/ABS constructs.
991 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
992 ((a == true_value && b == false_value) ||
993 (b == true_value && a == false_value))) {
994 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
995 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
996 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
997 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700998 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
999 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
1000 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
1001 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
1002 HInstruction* not_negated = negLeft ? false_value : true_value;
1003 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
1004 // Found a < 0 ? -a : a
1005 // or a > 0 ? a : -a
1006 // which can be replaced by ABS(a).
1007 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001008 }
1009 } else if (true_value->IsSub() && false_value->IsSub()) {
1010 HInstruction* true_sub1 = true_value->InputAt(0);
1011 HInstruction* true_sub2 = true_value->InputAt(1);
1012 HInstruction* false_sub1 = false_value->InputAt(0);
1013 HInstruction* false_sub2 = false_value->InputAt(1);
1014 if ((((cmp == kCondGT || cmp == kCondGE) &&
1015 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1016 ((cmp == kCondLT || cmp == kCondLE) &&
1017 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1018 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001019 // Found a > b ? a - b : b - a
1020 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001021 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001022 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001023 }
1024 }
1025 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001026 }
1027
1028 if (replace_with != nullptr) {
1029 select->ReplaceWith(replace_with);
1030 select->GetBlock()->RemoveInstruction(select);
1031 RecordSimplification();
1032 }
1033}
1034
1035void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1036 HInstruction* condition = instruction->InputAt(0);
1037 if (condition->IsBooleanNot()) {
1038 // Swap successors if input is negated.
1039 instruction->ReplaceInput(condition->InputAt(0), 0);
1040 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001041 RecordSimplification();
1042 }
1043}
1044
Mingyao Yang0304e182015-01-30 16:41:29 -08001045void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1046 HInstruction* input = instruction->InputAt(0);
1047 // If the array is a NewArray with constant size, replace the array length
1048 // with the constant instruction. This helps the bounds check elimination phase.
1049 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001050 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001051 if (input->IsIntConstant()) {
1052 instruction->ReplaceWith(input);
1053 }
1054 }
1055}
1056
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001057void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001058 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001059 if (value->GetType() != DataType::Type::kReference) {
1060 return;
1061 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001062
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001063 if (CanEnsureNotNullAt(value, instruction)) {
1064 instruction->ClearValueCanBeNull();
1065 }
1066
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001067 if (value->IsArrayGet()) {
1068 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1069 // If the code is just swapping elements in the array, no need for a type check.
1070 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001071 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001072 }
1073 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001074
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001075 if (value->IsNullConstant()) {
1076 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001077 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001078 }
1079
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001080 ScopedObjectAccess soa(Thread::Current());
1081 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1082 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1083 if (!array_rti.IsValid()) {
1084 return;
1085 }
1086
1087 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1088 instruction->ClearNeedsTypeCheck();
1089 return;
1090 }
1091
1092 if (array_rti.IsObjectArray()) {
1093 if (array_rti.IsExact()) {
1094 instruction->ClearNeedsTypeCheck();
1095 return;
1096 }
1097 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001098 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001099}
1100
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001101static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001102 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1103 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1104 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001105 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001106 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001107 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1108 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001109 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001110 return DataType::Size(result_type) > DataType::Size(input_type) &&
1111 result_type != DataType::Type::kUint16 &&
1112 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001113}
1114
Vladimir Marko61b92282017-10-11 13:23:17 +01001115static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1116 if (maybe_get->IsInstanceFieldGet()) {
1117 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1118 return true;
1119 } else if (maybe_get->IsStaticFieldGet()) {
1120 maybe_get->AsStaticFieldGet()->SetType(new_type);
1121 return true;
1122 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1123 maybe_get->AsArrayGet()->SetType(new_type);
1124 return true;
1125 } else {
1126 return false;
1127 }
1128}
1129
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001130// The type conversion is only used for storing into a field/element of the
1131// same/narrower size.
1132static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1133 if (type_conversion->HasEnvironmentUses()) {
1134 return false;
1135 }
1136 DataType::Type input_type = type_conversion->GetInputType();
1137 DataType::Type result_type = type_conversion->GetResultType();
1138 if (!DataType::IsIntegralType(input_type) ||
1139 !DataType::IsIntegralType(result_type) ||
1140 input_type == DataType::Type::kInt64 ||
1141 result_type == DataType::Type::kInt64) {
1142 // Type conversion is needed if non-integer types are involved, or 64-bit
1143 // types are involved, which may use different number of registers.
1144 return false;
1145 }
1146 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1147 // Type conversion is not necessary when storing to a field/element of the
1148 // same/smaller size.
1149 } else {
1150 // We do not handle this case here.
1151 return false;
1152 }
1153
1154 // Check if the converted value is only used for storing into heap.
1155 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1156 HInstruction* instruction = use.GetUser();
1157 if (instruction->IsInstanceFieldSet() &&
1158 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1159 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1160 continue;
1161 }
1162 if (instruction->IsStaticFieldSet() &&
1163 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1164 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1165 continue;
1166 }
1167 if (instruction->IsArraySet() &&
1168 instruction->AsArraySet()->GetComponentType() == result_type &&
1169 // not index use.
1170 instruction->AsArraySet()->GetIndex() != type_conversion) {
1171 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1172 continue;
1173 }
1174 // The use is not as a store value, or the field/element type is not the
1175 // same as the result_type, keep the type conversion.
1176 return false;
1177 }
1178 // Codegen automatically handles the type conversion during the store.
1179 return true;
1180}
1181
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001182void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001183 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001184 DataType::Type input_type = input->GetType();
1185 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001186 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001187 // Remove the implicit conversion; this includes conversion to the same type.
1188 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001189 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001190 RecordSimplification();
1191 return;
1192 }
1193
1194 if (input->IsTypeConversion()) {
1195 HTypeConversion* input_conversion = input->AsTypeConversion();
1196 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001197 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001198
1199 // When the first conversion is lossless, a direct conversion from the original type
1200 // to the final type yields the same result, even for a lossy second conversion, for
1201 // example float->double->int or int->double->float.
1202 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1203
1204 // For integral conversions, see if the first conversion loses only bits that the second
1205 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1206 // conversion yields the same result, for example long->int->short or int->char->short.
1207 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001208 DataType::IsIntegralType(input_type) &&
1209 DataType::IsIntegralType(original_type) &&
1210 DataType::IsIntegralType(result_type) &&
1211 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001212
1213 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1214 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001215 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001216 instruction->ReplaceWith(original_input);
1217 instruction->GetBlock()->RemoveInstruction(instruction);
1218 if (!input_conversion->HasUses()) {
1219 // Don't wait for DCE.
1220 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1221 }
1222 RecordSimplification();
1223 return;
1224 }
1225 // Otherwise simplify only if the first conversion has no other use.
1226 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1227 input_conversion->ReplaceWith(original_input);
1228 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1229 RecordSimplification();
1230 return;
1231 }
1232 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001233 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1234 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001235 HAnd* input_and = input->AsAnd();
1236 HConstant* constant = input_and->GetConstantRight();
1237 if (constant != nullptr) {
1238 int64_t value = Int64FromConstant(constant);
1239 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1240 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001241 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001242 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001243 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001244 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001245 instruction->ReplaceWith(original_input);
1246 instruction->GetBlock()->RemoveInstruction(instruction);
1247 RecordSimplification();
1248 return;
1249 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1250 input_and->ReplaceWith(original_input);
1251 input_and->GetBlock()->RemoveInstruction(input_and);
1252 RecordSimplification();
1253 return;
1254 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001255 }
1256 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001257 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1258 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1259 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1260 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1261 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1262 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1263 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1264 instruction->ReplaceWith(input);
1265 instruction->GetBlock()->RemoveInstruction(instruction);
1266 RecordSimplification();
1267 return;
1268 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001269 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001270
1271 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1272 instruction->ReplaceWith(input);
1273 instruction->GetBlock()->RemoveInstruction(instruction);
1274 RecordSimplification();
1275 return;
1276 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001277}
1278
Aart Bikc6eec4b2018-03-29 17:22:00 -07001279void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1280 HInstruction* input = instruction->GetInput();
1281 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1282 // Zero extension from narrow to wide can never set sign bit in the wider
1283 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1284 instruction->ReplaceWith(input);
1285 instruction->GetBlock()->RemoveInstruction(instruction);
1286 RecordSimplification();
1287 }
1288}
1289
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001290void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1291 HConstant* input_cst = instruction->GetConstantRight();
1292 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001293 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001294 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001295 // Replace code looking like
1296 // ADD dst, src, 0
1297 // with
1298 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001299 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1300 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1301 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001302 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001303 instruction->ReplaceWith(input_other);
1304 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001305 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001306 return;
1307 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001308 }
1309
1310 HInstruction* left = instruction->GetLeft();
1311 HInstruction* right = instruction->GetRight();
1312 bool left_is_neg = left->IsNeg();
1313 bool right_is_neg = right->IsNeg();
1314
1315 if (left_is_neg && right_is_neg) {
1316 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1317 return;
1318 }
1319 }
1320
1321 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1322 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1323 // Replace code looking like
1324 // NEG tmp, b
1325 // ADD dst, a, tmp
1326 // with
1327 // SUB dst, a, b
1328 // We do not perform the optimization if the input negation has environment
1329 // uses or multiple non-environment uses as it could lead to worse code. In
1330 // particular, we do not want the live range of `b` to be extended if we are
1331 // not sure the initial 'NEG' instruction can be removed.
1332 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001333 HSub* sub =
1334 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001335 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1336 RecordSimplification();
1337 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001338 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001339 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001340
Anton Kirilove14dc862016-05-13 17:56:15 +01001341 if (TryReplaceWithRotate(instruction)) {
1342 return;
1343 }
1344
1345 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1346 // so no need to return.
1347 TryHandleAssociativeAndCommutativeOperation(instruction);
1348
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001349 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001350 TrySubtractionChainSimplification(instruction)) {
1351 return;
1352 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001353
1354 if (integral_type) {
1355 // Replace code patterns looking like
1356 // SUB dst1, x, y SUB dst1, x, y
1357 // ADD dst2, dst1, y ADD dst2, y, dst1
1358 // with
1359 // SUB dst1, x, y
1360 // ADD instruction is not needed in this case, we may use
1361 // one of inputs of SUB instead.
1362 if (left->IsSub() && left->InputAt(1) == right) {
1363 instruction->ReplaceWith(left->InputAt(0));
1364 RecordSimplification();
1365 instruction->GetBlock()->RemoveInstruction(instruction);
1366 return;
1367 } else if (right->IsSub() && right->InputAt(1) == left) {
1368 instruction->ReplaceWith(right->InputAt(0));
1369 RecordSimplification();
1370 instruction->GetBlock()->RemoveInstruction(instruction);
1371 return;
1372 }
1373 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001374}
1375
1376void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001377 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001378 HConstant* input_cst = instruction->GetConstantRight();
1379 HInstruction* input_other = instruction->GetLeastConstantLeft();
1380
Vladimir Marko452c1b62015-09-25 14:44:17 +01001381 if (input_cst != nullptr) {
1382 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001383 if (value == -1 ||
1384 // Similar cases under zero extension.
1385 (DataType::IsUnsignedType(input_other->GetType()) &&
1386 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001387 // Replace code looking like
1388 // AND dst, src, 0xFFF...FF
1389 // with
1390 // src
1391 instruction->ReplaceWith(input_other);
1392 instruction->GetBlock()->RemoveInstruction(instruction);
1393 RecordSimplification();
1394 return;
1395 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001396 if (input_other->IsTypeConversion() &&
1397 input_other->GetType() == DataType::Type::kInt64 &&
1398 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1399 IsInt<32>(value) &&
1400 input_other->HasOnlyOneNonEnvironmentUse()) {
1401 // The AND can be reordered before the TypeConversion. Replace
1402 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1403 // TypeConversion<Int64> tmp, src
1404 // AND dst, tmp, cst
1405 // with
1406 // IntConstant cst, <32-bit-constant>
1407 // AND tmp, src, cst
1408 // TypeConversion<Int64> dst, tmp
1409 // This helps 32-bit targets and does not hurt 64-bit targets.
1410 // This also simplifies detection of other patterns, such as Uint8 loads.
1411 HInstruction* new_and_input = input_other->InputAt(0);
1412 // Implicit conversion Int64->Int64 would have been removed previously.
1413 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1414 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1415 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001416 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001417 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1418 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001419 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001420 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1421 input_other->GetBlock()->RemoveInstruction(input_other);
1422 RecordSimplification();
1423 // Try to process the new And now, do not wait for the next round of simplifications.
1424 instruction = new_and;
1425 input_other = new_and_input;
1426 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001427 // Eliminate And from UShr+And if the And-mask contains all the bits that
1428 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1429 // precisely clears the shifted-in sign bits.
1430 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001432 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1433 size_t num_tail_bits_set = CTZ(value + 1);
1434 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1435 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1436 instruction->ReplaceWith(input_other);
1437 instruction->GetBlock()->RemoveInstruction(instruction);
1438 RecordSimplification();
1439 return;
1440 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1441 input_other->HasOnlyOneNonEnvironmentUse()) {
1442 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1443 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001444 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001445 input_other->InputAt(0),
1446 input_other->InputAt(1),
1447 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001448 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1449 input_other->GetBlock()->RemoveInstruction(input_other);
1450 RecordSimplification();
1451 return;
1452 }
1453 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001454 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1455 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1456 // or array Get with only a single use, short-circuit the subsequent simplification
1457 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1458 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1459 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1460 if (input_other->GetType() == find_type &&
1461 input_other->HasOnlyOneNonEnvironmentUse() &&
1462 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1463 instruction->ReplaceWith(input_other);
1464 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001465 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1466 instruction->ReplaceWith(input_other);
1467 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001468 } else {
1469 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1470 new_type, input_other, instruction->GetDexPc());
1471 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1472 }
1473 RecordSimplification();
1474 return;
1475 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001476 }
1477
1478 // We assume that GVN has run before, so we only perform a pointer comparison.
1479 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001480 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001481 if (instruction->GetLeft() == instruction->GetRight()) {
1482 // Replace code looking like
1483 // AND dst, src, src
1484 // with
1485 // src
1486 instruction->ReplaceWith(instruction->GetLeft());
1487 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001488 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001489 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001490 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001491
Anton Kirilove14dc862016-05-13 17:56:15 +01001492 if (TryDeMorganNegationFactoring(instruction)) {
1493 return;
1494 }
1495
1496 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1497 // so no need to return.
1498 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001499}
1500
Mark Mendellc4701932015-04-10 13:18:51 -04001501void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1502 VisitCondition(condition);
1503}
1504
1505void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1506 VisitCondition(condition);
1507}
1508
1509void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1510 VisitCondition(condition);
1511}
1512
1513void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1514 VisitCondition(condition);
1515}
1516
Anton Shaminbdd79352016-02-15 12:48:36 +06001517void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1518 VisitCondition(condition);
1519}
1520
1521void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1522 VisitCondition(condition);
1523}
1524
1525void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1526 VisitCondition(condition);
1527}
1528
1529void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1530 VisitCondition(condition);
1531}
Aart Bike9f37602015-10-09 11:15:55 -07001532
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001533// Recognize the following pattern:
1534// obj.getClass() ==/!= Foo.class
1535// And replace it with a constant value if the type of `obj` is statically known.
1536static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1537 HInstruction* input_one = condition->InputAt(0);
1538 HInstruction* input_two = condition->InputAt(1);
1539 HLoadClass* load_class = input_one->IsLoadClass()
1540 ? input_one->AsLoadClass()
1541 : input_two->AsLoadClass();
1542 if (load_class == nullptr) {
1543 return false;
1544 }
1545
1546 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1547 if (!class_rti.IsValid()) {
1548 // Unresolved class.
1549 return false;
1550 }
1551
1552 HInstanceFieldGet* field_get = (load_class == input_one)
1553 ? input_two->AsInstanceFieldGet()
1554 : input_one->AsInstanceFieldGet();
1555 if (field_get == nullptr) {
1556 return false;
1557 }
1558
1559 HInstruction* receiver = field_get->InputAt(0);
1560 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1561 if (!receiver_type.IsExact()) {
1562 return false;
1563 }
1564
1565 {
1566 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001567 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001568 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1569 if (field_get->GetFieldInfo().GetField() != field) {
1570 return false;
1571 }
1572
1573 // We can replace the compare.
1574 int value = 0;
1575 if (receiver_type.IsEqual(class_rti)) {
1576 value = condition->IsEqual() ? 1 : 0;
1577 } else {
1578 value = condition->IsNotEqual() ? 1 : 0;
1579 }
1580 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1581 return true;
1582 }
1583}
1584
Mark Mendellc4701932015-04-10 13:18:51 -04001585void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001586 if (condition->IsEqual() || condition->IsNotEqual()) {
1587 if (RecognizeAndSimplifyClassCheck(condition)) {
1588 return;
1589 }
1590 }
1591
Anton Shaminbdd79352016-02-15 12:48:36 +06001592 // Reverse condition if left is constant. Our code generators prefer constant
1593 // on the right hand side.
1594 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1595 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001596 HCondition* replacement =
1597 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001598 // If it is a fp we must set the opposite bias.
1599 if (replacement != nullptr) {
1600 if (condition->IsLtBias()) {
1601 replacement->SetBias(ComparisonBias::kGtBias);
1602 } else if (condition->IsGtBias()) {
1603 replacement->SetBias(ComparisonBias::kLtBias);
1604 }
1605 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1606 RecordSimplification();
1607
1608 condition = replacement;
1609 }
1610 }
Mark Mendellc4701932015-04-10 13:18:51 -04001611
Mark Mendellc4701932015-04-10 13:18:51 -04001612 HInstruction* left = condition->GetLeft();
1613 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001614
1615 // Try to fold an HCompare into this HCondition.
1616
Mark Mendellc4701932015-04-10 13:18:51 -04001617 // We can only replace an HCondition which compares a Compare to 0.
1618 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1619 // condition with a long, float or double comparison as input.
1620 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1621 // Conversion is not possible.
1622 return;
1623 }
1624
1625 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001626 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001627 // Someone else also wants the result of the compare.
1628 return;
1629 }
1630
Vladimir Marko46817b82016-03-29 12:21:58 +01001631 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001632 // There is a reference to the compare result in an environment. Do we really need it?
1633 if (GetGraph()->IsDebuggable()) {
1634 return;
1635 }
1636
1637 // We have to ensure that there are no deopt points in the sequence.
1638 if (left->HasAnyEnvironmentUseBefore(condition)) {
1639 return;
1640 }
1641 }
1642
1643 // Clean up any environment uses from the HCompare, if any.
1644 left->RemoveEnvironmentUsers();
1645
1646 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1647 condition->SetBias(left->AsCompare()->GetBias());
1648
1649 // Replace the operands of the HCondition.
1650 condition->ReplaceInput(left->InputAt(0), 0);
1651 condition->ReplaceInput(left->InputAt(1), 1);
1652
1653 // Remove the HCompare.
1654 left->GetBlock()->RemoveInstruction(left);
1655
1656 RecordSimplification();
1657}
1658
Andreas Gampe9186ced2016-12-12 14:28:21 -08001659// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1660static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1661 // True, if the most significant bits of divisor are 0.
1662 return ((divisor & 0x7fffff) == 0);
1663}
1664
1665// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1666static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1667 // True, if the most significant bits of divisor are 0.
1668 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1669}
1670
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001671void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1672 HConstant* input_cst = instruction->GetConstantRight();
1673 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001674 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001675
1676 if ((input_cst != nullptr) && input_cst->IsOne()) {
1677 // Replace code looking like
1678 // DIV dst, src, 1
1679 // with
1680 // src
1681 instruction->ReplaceWith(input_other);
1682 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001683 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001684 return;
1685 }
1686
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001687 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001688 // Replace code looking like
1689 // DIV dst, src, -1
1690 // with
1691 // NEG dst, src
1692 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001693 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001694 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001695 return;
1696 }
1697
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001698 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001699 // Try replacing code looking like
1700 // DIV dst, src, constant
1701 // with
1702 // MUL dst, src, 1 / constant
1703 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001704 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001705 double value = input_cst->AsDoubleConstant()->GetValue();
1706 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1707 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1708 }
1709 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001710 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001711 float value = input_cst->AsFloatConstant()->GetValue();
1712 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1713 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1714 }
1715 }
1716
1717 if (reciprocal != nullptr) {
1718 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001719 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001720 RecordSimplification();
1721 return;
1722 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001723 }
1724}
1725
1726void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1727 HConstant* input_cst = instruction->GetConstantRight();
1728 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001729 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001730 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001731 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001732
1733 if (input_cst == nullptr) {
1734 return;
1735 }
1736
1737 if (input_cst->IsOne()) {
1738 // Replace code looking like
1739 // MUL dst, src, 1
1740 // with
1741 // src
1742 instruction->ReplaceWith(input_other);
1743 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001744 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001745 return;
1746 }
1747
1748 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001749 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001750 // Replace code looking like
1751 // MUL dst, src, -1
1752 // with
1753 // NEG dst, src
1754 HNeg* neg = new (allocator) HNeg(type, input_other);
1755 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001756 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001757 return;
1758 }
1759
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001760 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001761 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1762 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1763 // Replace code looking like
1764 // FP_MUL dst, src, 2.0
1765 // with
1766 // FP_ADD dst, src, src
1767 // The 'int' and 'long' cases are handled below.
1768 block->ReplaceAndRemoveInstructionWith(instruction,
1769 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001770 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001771 return;
1772 }
1773
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001774 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001775 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001776 // Even though constant propagation also takes care of the zero case, other
1777 // optimizations can lead to having a zero multiplication.
1778 if (factor == 0) {
1779 // Replace code looking like
1780 // MUL dst, src, 0
1781 // with
1782 // 0
1783 instruction->ReplaceWith(input_cst);
1784 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001785 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001786 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001787 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001788 // Replace code looking like
1789 // MUL dst, src, pow_of_2
1790 // with
1791 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001792 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001793 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001794 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001795 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001796 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001797 } else if (IsPowerOfTwo(factor - 1)) {
1798 // Transform code looking like
1799 // MUL dst, src, (2^n + 1)
1800 // into
1801 // SHL tmp, src, n
1802 // ADD dst, src, tmp
1803 HShl* shl = new (allocator) HShl(type,
1804 input_other,
1805 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1806 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1807
1808 block->InsertInstructionBefore(shl, instruction);
1809 block->ReplaceAndRemoveInstructionWith(instruction, add);
1810 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001811 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001812 } else if (IsPowerOfTwo(factor + 1)) {
1813 // Transform code looking like
1814 // MUL dst, src, (2^n - 1)
1815 // into
1816 // SHL tmp, src, n
1817 // SUB dst, tmp, src
1818 HShl* shl = new (allocator) HShl(type,
1819 input_other,
1820 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1821 HSub* sub = new (allocator) HSub(type, shl, input_other);
1822
1823 block->InsertInstructionBefore(shl, instruction);
1824 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1825 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001826 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001827 }
1828 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001829
1830 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1831 // so no need to return.
1832 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001833}
1834
Alexandre Rames188d4312015-04-09 18:30:21 +01001835void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1836 HInstruction* input = instruction->GetInput();
1837 if (input->IsNeg()) {
1838 // Replace code looking like
1839 // NEG tmp, src
1840 // NEG dst, tmp
1841 // with
1842 // src
1843 HNeg* previous_neg = input->AsNeg();
1844 instruction->ReplaceWith(previous_neg->GetInput());
1845 instruction->GetBlock()->RemoveInstruction(instruction);
1846 // We perform the optimization even if the input negation has environment
1847 // uses since it allows removing the current instruction. But we only delete
1848 // the input negation only if it is does not have any uses left.
1849 if (!previous_neg->HasUses()) {
1850 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1851 }
1852 RecordSimplification();
1853 return;
1854 }
1855
Serguei Katkov339dfc22015-04-20 12:29:32 +06001856 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001857 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001858 // Replace code looking like
1859 // SUB tmp, a, b
1860 // NEG dst, tmp
1861 // with
1862 // SUB dst, b, a
1863 // We do not perform the optimization if the input subtraction has
1864 // environment uses or multiple non-environment uses as it could lead to
1865 // worse code. In particular, we do not want the live ranges of `a` and `b`
1866 // to be extended if we are not sure the initial 'SUB' instruction can be
1867 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001868 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001869 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001870 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1871 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001872 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1873 if (!sub->HasUses()) {
1874 sub->GetBlock()->RemoveInstruction(sub);
1875 }
1876 RecordSimplification();
1877 }
1878}
1879
1880void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1881 HInstruction* input = instruction->GetInput();
1882 if (input->IsNot()) {
1883 // Replace code looking like
1884 // NOT tmp, src
1885 // NOT dst, tmp
1886 // with
1887 // src
1888 // We perform the optimization even if the input negation has environment
1889 // uses since it allows removing the current instruction. But we only delete
1890 // the input negation only if it is does not have any uses left.
1891 HNot* previous_not = input->AsNot();
1892 instruction->ReplaceWith(previous_not->GetInput());
1893 instruction->GetBlock()->RemoveInstruction(instruction);
1894 if (!previous_not->HasUses()) {
1895 previous_not->GetBlock()->RemoveInstruction(previous_not);
1896 }
1897 RecordSimplification();
1898 }
1899}
1900
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001901void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1902 HConstant* input_cst = instruction->GetConstantRight();
1903 HInstruction* input_other = instruction->GetLeastConstantLeft();
1904
Roland Levillain1a653882016-03-18 18:05:57 +00001905 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001906 // Replace code looking like
1907 // OR dst, src, 0
1908 // with
1909 // src
1910 instruction->ReplaceWith(input_other);
1911 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001912 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001913 return;
1914 }
1915
1916 // We assume that GVN has run before, so we only perform a pointer comparison.
1917 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001918 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001919 if (instruction->GetLeft() == instruction->GetRight()) {
1920 // Replace code looking like
1921 // OR dst, src, src
1922 // with
1923 // src
1924 instruction->ReplaceWith(instruction->GetLeft());
1925 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001926 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001927 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001928 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001929
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001930 if (TryDeMorganNegationFactoring(instruction)) return;
1931
Anton Kirilove14dc862016-05-13 17:56:15 +01001932 if (TryReplaceWithRotate(instruction)) {
1933 return;
1934 }
1935
1936 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1937 // so no need to return.
1938 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001939}
1940
1941void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1942 VisitShift(instruction);
1943}
1944
1945void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1946 VisitShift(instruction);
1947}
1948
1949void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1950 HConstant* input_cst = instruction->GetConstantRight();
1951 HInstruction* input_other = instruction->GetLeastConstantLeft();
1952
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001953 DataType::Type type = instruction->GetType();
1954 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001955 return;
1956 }
1957
Roland Levillain1a653882016-03-18 18:05:57 +00001958 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001959 // Replace code looking like
1960 // SUB dst, src, 0
1961 // with
1962 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001963 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1964 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1965 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001966 instruction->ReplaceWith(input_other);
1967 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001968 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001969 return;
1970 }
1971
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001972 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001973 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001974
Alexandre Rames188d4312015-04-09 18:30:21 +01001975 HInstruction* left = instruction->GetLeft();
1976 HInstruction* right = instruction->GetRight();
1977 if (left->IsConstant()) {
1978 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001979 // Replace code looking like
1980 // SUB dst, 0, src
1981 // with
1982 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001983 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001984 // `x` is `0.0`, the former expression yields `0.0`, while the later
1985 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001986 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001987 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001988 RecordSimplification();
1989 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001990 }
1991 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001992
1993 if (left->IsNeg() && right->IsNeg()) {
1994 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1995 return;
1996 }
1997 }
1998
1999 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
2000 // Replace code looking like
2001 // NEG tmp, b
2002 // SUB dst, a, tmp
2003 // with
2004 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01002005 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002006 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2007 RecordSimplification();
2008 right->GetBlock()->RemoveInstruction(right);
2009 return;
2010 }
2011
2012 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2013 // Replace code looking like
2014 // NEG tmp, a
2015 // SUB dst, tmp, b
2016 // with
2017 // ADD tmp, a, b
2018 // NEG dst, tmp
2019 // The second version is not intrinsically better, but enables more
2020 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002021 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002022 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002023 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002024 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2025 instruction->ReplaceWith(neg);
2026 instruction->GetBlock()->RemoveInstruction(instruction);
2027 RecordSimplification();
2028 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002029 return;
2030 }
2031
2032 if (TrySubtractionChainSimplification(instruction)) {
2033 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002034 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002035
2036 if (left->IsAdd()) {
2037 // Replace code patterns looking like
2038 // ADD dst1, x, y ADD dst1, x, y
2039 // SUB dst2, dst1, y SUB dst2, dst1, x
2040 // with
2041 // ADD dst1, x, y
2042 // SUB instruction is not needed in this case, we may use
2043 // one of inputs of ADD instead.
2044 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002045 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002046 if (left->InputAt(1) == right) {
2047 instruction->ReplaceWith(left->InputAt(0));
2048 RecordSimplification();
2049 instruction->GetBlock()->RemoveInstruction(instruction);
2050 return;
2051 } else if (left->InputAt(0) == right) {
2052 instruction->ReplaceWith(left->InputAt(1));
2053 RecordSimplification();
2054 instruction->GetBlock()->RemoveInstruction(instruction);
2055 return;
2056 }
2057 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002058}
2059
2060void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2061 VisitShift(instruction);
2062}
2063
2064void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2065 HConstant* input_cst = instruction->GetConstantRight();
2066 HInstruction* input_other = instruction->GetLeastConstantLeft();
2067
Roland Levillain1a653882016-03-18 18:05:57 +00002068 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002069 // Replace code looking like
2070 // XOR dst, src, 0
2071 // with
2072 // src
2073 instruction->ReplaceWith(input_other);
2074 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002075 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002076 return;
2077 }
2078
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002079 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002080 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002081 // Replace code looking like
2082 // XOR dst, src, 1
2083 // with
2084 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002085 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002086 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2087 RecordSimplification();
2088 return;
2089 }
2090
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002091 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2092 // Replace code looking like
2093 // XOR dst, src, 0xFFF...FF
2094 // with
2095 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002096 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002097 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002098 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002099 return;
2100 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002101
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002102 HInstruction* left = instruction->GetLeft();
2103 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002104 if (((left->IsNot() && right->IsNot()) ||
2105 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002106 left->HasOnlyOneNonEnvironmentUse() &&
2107 right->HasOnlyOneNonEnvironmentUse()) {
2108 // Replace code looking like
2109 // NOT nota, a
2110 // NOT notb, b
2111 // XOR dst, nota, notb
2112 // with
2113 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002114 instruction->ReplaceInput(left->InputAt(0), 0);
2115 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002116 left->GetBlock()->RemoveInstruction(left);
2117 right->GetBlock()->RemoveInstruction(right);
2118 RecordSimplification();
2119 return;
2120 }
2121
Anton Kirilove14dc862016-05-13 17:56:15 +01002122 if (TryReplaceWithRotate(instruction)) {
2123 return;
2124 }
2125
2126 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2127 // so no need to return.
2128 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002129}
2130
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002131void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2132 HInstruction* argument = instruction->InputAt(1);
2133 HInstruction* receiver = instruction->InputAt(0);
2134 if (receiver == argument) {
2135 // Because String.equals is an instance call, the receiver is
2136 // a null check if we don't know it's null. The argument however, will
2137 // be the actual object. So we cannot end up in a situation where both
2138 // are equal but could be null.
2139 DCHECK(CanEnsureNotNullAt(argument, instruction));
2140 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2141 instruction->GetBlock()->RemoveInstruction(instruction);
2142 } else {
2143 StringEqualsOptimizations optimizations(instruction);
2144 if (CanEnsureNotNullAt(argument, instruction)) {
2145 optimizations.SetArgumentNotNull();
2146 }
2147 ScopedObjectAccess soa(Thread::Current());
2148 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2149 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2150 optimizations.SetArgumentIsString();
Vladimir Markoda283052017-11-07 21:17:24 +00002151 } else if (kUseReadBarrier) {
2152 DCHECK(instruction->GetResolvedMethod() != nullptr);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08002153 DCHECK(instruction->GetResolvedMethod()->GetDeclaringClass()->IsStringClass() ||
2154 // Object.equals() can be devirtualized to String.equals().
2155 instruction->GetResolvedMethod()->GetDeclaringClass()->IsObjectClass());
Vladimir Markoda283052017-11-07 21:17:24 +00002156 Runtime* runtime = Runtime::Current();
2157 // For AOT, we always assume that the boot image shall contain the String.class and
2158 // we do not need a read barrier for boot image classes as they are non-moveable.
2159 // For JIT, check if we actually have a boot image; if we do, the String.class
2160 // should also be non-moveable.
2161 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2162 DCHECK(runtime->IsAotCompiler() ||
2163 !runtime->GetHeap()->IsMovableObject(
2164 instruction->GetResolvedMethod()->GetDeclaringClass()));
2165 optimizations.SetNoReadBarrierForStringClass();
2166 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002167 }
2168 }
2169}
2170
Roland Levillain22c49222016-03-18 14:04:28 +00002171void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
2172 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002173 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002174 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01002175 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002176 HInstruction* value = invoke->InputAt(0);
2177 HInstruction* distance = invoke->InputAt(1);
2178 // Replace the invoke with an HRor.
2179 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00002180 // Unconditionally set the type of the negated distance to `int`,
2181 // as shift and rotate operations expect a 32-bit (or narrower)
2182 // value for their distance input.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002183 distance = new (GetGraph()->GetAllocator()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002184 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
2185 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002186 HRor* ror = new (GetGraph()->GetAllocator()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002187 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
2188 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01002189 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002190 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
2191 clinit->GetBlock()->RemoveInstruction(clinit);
2192 HInstruction* ldclass = clinit->InputAt(0);
2193 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
2194 ldclass->GetBlock()->RemoveInstruction(ldclass);
2195 }
2196 }
2197}
2198
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002199static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2200 if (potential_length->IsArrayLength()) {
2201 return potential_length->InputAt(0) == potential_array;
2202 }
2203
2204 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002205 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002206 }
2207
2208 return false;
2209}
2210
2211void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2212 HInstruction* source = instruction->InputAt(0);
2213 HInstruction* destination = instruction->InputAt(2);
2214 HInstruction* count = instruction->InputAt(4);
2215 SystemArrayCopyOptimizations optimizations(instruction);
2216 if (CanEnsureNotNullAt(source, instruction)) {
2217 optimizations.SetSourceIsNotNull();
2218 }
2219 if (CanEnsureNotNullAt(destination, instruction)) {
2220 optimizations.SetDestinationIsNotNull();
2221 }
2222 if (destination == source) {
2223 optimizations.SetDestinationIsSource();
2224 }
2225
2226 if (IsArrayLengthOf(count, source)) {
2227 optimizations.SetCountIsSourceLength();
2228 }
2229
2230 if (IsArrayLengthOf(count, destination)) {
2231 optimizations.SetCountIsDestinationLength();
2232 }
2233
2234 {
2235 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002236 DataType::Type source_component_type = DataType::Type::kVoid;
2237 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002238 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2239 if (destination_rti.IsValid()) {
2240 if (destination_rti.IsObjectArray()) {
2241 if (destination_rti.IsExact()) {
2242 optimizations.SetDoesNotNeedTypeCheck();
2243 }
2244 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002245 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002246 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002247 destination_component_type = DataTypeFromPrimitive(
2248 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002249 optimizations.SetDestinationIsPrimitiveArray();
2250 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2251 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002252 }
2253 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002254 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2255 if (source_rti.IsValid()) {
2256 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2257 optimizations.SetDoesNotNeedTypeCheck();
2258 }
2259 if (source_rti.IsPrimitiveArrayClass()) {
2260 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002261 source_component_type = DataTypeFromPrimitive(
2262 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002263 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2264 optimizations.SetSourceIsNonPrimitiveArray();
2265 }
2266 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002267 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002268 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002269 (source_component_type == destination_component_type)) {
2270 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2271 PointerSize image_size = class_linker->GetImagePointerSize();
2272 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2273 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2274 ArtMethod* method = nullptr;
2275 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002276 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002277 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002278 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002279 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002280 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002281 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002282 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002283 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002284 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002285 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002286 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002287 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002288 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002289 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002290 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002291 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002292 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002293 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002294 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002295 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002296 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002297 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002298 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002299 break;
2300 default:
2301 LOG(FATAL) << "Unreachable";
2302 }
2303 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002304 DCHECK(method->IsStatic());
2305 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002306 invoke->SetResolvedMethod(method);
2307 // Sharpen the new invoke. Note that we do not update the dex method index of
2308 // the invoke, as we would need to look it up in the current dex file, and it
2309 // is unlikely that it exists. The most usual situation for such typed
2310 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002311 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002312 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002313 }
2314}
2315
Roland Levillaina5c4a402016-03-15 15:02:50 +00002316void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2317 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002318 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002319 DCHECK(invoke->IsInvokeStaticOrDirect());
2320 uint32_t dex_pc = invoke->GetDexPc();
2321 HInstruction* left = invoke->InputAt(0);
2322 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002323 if (!is_signum) {
2324 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002325 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002326 right = GetGraph()->GetLongConstant(0);
2327 } else {
2328 right = GetGraph()->GetIntConstant(0);
2329 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01002330 HCompare* compare = new (GetGraph()->GetAllocator())
Aart Bika19616e2016-02-01 18:57:58 -08002331 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2332 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2333}
2334
Aart Bik75a38b22016-02-17 10:41:50 -08002335void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2336 DCHECK(invoke->IsInvokeStaticOrDirect());
2337 uint32_t dex_pc = invoke->GetDexPc();
2338 // IsNaN(x) is the same as x != x.
2339 HInstruction* x = invoke->InputAt(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002340 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002341 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002342 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2343}
2344
Aart Bik2a6aad92016-02-25 11:32:32 -08002345void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2346 DCHECK(invoke->IsInvokeStaticOrDirect());
2347 uint32_t dex_pc = invoke->GetDexPc();
2348 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002349 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002350 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2351 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002352 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002353 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2354 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2355 kNeedsEnvironmentOrCache,
2356 kNoSideEffects,
2357 kNoThrow);
2358 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002359 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002360 nan = GetGraph()->GetIntConstant(0x7fc00000);
2361 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2362 kNeedsEnvironmentOrCache,
2363 kNoSideEffects,
2364 kNoThrow);
2365 }
2366 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002367 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002368 condition->SetBias(ComparisonBias::kLtBias);
2369 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2370 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002371 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002372 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2373 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2374}
2375
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002376void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2377 HInstruction* str = invoke->InputAt(0);
2378 HInstruction* index = invoke->InputAt(1);
2379 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002380 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002381 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2382 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002383 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002384 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002385 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Vladimir Marko0259c242017-12-04 11:27:47 +00002386 index, length, dex_pc, /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002387 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002388 HArrayGet* array_get = new (allocator) HArrayGet(str,
2389 bounds_check,
2390 DataType::Type::kUint16,
2391 SideEffects::None(), // Strings are immutable.
2392 dex_pc,
2393 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002394 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2395 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2396 GetGraph()->SetHasBoundsChecks(true);
2397}
2398
Vladimir Markodce016e2016-04-28 13:10:02 +01002399void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2400 HInstruction* str = invoke->InputAt(0);
2401 uint32_t dex_pc = invoke->GetDexPc();
2402 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2403 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002404 HArrayLength* length =
Vladimir Markoca6fff82017-10-03 14:49:14 +01002405 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002406 HInstruction* replacement;
2407 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2408 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2409 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2410 HIntConstant* zero = GetGraph()->GetIntConstant(0);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002411 HEqual* equal = new (GetGraph()->GetAllocator()) HEqual(length, zero, dex_pc);
Vladimir Markodce016e2016-04-28 13:10:02 +01002412 replacement = equal;
2413 } else {
2414 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2415 replacement = length;
2416 }
2417 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2418}
2419
Aart Bikff7d89c2016-11-07 08:49:28 -08002420// This method should only be used on intrinsics whose sole way of throwing an
2421// exception is raising a NPE when the nth argument is null. If that argument
2422// is provably non-null, we can clear the flag.
2423void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2424 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002425 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002426 invoke->SetCanThrow(false);
2427 }
2428}
2429
Aart Bik71bf7b42016-11-16 10:17:46 -08002430// Methods that return "this" can replace the returned value with the receiver.
2431void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2432 if (invoke->HasUses()) {
2433 HInstruction* receiver = invoke->InputAt(0);
2434 invoke->ReplaceWith(receiver);
2435 RecordSimplification();
2436 }
2437}
2438
2439// Helper method for StringBuffer escape analysis.
2440static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2441 if (user->IsInvokeStaticOrDirect()) {
2442 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002443 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2444 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002445 user->InputAt(0) == reference;
2446 } else if (user->IsInvokeVirtual()) {
2447 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2448 case Intrinsics::kStringBufferLength:
2449 case Intrinsics::kStringBufferToString:
2450 DCHECK_EQ(user->InputAt(0), reference);
2451 return true;
2452 case Intrinsics::kStringBufferAppend:
2453 // Returns "this", so only okay if no further uses.
2454 DCHECK_EQ(user->InputAt(0), reference);
2455 DCHECK_NE(user->InputAt(1), reference);
2456 return !user->HasUses();
2457 default:
2458 break;
2459 }
2460 }
2461 return false;
2462}
2463
2464// Certain allocation intrinsics are not removed by dead code elimination
2465// because of potentially throwing an OOM exception or other side effects.
2466// This method removes such intrinsics when special circumstances allow.
2467void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2468 if (!invoke->HasUses()) {
2469 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2470 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2471 // call does not escape since only thread-local synchronization may be removed.
2472 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2473 HInstruction* receiver = invoke->InputAt(0);
2474 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2475 invoke->GetBlock()->RemoveInstruction(invoke);
2476 RecordSimplification();
2477 }
2478 }
2479}
2480
Vladimir Markoca6fff82017-10-03 14:49:14 +01002481void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke,
2482 MemBarrierKind barrier_kind) {
Aart Bik11932592016-03-08 12:42:25 -08002483 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002484 HMemoryBarrier* mem_barrier =
2485 new (GetGraph()->GetAllocator()) HMemoryBarrier(barrier_kind, dex_pc);
Aart Bik11932592016-03-08 12:42:25 -08002486 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2487}
2488
Aart Bik1f8d51b2018-02-15 10:42:37 -08002489void InstructionSimplifierVisitor::SimplifyMin(HInvoke* invoke, DataType::Type type) {
2490 DCHECK(invoke->IsInvokeStaticOrDirect());
2491 HMin* min = new (GetGraph()->GetAllocator())
2492 HMin(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2493 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, min);
2494}
2495
2496void InstructionSimplifierVisitor::SimplifyMax(HInvoke* invoke, DataType::Type type) {
2497 DCHECK(invoke->IsInvokeStaticOrDirect());
2498 HMax* max = new (GetGraph()->GetAllocator())
2499 HMax(type, invoke->InputAt(0), invoke->InputAt(1), invoke->GetDexPc());
2500 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, max);
2501}
2502
Aart Bik3dad3412018-02-28 12:01:46 -08002503void InstructionSimplifierVisitor::SimplifyAbs(HInvoke* invoke, DataType::Type type) {
2504 DCHECK(invoke->IsInvokeStaticOrDirect());
2505 HAbs* abs = new (GetGraph()->GetAllocator())
2506 HAbs(type, invoke->InputAt(0), invoke->GetDexPc());
2507 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, abs);
2508}
2509
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002510void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002511 switch (instruction->GetIntrinsic()) {
2512 case Intrinsics::kStringEquals:
2513 SimplifyStringEquals(instruction);
2514 break;
2515 case Intrinsics::kSystemArrayCopy:
2516 SimplifySystemArrayCopy(instruction);
2517 break;
2518 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002519 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002520 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002521 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002522 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002523 break;
2524 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002525 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002526 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002527 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002528 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002529 break;
2530 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002531 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002532 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002533 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002534 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002535 break;
2536 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002537 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002538 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002539 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002540 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002541 break;
2542 case Intrinsics::kFloatIsNaN:
2543 case Intrinsics::kDoubleIsNaN:
2544 SimplifyIsNaN(instruction);
2545 break;
2546 case Intrinsics::kFloatFloatToIntBits:
2547 case Intrinsics::kDoubleDoubleToLongBits:
2548 SimplifyFP2Int(instruction);
2549 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002550 case Intrinsics::kStringCharAt:
2551 SimplifyStringCharAt(instruction);
2552 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002553 case Intrinsics::kStringIsEmpty:
2554 case Intrinsics::kStringLength:
2555 SimplifyStringIsEmptyOrLength(instruction);
2556 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002557 case Intrinsics::kStringStringIndexOf:
2558 case Intrinsics::kStringStringIndexOfAfter:
2559 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2560 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002561 case Intrinsics::kStringBufferAppend:
2562 case Intrinsics::kStringBuilderAppend:
2563 SimplifyReturnThis(instruction);
2564 break;
2565 case Intrinsics::kStringBufferToString:
2566 case Intrinsics::kStringBuilderToString:
2567 SimplifyAllocationIntrinsic(instruction);
2568 break;
Aart Bik11932592016-03-08 12:42:25 -08002569 case Intrinsics::kUnsafeLoadFence:
2570 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2571 break;
2572 case Intrinsics::kUnsafeStoreFence:
2573 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2574 break;
2575 case Intrinsics::kUnsafeFullFence:
2576 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2577 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002578 case Intrinsics::kVarHandleFullFence:
2579 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2580 break;
2581 case Intrinsics::kVarHandleAcquireFence:
2582 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2583 break;
2584 case Intrinsics::kVarHandleReleaseFence:
2585 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2586 break;
2587 case Intrinsics::kVarHandleLoadLoadFence:
2588 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2589 break;
2590 case Intrinsics::kVarHandleStoreStoreFence:
2591 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2592 break;
Aart Bik1f8d51b2018-02-15 10:42:37 -08002593 case Intrinsics::kMathMinIntInt:
2594 SimplifyMin(instruction, DataType::Type::kInt32);
2595 break;
2596 case Intrinsics::kMathMinLongLong:
2597 SimplifyMin(instruction, DataType::Type::kInt64);
2598 break;
2599 case Intrinsics::kMathMinFloatFloat:
2600 SimplifyMin(instruction, DataType::Type::kFloat32);
2601 break;
2602 case Intrinsics::kMathMinDoubleDouble:
2603 SimplifyMin(instruction, DataType::Type::kFloat64);
2604 break;
2605 case Intrinsics::kMathMaxIntInt:
2606 SimplifyMax(instruction, DataType::Type::kInt32);
2607 break;
2608 case Intrinsics::kMathMaxLongLong:
2609 SimplifyMax(instruction, DataType::Type::kInt64);
2610 break;
2611 case Intrinsics::kMathMaxFloatFloat:
2612 SimplifyMax(instruction, DataType::Type::kFloat32);
2613 break;
2614 case Intrinsics::kMathMaxDoubleDouble:
2615 SimplifyMax(instruction, DataType::Type::kFloat64);
2616 break;
Aart Bik3dad3412018-02-28 12:01:46 -08002617 case Intrinsics::kMathAbsInt:
2618 SimplifyAbs(instruction, DataType::Type::kInt32);
2619 break;
2620 case Intrinsics::kMathAbsLong:
2621 SimplifyAbs(instruction, DataType::Type::kInt64);
2622 break;
2623 case Intrinsics::kMathAbsFloat:
2624 SimplifyAbs(instruction, DataType::Type::kFloat32);
2625 break;
2626 case Intrinsics::kMathAbsDouble:
2627 SimplifyAbs(instruction, DataType::Type::kFloat64);
2628 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002629 default:
2630 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002631 }
2632}
2633
Aart Bikbb245d12015-10-19 11:05:03 -07002634void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2635 HInstruction* cond = deoptimize->InputAt(0);
2636 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002637 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002638 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002639 if (deoptimize->GuardsAnInput()) {
2640 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2641 }
Aart Bikbb245d12015-10-19 11:05:03 -07002642 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2643 } else {
2644 // Always deopt.
2645 }
2646 }
2647}
2648
Anton Kirilove14dc862016-05-13 17:56:15 +01002649// Replace code looking like
2650// OP y, x, const1
2651// OP z, y, const2
2652// with
2653// OP z, x, const3
2654// where OP is both an associative and a commutative operation.
2655bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2656 HBinaryOperation* instruction) {
2657 DCHECK(instruction->IsCommutative());
2658
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002659 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002660 return false;
2661 }
2662
2663 HInstruction* left = instruction->GetLeft();
2664 HInstruction* right = instruction->GetRight();
2665 // Variable names as described above.
2666 HConstant* const2;
2667 HBinaryOperation* y;
2668
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002669 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002670 const2 = right->AsConstant();
2671 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002672 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002673 const2 = left->AsConstant();
2674 y = right->AsBinaryOperation();
2675 } else {
2676 // The node does not match the pattern.
2677 return false;
2678 }
2679
2680 // If `y` has more than one use, we do not perform the optimization
2681 // because it might increase code size (e.g. if the new constant is
2682 // no longer encodable as an immediate operand in the target ISA).
2683 if (!y->HasOnlyOneNonEnvironmentUse()) {
2684 return false;
2685 }
2686
2687 // GetConstantRight() can return both left and right constants
2688 // for commutative operations.
2689 HConstant* const1 = y->GetConstantRight();
2690 if (const1 == nullptr) {
2691 return false;
2692 }
2693
2694 instruction->ReplaceInput(const1, 0);
2695 instruction->ReplaceInput(const2, 1);
2696 HConstant* const3 = instruction->TryStaticEvaluation();
2697 DCHECK(const3 != nullptr);
2698 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2699 instruction->ReplaceInput(const3, 1);
2700 RecordSimplification();
2701 return true;
2702}
2703
2704static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2705 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2706}
2707
2708// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002709static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002710 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002711 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002712 return HAdd::Compute<int32_t>(x, y);
2713 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002714 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002715 return HAdd::Compute<int64_t>(x, y);
2716 }
2717}
2718
2719// Helper function that handles the child classes of HConstant
2720// and returns an integer with the appropriate sign.
2721static int64_t GetValue(HConstant* constant, bool is_negated) {
2722 int64_t ret = Int64FromConstant(constant);
2723 return is_negated ? -ret : ret;
2724}
2725
2726// Replace code looking like
2727// OP1 y, x, const1
2728// OP2 z, y, const2
2729// with
2730// OP3 z, x, const3
2731// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2732bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2733 HBinaryOperation* instruction) {
2734 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2735
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002736 DataType::Type type = instruction->GetType();
2737 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002738 return false;
2739 }
2740
2741 HInstruction* left = instruction->GetLeft();
2742 HInstruction* right = instruction->GetRight();
2743 // Variable names as described above.
2744 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2745 if (const2 == nullptr) {
2746 return false;
2747 }
2748
2749 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2750 ? left->AsBinaryOperation()
2751 : AsAddOrSub(right);
2752 // If y has more than one use, we do not perform the optimization because
2753 // it might increase code size (e.g. if the new constant is no longer
2754 // encodable as an immediate operand in the target ISA).
2755 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2756 return false;
2757 }
2758
2759 left = y->GetLeft();
2760 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2761 if (const1 == nullptr) {
2762 return false;
2763 }
2764
2765 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2766 // If both inputs are constants, let the constant folding pass deal with it.
2767 if (x->IsConstant()) {
2768 return false;
2769 }
2770
2771 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2772 int64_t const2_val = GetValue(const2, is_const2_negated);
2773 bool is_y_negated = (y == right) && instruction->IsSub();
2774 right = y->GetRight();
2775 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2776 int64_t const1_val = GetValue(const1, is_const1_negated);
2777 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2778 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2779 HBasicBlock* block = instruction->GetBlock();
2780 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002781 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002782 HInstruction* z;
2783
2784 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002785 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002786 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002787 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002788 }
2789
2790 block->ReplaceAndRemoveInstructionWith(instruction, z);
2791 RecordSimplification();
2792 return true;
2793}
2794
Lena Djokicbc5460b2017-07-20 16:07:36 +02002795void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2796 if (TryCombineVecMultiplyAccumulate(instruction)) {
2797 RecordSimplification();
2798 }
2799}
2800
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002801} // namespace art