blob: 8e0b4145e30ab11397c3c55fad992e251caad181 [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"
Vladimir Marko552a1342017-10-31 10:56:47 +000028#include "string_builder_append.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000029
Vladimir Marko0a516052019-10-14 13:00:44 +000030namespace art {
Nicolas Geoffray3c049742014-09-24 18:10:46 +010031
Artem Serovcced8ba2017-07-19 18:18:09 +010032// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
33// is replaced with its copy if it is clonable.
34static constexpr bool kTestInstructionClonerExhaustively = false;
35
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010036class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000037 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000038 InstructionSimplifierVisitor(HGraph* graph,
39 CodeGenerator* codegen,
40 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010041 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000042 codegen_(codegen),
Alexandre Rames188d4312015-04-09 18:30:21 +010043 stats_(stats) {}
44
Aart Bik24773202018-04-26 10:28:51 -070045 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000046
47 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010048 void RecordSimplification() {
49 simplification_occurred_ = true;
50 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000051 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010052 }
53
Scott Wakeling40a04bf2015-12-11 09:50:36 +000054 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55 bool TryReplaceWithRotate(HBinaryOperation* instruction);
56 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
57 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
58 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
59
Alexandre Rames188d4312015-04-09 18:30:21 +010060 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000061 // `op` should be either HOr or HAnd.
62 // De Morgan's laws:
63 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
64 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010065 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
66 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020067 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010068
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000069 void VisitShift(HBinaryOperation* shift);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010070 void VisitEqual(HEqual* equal) override;
71 void VisitNotEqual(HNotEqual* equal) override;
72 void VisitBooleanNot(HBooleanNot* bool_not) override;
73 void VisitInstanceFieldSet(HInstanceFieldSet* equal) override;
74 void VisitStaticFieldSet(HStaticFieldSet* equal) override;
75 void VisitArraySet(HArraySet* equal) override;
76 void VisitTypeConversion(HTypeConversion* instruction) override;
77 void VisitNullCheck(HNullCheck* instruction) override;
78 void VisitArrayLength(HArrayLength* instruction) override;
79 void VisitCheckCast(HCheckCast* instruction) override;
80 void VisitAbs(HAbs* instruction) override;
81 void VisitAdd(HAdd* instruction) override;
82 void VisitAnd(HAnd* instruction) override;
83 void VisitCondition(HCondition* instruction) override;
84 void VisitGreaterThan(HGreaterThan* condition) override;
85 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) override;
86 void VisitLessThan(HLessThan* condition) override;
87 void VisitLessThanOrEqual(HLessThanOrEqual* condition) override;
88 void VisitBelow(HBelow* condition) override;
89 void VisitBelowOrEqual(HBelowOrEqual* condition) override;
90 void VisitAbove(HAbove* condition) override;
91 void VisitAboveOrEqual(HAboveOrEqual* condition) override;
92 void VisitDiv(HDiv* instruction) override;
93 void VisitMul(HMul* instruction) override;
94 void VisitNeg(HNeg* instruction) override;
95 void VisitNot(HNot* instruction) override;
96 void VisitOr(HOr* instruction) override;
97 void VisitShl(HShl* instruction) override;
98 void VisitShr(HShr* instruction) override;
99 void VisitSub(HSub* instruction) override;
100 void VisitUShr(HUShr* instruction) override;
101 void VisitXor(HXor* instruction) override;
102 void VisitSelect(HSelect* select) override;
103 void VisitIf(HIf* instruction) override;
104 void VisitInstanceOf(HInstanceOf* instruction) override;
105 void VisitInvoke(HInvoke* invoke) override;
106 void VisitDeoptimize(HDeoptimize* deoptimize) override;
107 void VisitVecMul(HVecMul* instruction) override;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100108
109 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000110
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100111 void SimplifySystemArrayCopy(HInvoke* invoke);
112 void SimplifyStringEquals(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800113 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100114 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Marko5f846072020-04-09 13:20:11 +0100115 void SimplifyStringLength(HInvoke* invoke);
Vladimir Marko6fa44042018-03-19 18:42:49 +0000116 void SimplifyStringIndexOf(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800117 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800118 void SimplifyReturnThis(HInvoke* invoke);
119 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100120
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000121 CodeGenerator* codegen_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000122 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 bool simplification_occurred_ = false;
124 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700125 // We ensure we do not loop infinitely. The value should not be too high, since that
126 // would allow looping around the same basic block too many times. The value should
127 // not be too low either, however, since we want to allow revisiting a basic block
128 // with many statements and simplifications at least once.
129 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000130};
131
Aart Bik24773202018-04-26 10:28:51 -0700132bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100133 if (kTestInstructionClonerExhaustively) {
134 CloneAndReplaceInstructionVisitor visitor(graph_);
135 visitor.VisitReversePostOrder();
136 }
137
Vladimir Markobb089b62018-06-28 17:30:16 +0100138 InstructionSimplifierVisitor visitor(graph_, codegen_, stats_);
Aart Bik24773202018-04-26 10:28:51 -0700139 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100140}
141
Aart Bik24773202018-04-26 10:28:51 -0700142bool InstructionSimplifierVisitor::Run() {
143 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100144 // Iterate in reverse post order to open up more simplifications to users
145 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100146 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100147 // The simplification of an instruction to another instruction may yield
148 // possibilities for other simplifications. So although we perform a reverse
149 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100150 do {
151 simplification_occurred_ = false;
152 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700153 if (simplification_occurred_) {
154 didSimplify = true;
155 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100156 } while (simplification_occurred_ &&
157 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100158 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100159 }
Aart Bik24773202018-04-26 10:28:51 -0700160 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100161}
162
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000163namespace {
164
165bool AreAllBitsSet(HConstant* constant) {
166 return Int64FromConstant(constant) == -1;
167}
168
169} // namespace
170
Alexandre Rames188d4312015-04-09 18:30:21 +0100171// Returns true if the code was simplified to use only one negation operation
172// after the binary operation instead of one on each of the inputs.
173bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
174 DCHECK(binop->IsAdd() || binop->IsSub());
175 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
176 HNeg* left_neg = binop->GetLeft()->AsNeg();
177 HNeg* right_neg = binop->GetRight()->AsNeg();
178 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
179 !right_neg->HasOnlyOneNonEnvironmentUse()) {
180 return false;
181 }
182 // Replace code looking like
183 // NEG tmp1, a
184 // NEG tmp2, b
185 // ADD dst, tmp1, tmp2
186 // with
187 // ADD tmp, a, b
188 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600189 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
190 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
191 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100192 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600193 return false;
194 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100195 binop->ReplaceInput(left_neg->GetInput(), 0);
196 binop->ReplaceInput(right_neg->GetInput(), 1);
197 left_neg->GetBlock()->RemoveInstruction(left_neg);
198 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100199 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100200 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
201 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
202 RecordSimplification();
203 return true;
204}
205
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000206bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
207 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100208 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000209 HInstruction* left = op->GetLeft();
210 HInstruction* right = op->GetRight();
211
212 // We can apply De Morgan's laws if both inputs are Not's and are only used
213 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000214 if (((left->IsNot() && right->IsNot()) ||
215 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000216 left->HasOnlyOneNonEnvironmentUse() &&
217 right->HasOnlyOneNonEnvironmentUse()) {
218 // Replace code looking like
219 // NOT nota, a
220 // NOT notb, b
221 // AND dst, nota, notb (respectively OR)
222 // with
223 // OR or, a, b (respectively AND)
224 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000225 HInstruction* src_left = left->InputAt(0);
226 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000227 uint32_t dex_pc = op->GetDexPc();
228
229 // Remove the negations on the inputs.
230 left->ReplaceWith(src_left);
231 right->ReplaceWith(src_right);
232 left->GetBlock()->RemoveInstruction(left);
233 right->GetBlock()->RemoveInstruction(right);
234
235 // Replace the `HAnd` or `HOr`.
236 HBinaryOperation* hbin;
237 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100238 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000239 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100240 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000241 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000242 HInstruction* hnot;
243 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100244 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000245 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100246 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000247 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000248
249 op->GetBlock()->InsertInstructionBefore(hbin, op);
250 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
251
252 RecordSimplification();
253 return true;
254 }
255
256 return false;
257}
258
Lena Djokicbc5460b2017-07-20 16:07:36 +0200259bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100260 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200261 InstructionSet isa = codegen_->GetInstructionSet();
262 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000263 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100264 if (!(type == DataType::Type::kUint8 ||
265 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 type == DataType::Type::kUint16 ||
267 type == DataType::Type::kInt16 ||
268 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200269 return false;
270 }
271 break;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200272 default:
273 return false;
274 }
275
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100276 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200277
278 if (mul->HasOnlyOneNonEnvironmentUse()) {
279 HInstruction* use = mul->GetUses().front().GetUser();
280 if (use->IsVecAdd() || use->IsVecSub()) {
281 // Replace code looking like
282 // VECMUL tmp, x, y
283 // VECADD/SUB dst, acc, tmp
284 // with
285 // VECMULACC dst, acc, x, y
286 // Note that we do not want to (unconditionally) perform the merge when the
287 // multiplication has multiple uses and it can be merged in all of them.
288 // Multiple uses could happen on the same control-flow path, and we would
289 // then increase the amount of work. In the future we could try to evaluate
290 // whether all uses are on different control-flow paths (using dominance and
291 // reverse-dominance information) and only perform the merge when they are.
292 HInstruction* accumulator = nullptr;
293 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
294 HInstruction* binop_left = binop->GetLeft();
295 HInstruction* binop_right = binop->GetRight();
296 // This is always true since the `HVecMul` has only one use (which is checked above).
297 DCHECK_NE(binop_left, binop_right);
298 if (binop_right == mul) {
299 accumulator = binop_left;
300 } else if (use->IsVecAdd()) {
301 DCHECK_EQ(binop_left, mul);
302 accumulator = binop_right;
303 }
304
305 HInstruction::InstructionKind kind =
306 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
307 if (accumulator != nullptr) {
308 HVecMultiplyAccumulate* mulacc =
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100309 new (allocator) HVecMultiplyAccumulate(allocator,
310 kind,
311 accumulator,
312 mul->GetLeft(),
313 mul->GetRight(),
314 binop->GetPackedType(),
315 binop->GetVectorLength(),
316 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200317
318 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
319 DCHECK(!mul->HasUses());
320 mul->GetBlock()->RemoveInstruction(mul);
321 return true;
322 }
323 }
324 }
325
326 return false;
327}
328
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000329void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
330 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100331 HInstruction* shift_amount = instruction->GetRight();
332 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000333
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100334 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100335 ? kMaxLongShiftDistance
336 : kMaxIntShiftDistance;
337
338 if (shift_amount->IsConstant()) {
339 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700340 int64_t masked_cst = cst & implicit_mask;
341 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400342 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100343 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400344 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100345 // value
346 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400347 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100348 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100349 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700350 } else if (masked_cst != cst) {
351 // Replace code looking like
352 // SHL dst, value, cst
353 // where cst exceeds maximum distance with the equivalent
354 // SHL dst, value, cst & implicit_mask
355 // (as defined by shift semantics). This ensures other
356 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100357 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Andreas Gampe3db70682018-12-26 15:12:03 -0800358 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index= */ 1);
Aart Bik50e20d52017-05-05 14:07:29 -0700359 RecordSimplification();
360 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100361 }
362 }
363
364 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100365 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
366 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100367 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100368 // AND adjusted_shift, shift, <superset of implicit mask>
369 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
370 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
371 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100372 // with
373 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100374 if (shift_amount->IsAnd() ||
375 shift_amount->IsOr() ||
376 shift_amount->IsXor() ||
377 shift_amount->IsAdd() ||
378 shift_amount->IsSub()) {
379 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
380 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
381 HConstant* mask = bin_op->GetConstantRight();
382 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
383 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100384 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100385 return;
386 }
387 } else if (shift_amount->IsTypeConversion()) {
388 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
389 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
390 // Non-integral and 64-bit source types require an explicit type conversion.
391 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
392 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
393 RecordSimplification();
394 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400395 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000396 }
397}
398
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000399static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
400 return (sub->GetRight() == other &&
401 sub->GetLeft()->IsConstant() &&
402 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
403}
404
405bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
406 HUShr* ushr,
407 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000408 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100409 HRor* ror =
410 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000411 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
412 if (!ushr->HasUses()) {
413 ushr->GetBlock()->RemoveInstruction(ushr);
414 }
415 if (!ushr->GetRight()->HasUses()) {
416 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
417 }
418 if (!shl->HasUses()) {
419 shl->GetBlock()->RemoveInstruction(shl);
420 }
421 if (!shl->GetRight()->HasUses()) {
422 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
423 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100424 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000425 return true;
426}
427
428// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
429bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000430 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
431 HInstruction* left = op->GetLeft();
432 HInstruction* right = op->GetRight();
433 // If we have an UShr and a Shl (in either order).
434 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
435 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
436 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100437 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000438 if (ushr->GetType() == shl->GetType() &&
439 ushr->GetLeft() == shl->GetLeft()) {
440 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
441 // Shift distances are both constant, try replacing with Ror if they
442 // add up to the register size.
443 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
444 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
445 // Shift distances are potentially of the form x and (reg_size - x).
446 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
447 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
448 // Shift distances are potentially of the form d and -d.
449 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
450 }
451 }
452 }
453 return false;
454}
455
456// Try replacing code looking like (x >>> #rdist OP x << #ldist):
457// UShr dst, x, #rdist
458// Shl tmp, x, #ldist
459// OP dst, dst, tmp
460// or like (x >>> #rdist OP x << #-ldist):
461// UShr dst, x, #rdist
462// Shl tmp, x, #-ldist
463// OP dst, dst, tmp
464// with
465// Ror dst, x, #rdist
466bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
467 HUShr* ushr,
468 HShl* shl) {
469 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100470 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000471 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
472 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
473 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
474 ReplaceRotateWithRor(op, ushr, shl);
475 return true;
476 }
477 return false;
478}
479
480// Replace code looking like (x >>> -d OP x << d):
481// Neg neg, d
482// UShr dst, x, neg
483// Shl tmp, x, d
484// OP dst, dst, tmp
485// with
486// Neg neg, d
487// Ror dst, x, neg
488// *** OR ***
489// Replace code looking like (x >>> d OP x << -d):
490// UShr dst, x, d
491// Neg neg, d
492// Shl tmp, x, neg
493// OP dst, dst, tmp
494// with
495// Ror dst, x, d
496bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
497 HUShr* ushr,
498 HShl* shl) {
499 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
500 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
501 bool neg_is_left = shl->GetRight()->IsNeg();
502 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
503 // And the shift distance being negated is the distance being shifted the other way.
504 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
505 ReplaceRotateWithRor(op, ushr, shl);
506 }
507 return false;
508}
509
510// Try replacing code looking like (x >>> d OP x << (#bits - d)):
511// UShr dst, x, d
512// Sub ld, #bits, d
513// Shl tmp, x, ld
514// OP dst, dst, tmp
515// with
516// Ror dst, x, d
517// *** OR ***
518// Replace code looking like (x >>> (#bits - d) OP x << d):
519// Sub rd, #bits, d
520// UShr dst, x, rd
521// Shl tmp, x, d
522// OP dst, dst, tmp
523// with
524// Neg neg, d
525// Ror dst, x, neg
526bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
527 HUShr* ushr,
528 HShl* shl) {
529 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
530 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100531 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000532 HInstruction* shl_shift = shl->GetRight();
533 HInstruction* ushr_shift = ushr->GetRight();
534 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
535 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
536 return ReplaceRotateWithRor(op, ushr, shl);
537 }
538 return false;
539}
540
Calin Juravle10e244f2015-01-26 18:54:32 +0000541void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
542 HInstruction* obj = null_check->InputAt(0);
543 if (!obj->CanBeNull()) {
544 null_check->ReplaceWith(obj);
545 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000546 if (stats_ != nullptr) {
547 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
548 }
549 }
550}
551
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100552bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
553 if (!input->CanBeNull()) {
554 return true;
555 }
556
Vladimir Marko46817b82016-03-29 12:21:58 +0100557 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
558 HInstruction* user = use.GetUser();
559 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100560 return true;
561 }
562 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100563
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100564 return false;
565}
566
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100567// Returns whether doing a type test between the class of `object` against `klass` has
568// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000569static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
570 HInstruction* object,
571 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000572 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
573 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
574 ScopedObjectAccess soa(Thread::Current());
575 if (!obj_rti.IsValid()) {
576 // We run the simplifier before the reference type propagation so type info might not be
577 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100578 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000579 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100580
Calin Juravle98893e12015-10-02 21:05:03 +0100581 if (!class_rti.IsValid()) {
582 // Happens when the loaded class is unresolved.
583 return false;
584 }
585 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000586 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100587 *outcome = true;
588 return true;
589 } else if (obj_rti.IsExact()) {
590 // The test failed at compile time so will also fail at runtime.
591 *outcome = false;
592 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100593 } else if (!class_rti.IsInterface()
594 && !obj_rti.IsInterface()
595 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100596 // Different type hierarchy. The test will fail.
597 *outcome = false;
598 return true;
599 }
600 return false;
601}
602
603void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
604 HInstruction* object = check_cast->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000605 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
606 check_cast->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100607 // If we need to perform an access check we cannot remove the instruction.
608 return;
609 }
610
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100611 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100612 check_cast->ClearMustDoNullCheck();
613 }
614
615 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000616 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700617 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100618 return;
619 }
620
Roland Levillain05e34f42018-05-24 13:19:05 +0000621 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
622 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000623 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000624 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100625 if (outcome) {
626 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700627 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000628 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
629 HLoadClass* load_class = check_cast->GetTargetClass();
630 if (!load_class->HasUses()) {
631 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
632 // However, here we know that it cannot because the checkcast was successfull, hence
633 // the class was already loaded.
634 load_class->GetBlock()->RemoveInstruction(load_class);
635 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700636 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100637 } else {
638 // Don't do anything for exceptional cases for now. Ideally we should remove
639 // all instructions and blocks this instruction dominates.
640 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000641 }
642}
643
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100644void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100645 HInstruction* object = instruction->InputAt(0);
Vladimir Marko175e7862018-03-27 09:03:13 +0000646 if (instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck &&
647 instruction->GetTargetClass()->NeedsAccessCheck()) {
Calin Juravlee53fb552015-10-07 17:51:52 +0100648 // If we need to perform an access check we cannot remove the instruction.
649 return;
650 }
651
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100652 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100653 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100654 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100655 instruction->ClearMustDoNullCheck();
656 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100657
658 HGraph* graph = GetGraph();
659 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000660 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100661 instruction->ReplaceWith(graph->GetIntConstant(0));
662 instruction->GetBlock()->RemoveInstruction(instruction);
663 RecordSimplification();
664 return;
665 }
666
Roland Levillain05e34f42018-05-24 13:19:05 +0000667 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
668 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000669 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000670 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000671 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100672 if (outcome && can_be_null) {
673 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100674 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100675 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
676 instruction->ReplaceWith(test);
677 } else {
678 // We've statically determined the result of the instanceof.
679 instruction->ReplaceWith(graph->GetIntConstant(outcome));
680 }
681 RecordSimplification();
682 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000683 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
684 HLoadClass* load_class = instruction->GetTargetClass();
685 if (!load_class->HasUses()) {
686 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
687 // However, here we know that it cannot because the instanceof check was successfull, hence
688 // the class was already loaded.
689 load_class->GetBlock()->RemoveInstruction(load_class);
690 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700691 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100692 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100693}
694
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100695void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100696 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100697 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100698 instruction->ClearValueCanBeNull();
699 }
700}
701
702void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100703 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100704 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100705 instruction->ClearValueCanBeNull();
706 }
707}
708
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100709static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600710 HInstruction *lhs = cond->InputAt(0);
711 HInstruction *rhs = cond->InputAt(1);
712 switch (cond->GetKind()) {
713 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100714 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600715 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100716 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600717 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100718 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600719 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100720 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600721 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100722 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600723 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100724 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600725 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100726 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600727 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100728 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600729 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100730 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600731 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100732 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600733 default:
734 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -0800735 UNREACHABLE();
Anton Shaminbdd79352016-02-15 12:48:36 +0600736 }
Anton Shaminbdd79352016-02-15 12:48:36 +0600737}
738
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000739void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100740 HInstruction* input_const = equal->GetConstantRight();
741 if (input_const != nullptr) {
742 HInstruction* input_value = equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100743 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100744 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100745 // We are comparing the boolean to a constant which is of type int and can
746 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000747 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100748 // Replace (bool_value == true) with bool_value
749 equal->ReplaceWith(input_value);
750 block->RemoveInstruction(equal);
751 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000752 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700753 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500754 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
755 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100756 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100757 } else {
758 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
759 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
760 block->RemoveInstruction(equal);
761 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100762 }
Mark Mendellc4701932015-04-10 13:18:51 -0400763 } else {
764 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100765 }
Mark Mendellc4701932015-04-10 13:18:51 -0400766 } else {
767 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100768 }
769}
770
David Brazdil0d13fee2015-04-17 14:52:19 +0100771void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
772 HInstruction* input_const = not_equal->GetConstantRight();
773 if (input_const != nullptr) {
774 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100775 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100776 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100777 // We are comparing the boolean to a constant which is of type int and can
778 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000779 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700780 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500781 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
782 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100783 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000784 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100785 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100786 not_equal->ReplaceWith(input_value);
787 block->RemoveInstruction(not_equal);
788 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100789 } else {
790 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
791 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
792 block->RemoveInstruction(not_equal);
793 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100794 }
Mark Mendellc4701932015-04-10 13:18:51 -0400795 } else {
796 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100797 }
Mark Mendellc4701932015-04-10 13:18:51 -0400798 } else {
799 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100800 }
801}
802
803void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000804 HInstruction* input = bool_not->InputAt(0);
805 HInstruction* replace_with = nullptr;
806
807 if (input->IsIntConstant()) {
808 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000809 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000810 replace_with = GetGraph()->GetIntConstant(0);
811 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000812 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000813 replace_with = GetGraph()->GetIntConstant(1);
814 }
815 } else if (input->IsBooleanNot()) {
816 // Replace (!(!bool_value)) with bool_value.
817 replace_with = input->InputAt(0);
818 } else if (input->IsCondition() &&
819 // Don't change FP compares. The definition of compares involving
820 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100821 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000822 // Replace condition with its opposite.
823 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
824 }
825
826 if (replace_with != nullptr) {
827 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100828 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000829 RecordSimplification();
830 }
831}
832
Aart Bik4f7dd342017-09-12 13:12:57 -0700833// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100834static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
835 HInstruction* x,
836 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700837 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800838 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700839 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800840 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
841 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700842}
843
Aart Bik142b9132018-03-14 15:12:59 -0700844// Constructs a new MIN/MAX(x, y) node in the HIR.
845static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
846 HInstruction* x,
847 HInstruction* y,
848 HInstruction* cursor,
849 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700850 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700851 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
852 HBinaryOperation* minmax = nullptr;
853 if (is_min) {
854 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
855 } else {
856 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
857 }
858 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
859 return minmax;
860}
861
Aart Bik4f7dd342017-09-12 13:12:57 -0700862// Returns true if operands a and b consists of widening type conversions
863// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100864static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700865 if (a->IsTypeConversion() && a->GetType() == to_type) {
866 a = a->InputAt(0);
867 }
868 if (b->IsTypeConversion() && b->GetType() == to_type) {
869 b = b->InputAt(0);
870 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100871 DataType::Type type1 = a->GetType();
872 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100873 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
874 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
875 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
876 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
877 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100878 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700879}
880
Aart Bik1d746de2018-03-28 16:30:02 -0700881// Returns an acceptable substitution for "a" on the select
882// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
883static HInstruction* AllowInMinMax(IfCondition cmp,
884 HInstruction* a,
885 HInstruction* b,
886 HInstruction* c) {
887 int64_t value = 0;
888 if (IsInt64AndGet(b, /*out*/ &value) &&
889 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
890 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
891 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
892 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
893 int64_t other_value = Int64FromConstant(other);
894 bool is_max = (cmp == kCondLT || cmp == kCondLE);
895 // Allow the max for a < 100 ? max(a, -100) : ..
896 // or the min for a > -100 ? min(a, 100) : ..
897 if (is_max ? (value >= other_value) : (value <= other_value)) {
898 return c;
899 }
900 }
901 }
902 return nullptr;
903}
904
David Brazdil74eb1b22015-12-14 11:44:01 +0000905void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
906 HInstruction* replace_with = nullptr;
907 HInstruction* condition = select->GetCondition();
908 HInstruction* true_value = select->GetTrueValue();
909 HInstruction* false_value = select->GetFalseValue();
910
911 if (condition->IsBooleanNot()) {
912 // Change ((!cond) ? x : y) to (cond ? y : x).
913 condition = condition->InputAt(0);
914 std::swap(true_value, false_value);
915 select->ReplaceInput(false_value, 0);
916 select->ReplaceInput(true_value, 1);
917 select->ReplaceInput(condition, 2);
918 RecordSimplification();
919 }
920
921 if (true_value == false_value) {
922 // Replace (cond ? x : x) with (x).
923 replace_with = true_value;
924 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000925 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000926 // Replace (true ? x : y) with (x).
927 replace_with = true_value;
928 } else {
929 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000930 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000931 replace_with = false_value;
932 }
933 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000934 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000935 // Replace (cond ? true : false) with (cond).
936 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000937 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000938 // Replace (cond ? false : true) with (!cond).
939 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
940 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700941 } else if (condition->IsCondition()) {
942 IfCondition cmp = condition->AsCondition()->GetCondition();
943 HInstruction* a = condition->InputAt(0);
944 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100945 DataType::Type t_type = true_value->GetType();
946 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700947 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -0700948 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
949 // type will be int or long, like the condition). Replacements are general,
950 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -0700951 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700952 // Allow a < 100 ? max(a, -100) : ..
953 // or a > -100 ? min(a, 100) : ..
954 // to use min/max instead of a to detect nested min/max expressions.
955 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
956 if (new_a != nullptr) {
957 a = new_a;
958 }
Aart Bik142b9132018-03-14 15:12:59 -0700959 // Try to replace typical integral MIN/MAX/ABS constructs.
960 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
961 ((a == true_value && b == false_value) ||
962 (b == true_value && a == false_value))) {
963 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
964 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
965 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
966 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -0700967 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
968 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
969 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
970 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
971 HInstruction* not_negated = negLeft ? false_value : true_value;
972 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
973 // Found a < 0 ? -a : a
974 // or a > 0 ? a : -a
975 // which can be replaced by ABS(a).
976 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700977 }
978 } else if (true_value->IsSub() && false_value->IsSub()) {
979 HInstruction* true_sub1 = true_value->InputAt(0);
980 HInstruction* true_sub2 = true_value->InputAt(1);
981 HInstruction* false_sub1 = false_value->InputAt(0);
982 HInstruction* false_sub2 = false_value->InputAt(1);
983 if ((((cmp == kCondGT || cmp == kCondGE) &&
984 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
985 ((cmp == kCondLT || cmp == kCondLE) &&
986 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
987 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -0700988 // Found a > b ? a - b : b - a
989 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -0700990 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100991 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -0700992 }
993 }
994 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000995 }
996
997 if (replace_with != nullptr) {
998 select->ReplaceWith(replace_with);
999 select->GetBlock()->RemoveInstruction(select);
1000 RecordSimplification();
1001 }
1002}
1003
1004void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1005 HInstruction* condition = instruction->InputAt(0);
1006 if (condition->IsBooleanNot()) {
1007 // Swap successors if input is negated.
1008 instruction->ReplaceInput(condition->InputAt(0), 0);
1009 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001010 RecordSimplification();
1011 }
1012}
1013
Mingyao Yang0304e182015-01-30 16:41:29 -08001014void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1015 HInstruction* input = instruction->InputAt(0);
1016 // If the array is a NewArray with constant size, replace the array length
1017 // with the constant instruction. This helps the bounds check elimination phase.
1018 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001019 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001020 if (input->IsIntConstant()) {
1021 instruction->ReplaceWith(input);
1022 }
1023 }
1024}
1025
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001026void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001027 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001028 if (value->GetType() != DataType::Type::kReference) {
1029 return;
1030 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001031
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001032 if (CanEnsureNotNullAt(value, instruction)) {
1033 instruction->ClearValueCanBeNull();
1034 }
1035
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001036 if (value->IsArrayGet()) {
1037 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1038 // If the code is just swapping elements in the array, no need for a type check.
1039 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001040 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001041 }
1042 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001043
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001044 if (value->IsNullConstant()) {
1045 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001046 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001047 }
1048
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001049 ScopedObjectAccess soa(Thread::Current());
1050 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1051 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1052 if (!array_rti.IsValid()) {
1053 return;
1054 }
1055
1056 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1057 instruction->ClearNeedsTypeCheck();
1058 return;
1059 }
1060
1061 if (array_rti.IsObjectArray()) {
1062 if (array_rti.IsExact()) {
1063 instruction->ClearNeedsTypeCheck();
1064 return;
1065 }
1066 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001067 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001068}
1069
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001070static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001071 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1072 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1073 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001074 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001075 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001076 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1077 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001078 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001079 return DataType::Size(result_type) > DataType::Size(input_type) &&
1080 result_type != DataType::Type::kUint16 &&
1081 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001082}
1083
Vladimir Marko61b92282017-10-11 13:23:17 +01001084static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1085 if (maybe_get->IsInstanceFieldGet()) {
1086 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1087 return true;
1088 } else if (maybe_get->IsStaticFieldGet()) {
1089 maybe_get->AsStaticFieldGet()->SetType(new_type);
1090 return true;
1091 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1092 maybe_get->AsArrayGet()->SetType(new_type);
1093 return true;
1094 } else {
1095 return false;
1096 }
1097}
1098
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001099// The type conversion is only used for storing into a field/element of the
1100// same/narrower size.
1101static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1102 if (type_conversion->HasEnvironmentUses()) {
1103 return false;
1104 }
1105 DataType::Type input_type = type_conversion->GetInputType();
1106 DataType::Type result_type = type_conversion->GetResultType();
1107 if (!DataType::IsIntegralType(input_type) ||
1108 !DataType::IsIntegralType(result_type) ||
1109 input_type == DataType::Type::kInt64 ||
1110 result_type == DataType::Type::kInt64) {
1111 // Type conversion is needed if non-integer types are involved, or 64-bit
1112 // types are involved, which may use different number of registers.
1113 return false;
1114 }
1115 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1116 // Type conversion is not necessary when storing to a field/element of the
1117 // same/smaller size.
1118 } else {
1119 // We do not handle this case here.
1120 return false;
1121 }
1122
1123 // Check if the converted value is only used for storing into heap.
1124 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1125 HInstruction* instruction = use.GetUser();
1126 if (instruction->IsInstanceFieldSet() &&
1127 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1128 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1129 continue;
1130 }
1131 if (instruction->IsStaticFieldSet() &&
1132 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1133 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1134 continue;
1135 }
1136 if (instruction->IsArraySet() &&
1137 instruction->AsArraySet()->GetComponentType() == result_type &&
1138 // not index use.
1139 instruction->AsArraySet()->GetIndex() != type_conversion) {
1140 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1141 continue;
1142 }
1143 // The use is not as a store value, or the field/element type is not the
1144 // same as the result_type, keep the type conversion.
1145 return false;
1146 }
1147 // Codegen automatically handles the type conversion during the store.
1148 return true;
1149}
1150
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001151void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001152 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001153 DataType::Type input_type = input->GetType();
1154 DataType::Type result_type = instruction->GetResultType();
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001155 if (instruction->IsImplicitConversion()) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001156 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001157 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001158 RecordSimplification();
1159 return;
1160 }
1161
1162 if (input->IsTypeConversion()) {
1163 HTypeConversion* input_conversion = input->AsTypeConversion();
1164 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001165 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001166
1167 // When the first conversion is lossless, a direct conversion from the original type
1168 // to the final type yields the same result, even for a lossy second conversion, for
1169 // example float->double->int or int->double->float.
1170 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1171
1172 // For integral conversions, see if the first conversion loses only bits that the second
1173 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1174 // conversion yields the same result, for example long->int->short or int->char->short.
1175 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001176 DataType::IsIntegralType(input_type) &&
1177 DataType::IsIntegralType(original_type) &&
1178 DataType::IsIntegralType(result_type) &&
1179 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001180
1181 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1182 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001183 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001184 instruction->ReplaceWith(original_input);
1185 instruction->GetBlock()->RemoveInstruction(instruction);
1186 if (!input_conversion->HasUses()) {
1187 // Don't wait for DCE.
1188 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1189 }
1190 RecordSimplification();
1191 return;
1192 }
1193 // Otherwise simplify only if the first conversion has no other use.
1194 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1195 input_conversion->ReplaceWith(original_input);
1196 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1197 RecordSimplification();
1198 return;
1199 }
1200 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001201 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1202 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001203 HAnd* input_and = input->AsAnd();
1204 HConstant* constant = input_and->GetConstantRight();
1205 if (constant != nullptr) {
1206 int64_t value = Int64FromConstant(constant);
1207 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1208 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001209 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001210 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001211 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001212 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001213 instruction->ReplaceWith(original_input);
1214 instruction->GetBlock()->RemoveInstruction(instruction);
1215 RecordSimplification();
1216 return;
1217 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1218 input_and->ReplaceWith(original_input);
1219 input_and->GetBlock()->RemoveInstruction(input_and);
1220 RecordSimplification();
1221 return;
1222 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001223 }
1224 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001225 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1226 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1227 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1228 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1229 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1230 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1231 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1232 instruction->ReplaceWith(input);
1233 instruction->GetBlock()->RemoveInstruction(instruction);
1234 RecordSimplification();
1235 return;
1236 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001237 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001238
1239 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1240 instruction->ReplaceWith(input);
1241 instruction->GetBlock()->RemoveInstruction(instruction);
1242 RecordSimplification();
1243 return;
1244 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001245}
1246
Aart Bikc6eec4b2018-03-29 17:22:00 -07001247void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1248 HInstruction* input = instruction->GetInput();
1249 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1250 // Zero extension from narrow to wide can never set sign bit in the wider
1251 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1252 instruction->ReplaceWith(input);
1253 instruction->GetBlock()->RemoveInstruction(instruction);
1254 RecordSimplification();
1255 }
1256}
1257
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001258void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1259 HConstant* input_cst = instruction->GetConstantRight();
1260 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001261 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001262 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001263 // Replace code looking like
1264 // ADD dst, src, 0
1265 // with
1266 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001267 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1268 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1269 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001270 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001271 instruction->ReplaceWith(input_other);
1272 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001273 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001274 return;
1275 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001276 }
1277
1278 HInstruction* left = instruction->GetLeft();
1279 HInstruction* right = instruction->GetRight();
1280 bool left_is_neg = left->IsNeg();
1281 bool right_is_neg = right->IsNeg();
1282
1283 if (left_is_neg && right_is_neg) {
1284 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1285 return;
1286 }
1287 }
1288
1289 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
Andreas Gampe654698d2018-09-20 13:34:35 -07001290 if (left_is_neg != right_is_neg && neg->HasOnlyOneNonEnvironmentUse()) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001291 // Replace code looking like
1292 // NEG tmp, b
1293 // ADD dst, a, tmp
1294 // with
1295 // SUB dst, a, b
1296 // We do not perform the optimization if the input negation has environment
1297 // uses or multiple non-environment uses as it could lead to worse code. In
1298 // particular, we do not want the live range of `b` to be extended if we are
1299 // not sure the initial 'NEG' instruction can be removed.
1300 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001301 HSub* sub =
1302 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001303 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1304 RecordSimplification();
1305 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001306 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001307 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001308
Anton Kirilove14dc862016-05-13 17:56:15 +01001309 if (TryReplaceWithRotate(instruction)) {
1310 return;
1311 }
1312
1313 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1314 // so no need to return.
1315 TryHandleAssociativeAndCommutativeOperation(instruction);
1316
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001317 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001318 TrySubtractionChainSimplification(instruction)) {
1319 return;
1320 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001321
1322 if (integral_type) {
1323 // Replace code patterns looking like
1324 // SUB dst1, x, y SUB dst1, x, y
1325 // ADD dst2, dst1, y ADD dst2, y, dst1
1326 // with
1327 // SUB dst1, x, y
1328 // ADD instruction is not needed in this case, we may use
1329 // one of inputs of SUB instead.
1330 if (left->IsSub() && left->InputAt(1) == right) {
1331 instruction->ReplaceWith(left->InputAt(0));
1332 RecordSimplification();
1333 instruction->GetBlock()->RemoveInstruction(instruction);
1334 return;
1335 } else if (right->IsSub() && right->InputAt(1) == left) {
1336 instruction->ReplaceWith(right->InputAt(0));
1337 RecordSimplification();
1338 instruction->GetBlock()->RemoveInstruction(instruction);
1339 return;
1340 }
1341 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001342}
1343
1344void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001345 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001346 HConstant* input_cst = instruction->GetConstantRight();
1347 HInstruction* input_other = instruction->GetLeastConstantLeft();
1348
Vladimir Marko452c1b62015-09-25 14:44:17 +01001349 if (input_cst != nullptr) {
1350 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001351 if (value == -1 ||
1352 // Similar cases under zero extension.
1353 (DataType::IsUnsignedType(input_other->GetType()) &&
1354 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001355 // Replace code looking like
1356 // AND dst, src, 0xFFF...FF
1357 // with
1358 // src
1359 instruction->ReplaceWith(input_other);
1360 instruction->GetBlock()->RemoveInstruction(instruction);
1361 RecordSimplification();
1362 return;
1363 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001364 if (input_other->IsTypeConversion() &&
1365 input_other->GetType() == DataType::Type::kInt64 &&
1366 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1367 IsInt<32>(value) &&
1368 input_other->HasOnlyOneNonEnvironmentUse()) {
1369 // The AND can be reordered before the TypeConversion. Replace
1370 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1371 // TypeConversion<Int64> tmp, src
1372 // AND dst, tmp, cst
1373 // with
1374 // IntConstant cst, <32-bit-constant>
1375 // AND tmp, src, cst
1376 // TypeConversion<Int64> dst, tmp
1377 // This helps 32-bit targets and does not hurt 64-bit targets.
1378 // This also simplifies detection of other patterns, such as Uint8 loads.
1379 HInstruction* new_and_input = input_other->InputAt(0);
1380 // Implicit conversion Int64->Int64 would have been removed previously.
1381 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1382 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1383 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001384 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001385 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1386 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001387 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001388 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1389 input_other->GetBlock()->RemoveInstruction(input_other);
1390 RecordSimplification();
1391 // Try to process the new And now, do not wait for the next round of simplifications.
1392 instruction = new_and;
1393 input_other = new_and_input;
1394 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001395 // Eliminate And from UShr+And if the And-mask contains all the bits that
1396 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1397 // precisely clears the shifted-in sign bits.
1398 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001399 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001400 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1401 size_t num_tail_bits_set = CTZ(value + 1);
1402 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1403 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1404 instruction->ReplaceWith(input_other);
1405 instruction->GetBlock()->RemoveInstruction(instruction);
1406 RecordSimplification();
1407 return;
1408 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1409 input_other->HasOnlyOneNonEnvironmentUse()) {
1410 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1411 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001412 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001413 input_other->InputAt(0),
1414 input_other->InputAt(1),
1415 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001416 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1417 input_other->GetBlock()->RemoveInstruction(input_other);
1418 RecordSimplification();
1419 return;
1420 }
1421 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001422 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1423 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1424 // or array Get with only a single use, short-circuit the subsequent simplification
1425 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1426 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1427 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1428 if (input_other->GetType() == find_type &&
1429 input_other->HasOnlyOneNonEnvironmentUse() &&
1430 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1431 instruction->ReplaceWith(input_other);
1432 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001433 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1434 instruction->ReplaceWith(input_other);
1435 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001436 } else {
1437 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1438 new_type, input_other, instruction->GetDexPc());
1439 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1440 }
1441 RecordSimplification();
1442 return;
1443 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001444 }
1445
1446 // We assume that GVN has run before, so we only perform a pointer comparison.
1447 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001448 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001449 if (instruction->GetLeft() == instruction->GetRight()) {
1450 // Replace code looking like
1451 // AND dst, src, src
1452 // with
1453 // src
1454 instruction->ReplaceWith(instruction->GetLeft());
1455 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001456 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001457 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001458 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001459
Anton Kirilove14dc862016-05-13 17:56:15 +01001460 if (TryDeMorganNegationFactoring(instruction)) {
1461 return;
1462 }
1463
1464 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1465 // so no need to return.
1466 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001467}
1468
Mark Mendellc4701932015-04-10 13:18:51 -04001469void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1470 VisitCondition(condition);
1471}
1472
1473void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1474 VisitCondition(condition);
1475}
1476
1477void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1478 VisitCondition(condition);
1479}
1480
1481void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1482 VisitCondition(condition);
1483}
1484
Anton Shaminbdd79352016-02-15 12:48:36 +06001485void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1486 VisitCondition(condition);
1487}
1488
1489void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1490 VisitCondition(condition);
1491}
1492
1493void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1494 VisitCondition(condition);
1495}
1496
1497void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1498 VisitCondition(condition);
1499}
Aart Bike9f37602015-10-09 11:15:55 -07001500
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001501// Recognize the following pattern:
1502// obj.getClass() ==/!= Foo.class
1503// And replace it with a constant value if the type of `obj` is statically known.
1504static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1505 HInstruction* input_one = condition->InputAt(0);
1506 HInstruction* input_two = condition->InputAt(1);
1507 HLoadClass* load_class = input_one->IsLoadClass()
1508 ? input_one->AsLoadClass()
1509 : input_two->AsLoadClass();
1510 if (load_class == nullptr) {
1511 return false;
1512 }
1513
1514 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1515 if (!class_rti.IsValid()) {
1516 // Unresolved class.
1517 return false;
1518 }
1519
1520 HInstanceFieldGet* field_get = (load_class == input_one)
1521 ? input_two->AsInstanceFieldGet()
1522 : input_one->AsInstanceFieldGet();
1523 if (field_get == nullptr) {
1524 return false;
1525 }
1526
1527 HInstruction* receiver = field_get->InputAt(0);
1528 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1529 if (!receiver_type.IsExact()) {
1530 return false;
1531 }
1532
1533 {
1534 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001535 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001536 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1537 if (field_get->GetFieldInfo().GetField() != field) {
1538 return false;
1539 }
1540
1541 // We can replace the compare.
1542 int value = 0;
1543 if (receiver_type.IsEqual(class_rti)) {
1544 value = condition->IsEqual() ? 1 : 0;
1545 } else {
1546 value = condition->IsNotEqual() ? 1 : 0;
1547 }
1548 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1549 return true;
1550 }
1551}
1552
Mark Mendellc4701932015-04-10 13:18:51 -04001553void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001554 if (condition->IsEqual() || condition->IsNotEqual()) {
1555 if (RecognizeAndSimplifyClassCheck(condition)) {
1556 return;
1557 }
1558 }
1559
Anton Shaminbdd79352016-02-15 12:48:36 +06001560 // Reverse condition if left is constant. Our code generators prefer constant
1561 // on the right hand side.
1562 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1563 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001564 HCondition* replacement =
1565 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001566 // If it is a fp we must set the opposite bias.
1567 if (replacement != nullptr) {
1568 if (condition->IsLtBias()) {
1569 replacement->SetBias(ComparisonBias::kGtBias);
1570 } else if (condition->IsGtBias()) {
1571 replacement->SetBias(ComparisonBias::kLtBias);
1572 }
1573 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1574 RecordSimplification();
1575
1576 condition = replacement;
1577 }
1578 }
Mark Mendellc4701932015-04-10 13:18:51 -04001579
Mark Mendellc4701932015-04-10 13:18:51 -04001580 HInstruction* left = condition->GetLeft();
1581 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001582
1583 // Try to fold an HCompare into this HCondition.
1584
Mark Mendellc4701932015-04-10 13:18:51 -04001585 // We can only replace an HCondition which compares a Compare to 0.
1586 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1587 // condition with a long, float or double comparison as input.
1588 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1589 // Conversion is not possible.
1590 return;
1591 }
1592
1593 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001594 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001595 // Someone else also wants the result of the compare.
1596 return;
1597 }
1598
Vladimir Marko46817b82016-03-29 12:21:58 +01001599 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001600 // There is a reference to the compare result in an environment. Do we really need it?
1601 if (GetGraph()->IsDebuggable()) {
1602 return;
1603 }
1604
1605 // We have to ensure that there are no deopt points in the sequence.
1606 if (left->HasAnyEnvironmentUseBefore(condition)) {
1607 return;
1608 }
1609 }
1610
1611 // Clean up any environment uses from the HCompare, if any.
1612 left->RemoveEnvironmentUsers();
1613
1614 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1615 condition->SetBias(left->AsCompare()->GetBias());
1616
1617 // Replace the operands of the HCondition.
1618 condition->ReplaceInput(left->InputAt(0), 0);
1619 condition->ReplaceInput(left->InputAt(1), 1);
1620
1621 // Remove the HCompare.
1622 left->GetBlock()->RemoveInstruction(left);
1623
1624 RecordSimplification();
1625}
1626
Andreas Gampe9186ced2016-12-12 14:28:21 -08001627// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1628static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1629 // True, if the most significant bits of divisor are 0.
1630 return ((divisor & 0x7fffff) == 0);
1631}
1632
1633// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1634static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1635 // True, if the most significant bits of divisor are 0.
1636 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1637}
1638
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001639void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1640 HConstant* input_cst = instruction->GetConstantRight();
1641 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001642 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001643
1644 if ((input_cst != nullptr) && input_cst->IsOne()) {
1645 // Replace code looking like
1646 // DIV dst, src, 1
1647 // with
1648 // src
1649 instruction->ReplaceWith(input_other);
1650 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001651 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001652 return;
1653 }
1654
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001655 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001656 // Replace code looking like
1657 // DIV dst, src, -1
1658 // with
1659 // NEG dst, src
1660 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001661 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001662 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001663 return;
1664 }
1665
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001666 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001667 // Try replacing code looking like
1668 // DIV dst, src, constant
1669 // with
1670 // MUL dst, src, 1 / constant
1671 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001673 double value = input_cst->AsDoubleConstant()->GetValue();
1674 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1675 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1676 }
1677 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001679 float value = input_cst->AsFloatConstant()->GetValue();
1680 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1681 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1682 }
1683 }
1684
1685 if (reciprocal != nullptr) {
1686 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001687 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001688 RecordSimplification();
1689 return;
1690 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001691 }
1692}
1693
1694void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1695 HConstant* input_cst = instruction->GetConstantRight();
1696 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001697 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001698 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001699 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001700
1701 if (input_cst == nullptr) {
1702 return;
1703 }
1704
1705 if (input_cst->IsOne()) {
1706 // Replace code looking like
1707 // MUL dst, src, 1
1708 // with
1709 // src
1710 instruction->ReplaceWith(input_other);
1711 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001712 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001713 return;
1714 }
1715
1716 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001717 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001718 // Replace code looking like
1719 // MUL dst, src, -1
1720 // with
1721 // NEG dst, src
1722 HNeg* neg = new (allocator) HNeg(type, input_other);
1723 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001724 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001725 return;
1726 }
1727
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001728 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001729 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1730 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1731 // Replace code looking like
1732 // FP_MUL dst, src, 2.0
1733 // with
1734 // FP_ADD dst, src, src
1735 // The 'int' and 'long' cases are handled below.
1736 block->ReplaceAndRemoveInstructionWith(instruction,
1737 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001738 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001739 return;
1740 }
1741
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001742 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001743 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001744 // Even though constant propagation also takes care of the zero case, other
1745 // optimizations can lead to having a zero multiplication.
1746 if (factor == 0) {
1747 // Replace code looking like
1748 // MUL dst, src, 0
1749 // with
1750 // 0
1751 instruction->ReplaceWith(input_cst);
1752 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001753 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001754 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001755 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001756 // Replace code looking like
1757 // MUL dst, src, pow_of_2
1758 // with
1759 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001760 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001761 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001762 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001763 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001764 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001765 } else if (IsPowerOfTwo(factor - 1)) {
1766 // Transform code looking like
1767 // MUL dst, src, (2^n + 1)
1768 // into
1769 // SHL tmp, src, n
1770 // ADD dst, src, tmp
1771 HShl* shl = new (allocator) HShl(type,
1772 input_other,
1773 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1774 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1775
1776 block->InsertInstructionBefore(shl, instruction);
1777 block->ReplaceAndRemoveInstructionWith(instruction, add);
1778 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001779 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001780 } else if (IsPowerOfTwo(factor + 1)) {
1781 // Transform code looking like
1782 // MUL dst, src, (2^n - 1)
1783 // into
1784 // SHL tmp, src, n
1785 // SUB dst, tmp, src
1786 HShl* shl = new (allocator) HShl(type,
1787 input_other,
1788 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1789 HSub* sub = new (allocator) HSub(type, shl, input_other);
1790
1791 block->InsertInstructionBefore(shl, instruction);
1792 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1793 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001794 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001795 }
1796 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001797
1798 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1799 // so no need to return.
1800 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001801}
1802
Alexandre Rames188d4312015-04-09 18:30:21 +01001803void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1804 HInstruction* input = instruction->GetInput();
1805 if (input->IsNeg()) {
1806 // Replace code looking like
1807 // NEG tmp, src
1808 // NEG dst, tmp
1809 // with
1810 // src
1811 HNeg* previous_neg = input->AsNeg();
1812 instruction->ReplaceWith(previous_neg->GetInput());
1813 instruction->GetBlock()->RemoveInstruction(instruction);
1814 // We perform the optimization even if the input negation has environment
1815 // uses since it allows removing the current instruction. But we only delete
1816 // the input negation only if it is does not have any uses left.
1817 if (!previous_neg->HasUses()) {
1818 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1819 }
1820 RecordSimplification();
1821 return;
1822 }
1823
Serguei Katkov339dfc22015-04-20 12:29:32 +06001824 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001825 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001826 // Replace code looking like
1827 // SUB tmp, a, b
1828 // NEG dst, tmp
1829 // with
1830 // SUB dst, b, a
1831 // We do not perform the optimization if the input subtraction has
1832 // environment uses or multiple non-environment uses as it could lead to
1833 // worse code. In particular, we do not want the live ranges of `a` and `b`
1834 // to be extended if we are not sure the initial 'SUB' instruction can be
1835 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001836 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001837 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001838 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
1839 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01001840 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1841 if (!sub->HasUses()) {
1842 sub->GetBlock()->RemoveInstruction(sub);
1843 }
1844 RecordSimplification();
1845 }
1846}
1847
1848void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1849 HInstruction* input = instruction->GetInput();
1850 if (input->IsNot()) {
1851 // Replace code looking like
1852 // NOT tmp, src
1853 // NOT dst, tmp
1854 // with
1855 // src
1856 // We perform the optimization even if the input negation has environment
1857 // uses since it allows removing the current instruction. But we only delete
1858 // the input negation only if it is does not have any uses left.
1859 HNot* previous_not = input->AsNot();
1860 instruction->ReplaceWith(previous_not->GetInput());
1861 instruction->GetBlock()->RemoveInstruction(instruction);
1862 if (!previous_not->HasUses()) {
1863 previous_not->GetBlock()->RemoveInstruction(previous_not);
1864 }
1865 RecordSimplification();
1866 }
1867}
1868
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001869void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1870 HConstant* input_cst = instruction->GetConstantRight();
1871 HInstruction* input_other = instruction->GetLeastConstantLeft();
1872
Roland Levillain1a653882016-03-18 18:05:57 +00001873 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001874 // Replace code looking like
1875 // OR dst, src, 0
1876 // with
1877 // src
1878 instruction->ReplaceWith(input_other);
1879 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001880 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001881 return;
1882 }
1883
1884 // We assume that GVN has run before, so we only perform a pointer comparison.
1885 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001886 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001887 if (instruction->GetLeft() == instruction->GetRight()) {
1888 // Replace code looking like
1889 // OR dst, src, src
1890 // with
1891 // src
1892 instruction->ReplaceWith(instruction->GetLeft());
1893 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001894 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001895 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001896 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001897
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001898 if (TryDeMorganNegationFactoring(instruction)) return;
1899
Anton Kirilove14dc862016-05-13 17:56:15 +01001900 if (TryReplaceWithRotate(instruction)) {
1901 return;
1902 }
1903
1904 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1905 // so no need to return.
1906 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001907}
1908
1909void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1910 VisitShift(instruction);
1911}
1912
1913void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1914 VisitShift(instruction);
1915}
1916
1917void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1918 HConstant* input_cst = instruction->GetConstantRight();
1919 HInstruction* input_other = instruction->GetLeastConstantLeft();
1920
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001921 DataType::Type type = instruction->GetType();
1922 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001923 return;
1924 }
1925
Roland Levillain1a653882016-03-18 18:05:57 +00001926 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001927 // Replace code looking like
1928 // SUB dst, src, 0
1929 // with
1930 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001931 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1932 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1933 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001934 instruction->ReplaceWith(input_other);
1935 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001936 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001937 return;
1938 }
1939
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001940 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001941 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001942
Alexandre Rames188d4312015-04-09 18:30:21 +01001943 HInstruction* left = instruction->GetLeft();
1944 HInstruction* right = instruction->GetRight();
1945 if (left->IsConstant()) {
1946 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001947 // Replace code looking like
1948 // SUB dst, 0, src
1949 // with
1950 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001951 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001952 // `x` is `0.0`, the former expression yields `0.0`, while the later
1953 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001954 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001955 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001956 RecordSimplification();
1957 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001958 }
1959 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001960
1961 if (left->IsNeg() && right->IsNeg()) {
1962 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1963 return;
1964 }
1965 }
1966
1967 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1968 // Replace code looking like
1969 // NEG tmp, b
1970 // SUB dst, a, tmp
1971 // with
1972 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01001973 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001974 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1975 RecordSimplification();
1976 right->GetBlock()->RemoveInstruction(right);
1977 return;
1978 }
1979
1980 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1981 // Replace code looking like
1982 // NEG tmp, a
1983 // SUB dst, tmp, b
1984 // with
1985 // ADD tmp, a, b
1986 // NEG dst, tmp
1987 // The second version is not intrinsically better, but enables more
1988 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001989 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01001990 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001991 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01001992 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1993 instruction->ReplaceWith(neg);
1994 instruction->GetBlock()->RemoveInstruction(instruction);
1995 RecordSimplification();
1996 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001997 return;
1998 }
1999
2000 if (TrySubtractionChainSimplification(instruction)) {
2001 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002002 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002003
2004 if (left->IsAdd()) {
2005 // Replace code patterns looking like
2006 // ADD dst1, x, y ADD dst1, x, y
2007 // SUB dst2, dst1, y SUB dst2, dst1, x
2008 // with
2009 // ADD dst1, x, y
2010 // SUB instruction is not needed in this case, we may use
2011 // one of inputs of ADD instead.
2012 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002013 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002014 if (left->InputAt(1) == right) {
2015 instruction->ReplaceWith(left->InputAt(0));
2016 RecordSimplification();
2017 instruction->GetBlock()->RemoveInstruction(instruction);
2018 return;
2019 } else if (left->InputAt(0) == right) {
2020 instruction->ReplaceWith(left->InputAt(1));
2021 RecordSimplification();
2022 instruction->GetBlock()->RemoveInstruction(instruction);
2023 return;
2024 }
2025 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002026}
2027
2028void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2029 VisitShift(instruction);
2030}
2031
2032void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2033 HConstant* input_cst = instruction->GetConstantRight();
2034 HInstruction* input_other = instruction->GetLeastConstantLeft();
2035
Roland Levillain1a653882016-03-18 18:05:57 +00002036 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002037 // Replace code looking like
2038 // XOR dst, src, 0
2039 // with
2040 // src
2041 instruction->ReplaceWith(input_other);
2042 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002043 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002044 return;
2045 }
2046
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002047 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002048 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002049 // Replace code looking like
2050 // XOR dst, src, 1
2051 // with
2052 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002053 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002054 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2055 RecordSimplification();
2056 return;
2057 }
2058
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002059 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2060 // Replace code looking like
2061 // XOR dst, src, 0xFFF...FF
2062 // with
2063 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002064 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002065 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002066 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002067 return;
2068 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002069
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002070 HInstruction* left = instruction->GetLeft();
2071 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002072 if (((left->IsNot() && right->IsNot()) ||
2073 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002074 left->HasOnlyOneNonEnvironmentUse() &&
2075 right->HasOnlyOneNonEnvironmentUse()) {
2076 // Replace code looking like
2077 // NOT nota, a
2078 // NOT notb, b
2079 // XOR dst, nota, notb
2080 // with
2081 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002082 instruction->ReplaceInput(left->InputAt(0), 0);
2083 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002084 left->GetBlock()->RemoveInstruction(left);
2085 right->GetBlock()->RemoveInstruction(right);
2086 RecordSimplification();
2087 return;
2088 }
2089
Anton Kirilove14dc862016-05-13 17:56:15 +01002090 if (TryReplaceWithRotate(instruction)) {
2091 return;
2092 }
2093
2094 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2095 // so no need to return.
2096 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002097}
2098
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002099void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2100 HInstruction* argument = instruction->InputAt(1);
2101 HInstruction* receiver = instruction->InputAt(0);
2102 if (receiver == argument) {
2103 // Because String.equals is an instance call, the receiver is
2104 // a null check if we don't know it's null. The argument however, will
2105 // be the actual object. So we cannot end up in a situation where both
2106 // are equal but could be null.
2107 DCHECK(CanEnsureNotNullAt(argument, instruction));
2108 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2109 instruction->GetBlock()->RemoveInstruction(instruction);
2110 } else {
2111 StringEqualsOptimizations optimizations(instruction);
2112 if (CanEnsureNotNullAt(argument, instruction)) {
2113 optimizations.SetArgumentNotNull();
2114 }
2115 ScopedObjectAccess soa(Thread::Current());
2116 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2117 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2118 optimizations.SetArgumentIsString();
2119 }
2120 }
2121}
2122
2123static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2124 if (potential_length->IsArrayLength()) {
2125 return potential_length->InputAt(0) == potential_array;
2126 }
2127
2128 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002129 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002130 }
2131
2132 return false;
2133}
2134
2135void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2136 HInstruction* source = instruction->InputAt(0);
2137 HInstruction* destination = instruction->InputAt(2);
2138 HInstruction* count = instruction->InputAt(4);
2139 SystemArrayCopyOptimizations optimizations(instruction);
2140 if (CanEnsureNotNullAt(source, instruction)) {
2141 optimizations.SetSourceIsNotNull();
2142 }
2143 if (CanEnsureNotNullAt(destination, instruction)) {
2144 optimizations.SetDestinationIsNotNull();
2145 }
2146 if (destination == source) {
2147 optimizations.SetDestinationIsSource();
2148 }
2149
2150 if (IsArrayLengthOf(count, source)) {
2151 optimizations.SetCountIsSourceLength();
2152 }
2153
2154 if (IsArrayLengthOf(count, destination)) {
2155 optimizations.SetCountIsDestinationLength();
2156 }
2157
2158 {
2159 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002160 DataType::Type source_component_type = DataType::Type::kVoid;
2161 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002162 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2163 if (destination_rti.IsValid()) {
2164 if (destination_rti.IsObjectArray()) {
2165 if (destination_rti.IsExact()) {
2166 optimizations.SetDoesNotNeedTypeCheck();
2167 }
2168 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002169 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002170 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002171 destination_component_type = DataTypeFromPrimitive(
2172 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002173 optimizations.SetDestinationIsPrimitiveArray();
2174 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2175 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002176 }
2177 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002178 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2179 if (source_rti.IsValid()) {
2180 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2181 optimizations.SetDoesNotNeedTypeCheck();
2182 }
2183 if (source_rti.IsPrimitiveArrayClass()) {
2184 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002185 source_component_type = DataTypeFromPrimitive(
2186 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002187 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2188 optimizations.SetSourceIsNonPrimitiveArray();
2189 }
2190 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002191 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002192 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002193 (source_component_type == destination_component_type)) {
2194 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2195 PointerSize image_size = class_linker->GetImagePointerSize();
2196 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
Vladimir Markod93e3742018-07-18 10:58:13 +01002197 ObjPtr<mirror::Class> system = invoke->GetResolvedMethod()->GetDeclaringClass();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002198 ArtMethod* method = nullptr;
2199 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002200 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002201 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002202 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002203 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002204 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002205 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002206 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002207 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002208 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002209 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002210 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002211 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002212 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002213 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002214 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002215 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002216 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002217 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002218 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002219 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002220 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002221 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002222 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002223 break;
2224 default:
2225 LOG(FATAL) << "Unreachable";
2226 }
2227 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002228 DCHECK(method->IsStatic());
2229 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002230 invoke->SetResolvedMethod(method);
2231 // Sharpen the new invoke. Note that we do not update the dex method index of
2232 // the invoke, as we would need to look it up in the current dex file, and it
2233 // is unlikely that it exists. The most usual situation for such typed
2234 // arraycopy methods is a direct pointer to the boot image.
Nicolas Geoffraybdb2ecc2018-09-18 14:33:55 +01002235 invoke->SetDispatchInfo(HSharpening::SharpenInvokeStaticOrDirect(method, codegen_));
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002236 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002237 }
2238}
2239
Aart Bik2a6aad92016-02-25 11:32:32 -08002240void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2241 DCHECK(invoke->IsInvokeStaticOrDirect());
2242 uint32_t dex_pc = invoke->GetDexPc();
2243 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002244 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002245 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2246 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002247 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002248 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2249 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2250 kNeedsEnvironmentOrCache,
2251 kNoSideEffects,
2252 kNoThrow);
2253 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002254 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002255 nan = GetGraph()->GetIntConstant(0x7fc00000);
2256 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2257 kNeedsEnvironmentOrCache,
2258 kNoSideEffects,
2259 kNoThrow);
2260 }
2261 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002262 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002263 condition->SetBias(ComparisonBias::kLtBias);
2264 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2265 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002266 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002267 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2268 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2269}
2270
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002271void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2272 HInstruction* str = invoke->InputAt(0);
2273 HInstruction* index = invoke->InputAt(1);
2274 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002275 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002276 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2277 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Andreas Gampe3db70682018-12-26 15:12:03 -08002278 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002279 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002280 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Andreas Gampe3db70682018-12-26 15:12:03 -08002281 index, length, dex_pc, /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002282 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002283 HArrayGet* array_get = new (allocator) HArrayGet(str,
2284 bounds_check,
2285 DataType::Type::kUint16,
2286 SideEffects::None(), // Strings are immutable.
2287 dex_pc,
Andreas Gampe3db70682018-12-26 15:12:03 -08002288 /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002289 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2290 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2291 GetGraph()->SetHasBoundsChecks(true);
2292}
2293
Vladimir Marko5f846072020-04-09 13:20:11 +01002294void InstructionSimplifierVisitor::SimplifyStringLength(HInvoke* invoke) {
Vladimir Markodce016e2016-04-28 13:10:02 +01002295 HInstruction* str = invoke->InputAt(0);
2296 uint32_t dex_pc = invoke->GetDexPc();
2297 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2298 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002299 HArrayLength* length =
Andreas Gampe3db70682018-12-26 15:12:03 -08002300 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko5f846072020-04-09 13:20:11 +01002301 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, length);
Vladimir Markodce016e2016-04-28 13:10:02 +01002302}
2303
Vladimir Marko6fa44042018-03-19 18:42:49 +00002304void InstructionSimplifierVisitor::SimplifyStringIndexOf(HInvoke* invoke) {
2305 DCHECK(invoke->GetIntrinsic() == Intrinsics::kStringIndexOf ||
2306 invoke->GetIntrinsic() == Intrinsics::kStringIndexOfAfter);
2307 if (invoke->InputAt(0)->IsLoadString()) {
2308 HLoadString* load_string = invoke->InputAt(0)->AsLoadString();
2309 const DexFile& dex_file = load_string->GetDexFile();
2310 uint32_t utf16_length;
2311 const char* data =
2312 dex_file.StringDataAndUtf16LengthByIdx(load_string->GetStringIndex(), &utf16_length);
2313 if (utf16_length == 0) {
2314 invoke->ReplaceWith(GetGraph()->GetIntConstant(-1));
2315 invoke->GetBlock()->RemoveInstruction(invoke);
2316 RecordSimplification();
2317 return;
2318 }
2319 if (utf16_length == 1 && invoke->GetIntrinsic() == Intrinsics::kStringIndexOf) {
2320 // Simplify to HSelect(HEquals(., load_string.charAt(0)), 0, -1).
2321 // If the sought character is supplementary, this gives the correct result, i.e. -1.
2322 uint32_t c = GetUtf16FromUtf8(&data);
2323 DCHECK_EQ(GetTrailingUtf16Char(c), 0u);
2324 DCHECK_EQ(GetLeadingUtf16Char(c), c);
2325 uint32_t dex_pc = invoke->GetDexPc();
2326 ArenaAllocator* allocator = GetGraph()->GetAllocator();
2327 HEqual* equal =
2328 new (allocator) HEqual(invoke->InputAt(1), GetGraph()->GetIntConstant(c), dex_pc);
2329 invoke->GetBlock()->InsertInstructionBefore(equal, invoke);
2330 HSelect* result = new (allocator) HSelect(equal,
2331 GetGraph()->GetIntConstant(0),
2332 GetGraph()->GetIntConstant(-1),
2333 dex_pc);
2334 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, result);
2335 RecordSimplification();
2336 return;
2337 }
2338 }
2339}
2340
Aart Bikff7d89c2016-11-07 08:49:28 -08002341// This method should only be used on intrinsics whose sole way of throwing an
2342// exception is raising a NPE when the nth argument is null. If that argument
2343// is provably non-null, we can clear the flag.
2344void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2345 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002346 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002347 invoke->SetCanThrow(false);
2348 }
2349}
2350
Aart Bik71bf7b42016-11-16 10:17:46 -08002351// Methods that return "this" can replace the returned value with the receiver.
2352void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2353 if (invoke->HasUses()) {
2354 HInstruction* receiver = invoke->InputAt(0);
2355 invoke->ReplaceWith(receiver);
2356 RecordSimplification();
2357 }
2358}
2359
2360// Helper method for StringBuffer escape analysis.
2361static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2362 if (user->IsInvokeStaticOrDirect()) {
2363 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002364 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2365 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002366 user->InputAt(0) == reference;
2367 } else if (user->IsInvokeVirtual()) {
2368 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2369 case Intrinsics::kStringBufferLength:
2370 case Intrinsics::kStringBufferToString:
2371 DCHECK_EQ(user->InputAt(0), reference);
2372 return true;
2373 case Intrinsics::kStringBufferAppend:
2374 // Returns "this", so only okay if no further uses.
2375 DCHECK_EQ(user->InputAt(0), reference);
2376 DCHECK_NE(user->InputAt(1), reference);
2377 return !user->HasUses();
2378 default:
2379 break;
2380 }
2381 }
2382 return false;
2383}
2384
Vladimir Marko552a1342017-10-31 10:56:47 +00002385static bool TryReplaceStringBuilderAppend(HInvoke* invoke) {
2386 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringBuilderToString);
2387 if (invoke->CanThrowIntoCatchBlock()) {
2388 return false;
2389 }
2390
2391 HBasicBlock* block = invoke->GetBlock();
2392 HInstruction* sb = invoke->InputAt(0);
2393
2394 // We support only a new StringBuilder, otherwise we cannot ensure that
2395 // the StringBuilder data does not need to be populated for other users.
2396 if (!sb->IsNewInstance()) {
2397 return false;
2398 }
2399
2400 // For now, we support only single-block recognition.
2401 // (Ternary operators feeding the append could be implemented.)
2402 for (const HUseListNode<HInstruction*>& use : sb->GetUses()) {
2403 if (use.GetUser()->GetBlock() != block) {
2404 return false;
2405 }
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002406 // The append pattern uses the StringBuilder only as the first argument.
2407 if (use.GetIndex() != 0u) {
2408 return false;
2409 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002410 }
2411
2412 // Collect args and check for unexpected uses.
2413 // We expect one call to a constructor with no arguments, one constructor fence (unless
2414 // eliminated), some number of append calls and one call to StringBuilder.toString().
2415 bool seen_constructor = false;
2416 bool seen_constructor_fence = false;
2417 bool seen_to_string = false;
2418 uint32_t format = 0u;
2419 uint32_t num_args = 0u;
2420 HInstruction* args[StringBuilderAppend::kMaxArgs]; // Added in reverse order.
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002421 for (HBackwardInstructionIterator iter(block->GetInstructions()); !iter.Done(); iter.Advance()) {
2422 HInstruction* user = iter.Current();
2423 // Instructions of interest apply to `sb`, skip those that do not involve `sb`.
2424 if (user->InputCount() == 0u || user->InputAt(0u) != sb) {
2425 continue;
Vladimir Marko552a1342017-10-31 10:56:47 +00002426 }
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002427 // We visit the uses in reverse order, so the StringBuilder.toString() must come first.
Vladimir Marko552a1342017-10-31 10:56:47 +00002428 if (!seen_to_string) {
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002429 if (user == invoke) {
Vladimir Marko552a1342017-10-31 10:56:47 +00002430 seen_to_string = true;
2431 continue;
2432 } else {
2433 return false;
2434 }
2435 }
2436 // Then we should see the arguments.
2437 if (user->IsInvokeVirtual()) {
2438 HInvokeVirtual* as_invoke_virtual = user->AsInvokeVirtual();
2439 DCHECK(!seen_constructor);
2440 DCHECK(!seen_constructor_fence);
2441 StringBuilderAppend::Argument arg;
2442 switch (as_invoke_virtual->GetIntrinsic()) {
2443 case Intrinsics::kStringBuilderAppendObject:
2444 // TODO: Unimplemented, needs to call String.valueOf().
2445 return false;
2446 case Intrinsics::kStringBuilderAppendString:
2447 arg = StringBuilderAppend::Argument::kString;
2448 break;
2449 case Intrinsics::kStringBuilderAppendCharArray:
2450 // TODO: Unimplemented, StringBuilder.append(char[]) can throw NPE and we would
2451 // not have the correct stack trace for it.
2452 return false;
2453 case Intrinsics::kStringBuilderAppendBoolean:
2454 arg = StringBuilderAppend::Argument::kBoolean;
2455 break;
2456 case Intrinsics::kStringBuilderAppendChar:
2457 arg = StringBuilderAppend::Argument::kChar;
2458 break;
2459 case Intrinsics::kStringBuilderAppendInt:
2460 arg = StringBuilderAppend::Argument::kInt;
2461 break;
2462 case Intrinsics::kStringBuilderAppendLong:
2463 arg = StringBuilderAppend::Argument::kLong;
2464 break;
2465 case Intrinsics::kStringBuilderAppendCharSequence: {
2466 ReferenceTypeInfo rti = user->AsInvokeVirtual()->InputAt(1)->GetReferenceTypeInfo();
2467 if (!rti.IsValid()) {
2468 return false;
2469 }
2470 ScopedObjectAccess soa(Thread::Current());
2471 Handle<mirror::Class> input_type = rti.GetTypeHandle();
2472 DCHECK(input_type != nullptr);
2473 if (input_type.Get() == GetClassRoot<mirror::String>()) {
2474 arg = StringBuilderAppend::Argument::kString;
2475 } else {
2476 // TODO: Check and implement for StringBuilder. We could find the StringBuilder's
2477 // internal char[] inconsistent with the length, or the string compression
2478 // of the result could be compromised with a concurrent modification, and
2479 // we would need to throw appropriate exceptions.
2480 return false;
2481 }
2482 break;
2483 }
2484 case Intrinsics::kStringBuilderAppendFloat:
2485 case Intrinsics::kStringBuilderAppendDouble:
2486 // TODO: Unimplemented, needs to call FloatingDecimal.getBinaryToASCIIConverter().
2487 return false;
2488 default: {
2489 return false;
2490 }
2491 }
2492 // Uses of the append return value should have been replaced with the first input.
2493 DCHECK(!as_invoke_virtual->HasUses());
2494 DCHECK(!as_invoke_virtual->HasEnvironmentUses());
2495 if (num_args == StringBuilderAppend::kMaxArgs) {
2496 return false;
2497 }
2498 format = (format << StringBuilderAppend::kBitsPerArg) | static_cast<uint32_t>(arg);
2499 args[num_args] = as_invoke_virtual->InputAt(1u);
2500 ++num_args;
2501 } else if (user->IsInvokeStaticOrDirect() &&
2502 user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2503 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
2504 user->AsInvokeStaticOrDirect()->GetNumberOfArguments() == 1u) {
2505 // After arguments, we should see the constructor.
2506 // We accept only the constructor with no extra arguments.
2507 DCHECK(!seen_constructor);
2508 DCHECK(!seen_constructor_fence);
2509 seen_constructor = true;
2510 } else if (user->IsConstructorFence()) {
2511 // The last use we see is the constructor fence.
2512 DCHECK(seen_constructor);
2513 DCHECK(!seen_constructor_fence);
2514 seen_constructor_fence = true;
2515 } else {
2516 return false;
2517 }
2518 }
2519
2520 if (num_args == 0u) {
2521 return false;
2522 }
2523
2524 // Check environment uses.
2525 for (const HUseListNode<HEnvironment*>& use : sb->GetEnvUses()) {
2526 HInstruction* holder = use.GetUser()->GetHolder();
2527 if (holder->GetBlock() != block) {
2528 return false;
2529 }
2530 // Accept only calls on the StringBuilder (which shall all be removed).
2531 // TODO: Carve-out for const-string? Or rely on environment pruning (to be implemented)?
2532 if (holder->InputCount() == 0 || holder->InputAt(0) != sb) {
2533 return false;
2534 }
2535 }
2536
2537 // Create replacement instruction.
2538 HIntConstant* fmt = block->GetGraph()->GetIntConstant(static_cast<int32_t>(format));
2539 ArenaAllocator* allocator = block->GetGraph()->GetAllocator();
2540 HStringBuilderAppend* append =
2541 new (allocator) HStringBuilderAppend(fmt, num_args, allocator, invoke->GetDexPc());
2542 append->SetReferenceTypeInfo(invoke->GetReferenceTypeInfo());
2543 for (size_t i = 0; i != num_args; ++i) {
2544 append->SetArgumentAt(i, args[num_args - 1u - i]);
2545 }
2546 block->InsertInstructionBefore(append, invoke);
Vladimir Markob1fe5e12020-03-10 14:30:49 +00002547 DCHECK(!invoke->CanBeNull());
2548 DCHECK(!append->CanBeNull());
Vladimir Marko552a1342017-10-31 10:56:47 +00002549 invoke->ReplaceWith(append);
2550 // Copy environment, except for the StringBuilder uses.
Vladimir Marko56f13322019-11-15 14:07:19 +00002551 for (HEnvironment* env = invoke->GetEnvironment(); env != nullptr; env = env->GetParent()) {
2552 for (size_t i = 0, size = env->Size(); i != size; ++i) {
2553 if (env->GetInstructionAt(i) == sb) {
2554 env->RemoveAsUserOfInput(i);
2555 env->SetRawEnvAt(i, /*instruction=*/ nullptr);
2556 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002557 }
2558 }
2559 append->CopyEnvironmentFrom(invoke->GetEnvironment());
2560 // Remove the old instruction.
2561 block->RemoveInstruction(invoke);
2562 // Remove the StringBuilder's uses and StringBuilder.
2563 while (sb->HasNonEnvironmentUses()) {
2564 block->RemoveInstruction(sb->GetUses().front().GetUser());
2565 }
2566 DCHECK(!sb->HasEnvironmentUses());
2567 block->RemoveInstruction(sb);
2568 return true;
2569}
2570
Aart Bik71bf7b42016-11-16 10:17:46 -08002571// Certain allocation intrinsics are not removed by dead code elimination
2572// because of potentially throwing an OOM exception or other side effects.
2573// This method removes such intrinsics when special circumstances allow.
2574void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2575 if (!invoke->HasUses()) {
2576 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2577 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2578 // call does not escape since only thread-local synchronization may be removed.
2579 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2580 HInstruction* receiver = invoke->InputAt(0);
2581 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2582 invoke->GetBlock()->RemoveInstruction(invoke);
2583 RecordSimplification();
2584 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002585 } else if (invoke->GetIntrinsic() == Intrinsics::kStringBuilderToString &&
2586 TryReplaceStringBuilderAppend(invoke)) {
2587 RecordSimplification();
Aart Bik71bf7b42016-11-16 10:17:46 -08002588 }
2589}
2590
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002591void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002592 switch (instruction->GetIntrinsic()) {
2593 case Intrinsics::kStringEquals:
2594 SimplifyStringEquals(instruction);
2595 break;
2596 case Intrinsics::kSystemArrayCopy:
2597 SimplifySystemArrayCopy(instruction);
2598 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002599 case Intrinsics::kFloatFloatToIntBits:
2600 case Intrinsics::kDoubleDoubleToLongBits:
2601 SimplifyFP2Int(instruction);
2602 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002603 case Intrinsics::kStringCharAt:
Vladimir Marko5f846072020-04-09 13:20:11 +01002604 // Instruction builder creates intermediate representation directly
2605 // but the inliner can sharpen CharSequence.charAt() to String.charAt().
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002606 SimplifyStringCharAt(instruction);
2607 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002608 case Intrinsics::kStringLength:
Vladimir Marko5f846072020-04-09 13:20:11 +01002609 // Instruction builder creates intermediate representation directly
2610 // but the inliner can sharpen CharSequence.length() to String.length().
2611 SimplifyStringLength(instruction);
Vladimir Markodce016e2016-04-28 13:10:02 +01002612 break;
Vladimir Marko6fa44042018-03-19 18:42:49 +00002613 case Intrinsics::kStringIndexOf:
2614 case Intrinsics::kStringIndexOfAfter:
2615 SimplifyStringIndexOf(instruction);
2616 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002617 case Intrinsics::kStringStringIndexOf:
2618 case Intrinsics::kStringStringIndexOfAfter:
2619 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2620 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002621 case Intrinsics::kStringBufferAppend:
Vladimir Markod4561172017-10-30 17:48:25 +00002622 case Intrinsics::kStringBuilderAppendObject:
2623 case Intrinsics::kStringBuilderAppendString:
2624 case Intrinsics::kStringBuilderAppendCharSequence:
2625 case Intrinsics::kStringBuilderAppendCharArray:
2626 case Intrinsics::kStringBuilderAppendBoolean:
2627 case Intrinsics::kStringBuilderAppendChar:
2628 case Intrinsics::kStringBuilderAppendInt:
2629 case Intrinsics::kStringBuilderAppendLong:
2630 case Intrinsics::kStringBuilderAppendFloat:
2631 case Intrinsics::kStringBuilderAppendDouble:
Aart Bik71bf7b42016-11-16 10:17:46 -08002632 SimplifyReturnThis(instruction);
2633 break;
2634 case Intrinsics::kStringBufferToString:
2635 case Intrinsics::kStringBuilderToString:
2636 SimplifyAllocationIntrinsic(instruction);
2637 break;
Vladimir Marko5f846072020-04-09 13:20:11 +01002638 case Intrinsics::kIntegerRotateRight:
2639 case Intrinsics::kLongRotateRight:
2640 case Intrinsics::kIntegerRotateLeft:
2641 case Intrinsics::kLongRotateLeft:
2642 case Intrinsics::kIntegerCompare:
2643 case Intrinsics::kLongCompare:
2644 case Intrinsics::kIntegerSignum:
2645 case Intrinsics::kLongSignum:
2646 case Intrinsics::kFloatIsNaN:
2647 case Intrinsics::kDoubleIsNaN:
2648 case Intrinsics::kStringIsEmpty:
Aart Bik11932592016-03-08 12:42:25 -08002649 case Intrinsics::kUnsafeLoadFence:
Aart Bik11932592016-03-08 12:42:25 -08002650 case Intrinsics::kUnsafeStoreFence:
Aart Bik11932592016-03-08 12:42:25 -08002651 case Intrinsics::kUnsafeFullFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01002652 case Intrinsics::kVarHandleFullFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01002653 case Intrinsics::kVarHandleAcquireFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01002654 case Intrinsics::kVarHandleReleaseFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01002655 case Intrinsics::kVarHandleLoadLoadFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01002656 case Intrinsics::kVarHandleStoreStoreFence:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002657 case Intrinsics::kMathMinIntInt:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002658 case Intrinsics::kMathMinLongLong:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002659 case Intrinsics::kMathMinFloatFloat:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002660 case Intrinsics::kMathMinDoubleDouble:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002661 case Intrinsics::kMathMaxIntInt:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002662 case Intrinsics::kMathMaxLongLong:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002663 case Intrinsics::kMathMaxFloatFloat:
Aart Bik1f8d51b2018-02-15 10:42:37 -08002664 case Intrinsics::kMathMaxDoubleDouble:
Aart Bik3dad3412018-02-28 12:01:46 -08002665 case Intrinsics::kMathAbsInt:
Aart Bik3dad3412018-02-28 12:01:46 -08002666 case Intrinsics::kMathAbsLong:
Aart Bik3dad3412018-02-28 12:01:46 -08002667 case Intrinsics::kMathAbsFloat:
Aart Bik3dad3412018-02-28 12:01:46 -08002668 case Intrinsics::kMathAbsDouble:
Vladimir Marko5f846072020-04-09 13:20:11 +01002669 // These are replaced by intermediate representation in the instruction builder.
2670 LOG(FATAL) << "Unexpected " << static_cast<Intrinsics>(instruction->GetIntrinsic());
2671 UNREACHABLE();
Aart Bik2a6aad92016-02-25 11:32:32 -08002672 default:
2673 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002674 }
2675}
2676
Aart Bikbb245d12015-10-19 11:05:03 -07002677void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2678 HInstruction* cond = deoptimize->InputAt(0);
2679 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002680 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002681 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002682 if (deoptimize->GuardsAnInput()) {
2683 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2684 }
Aart Bikbb245d12015-10-19 11:05:03 -07002685 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2686 } else {
2687 // Always deopt.
2688 }
2689 }
2690}
2691
Anton Kirilove14dc862016-05-13 17:56:15 +01002692// Replace code looking like
2693// OP y, x, const1
2694// OP z, y, const2
2695// with
2696// OP z, x, const3
2697// where OP is both an associative and a commutative operation.
2698bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2699 HBinaryOperation* instruction) {
2700 DCHECK(instruction->IsCommutative());
2701
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002702 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002703 return false;
2704 }
2705
2706 HInstruction* left = instruction->GetLeft();
2707 HInstruction* right = instruction->GetRight();
2708 // Variable names as described above.
2709 HConstant* const2;
2710 HBinaryOperation* y;
2711
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002712 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002713 const2 = right->AsConstant();
2714 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01002715 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002716 const2 = left->AsConstant();
2717 y = right->AsBinaryOperation();
2718 } else {
2719 // The node does not match the pattern.
2720 return false;
2721 }
2722
2723 // If `y` has more than one use, we do not perform the optimization
2724 // because it might increase code size (e.g. if the new constant is
2725 // no longer encodable as an immediate operand in the target ISA).
2726 if (!y->HasOnlyOneNonEnvironmentUse()) {
2727 return false;
2728 }
2729
2730 // GetConstantRight() can return both left and right constants
2731 // for commutative operations.
2732 HConstant* const1 = y->GetConstantRight();
2733 if (const1 == nullptr) {
2734 return false;
2735 }
2736
2737 instruction->ReplaceInput(const1, 0);
2738 instruction->ReplaceInput(const2, 1);
2739 HConstant* const3 = instruction->TryStaticEvaluation();
2740 DCHECK(const3 != nullptr);
2741 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2742 instruction->ReplaceInput(const3, 1);
2743 RecordSimplification();
2744 return true;
2745}
2746
2747static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2748 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2749}
2750
2751// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002752static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002753 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002754 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002755 return HAdd::Compute<int32_t>(x, y);
2756 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002757 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002758 return HAdd::Compute<int64_t>(x, y);
2759 }
2760}
2761
2762// Helper function that handles the child classes of HConstant
2763// and returns an integer with the appropriate sign.
2764static int64_t GetValue(HConstant* constant, bool is_negated) {
2765 int64_t ret = Int64FromConstant(constant);
2766 return is_negated ? -ret : ret;
2767}
2768
2769// Replace code looking like
2770// OP1 y, x, const1
2771// OP2 z, y, const2
2772// with
2773// OP3 z, x, const3
2774// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2775bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2776 HBinaryOperation* instruction) {
2777 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2778
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002779 DataType::Type type = instruction->GetType();
2780 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002781 return false;
2782 }
2783
2784 HInstruction* left = instruction->GetLeft();
2785 HInstruction* right = instruction->GetRight();
2786 // Variable names as described above.
2787 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2788 if (const2 == nullptr) {
2789 return false;
2790 }
2791
2792 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2793 ? left->AsBinaryOperation()
2794 : AsAddOrSub(right);
2795 // If y has more than one use, we do not perform the optimization because
2796 // it might increase code size (e.g. if the new constant is no longer
2797 // encodable as an immediate operand in the target ISA).
2798 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2799 return false;
2800 }
2801
2802 left = y->GetLeft();
2803 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2804 if (const1 == nullptr) {
2805 return false;
2806 }
2807
2808 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2809 // If both inputs are constants, let the constant folding pass deal with it.
2810 if (x->IsConstant()) {
2811 return false;
2812 }
2813
2814 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2815 int64_t const2_val = GetValue(const2, is_const2_negated);
2816 bool is_y_negated = (y == right) && instruction->IsSub();
2817 right = y->GetRight();
2818 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2819 int64_t const1_val = GetValue(const1, is_const1_negated);
2820 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2821 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2822 HBasicBlock* block = instruction->GetBlock();
2823 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002824 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01002825 HInstruction* z;
2826
2827 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002828 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002829 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002830 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01002831 }
2832
2833 block->ReplaceAndRemoveInstructionWith(instruction, z);
2834 RecordSimplification();
2835 return true;
2836}
2837
Lena Djokicbc5460b2017-07-20 16:07:36 +02002838void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2839 if (TryCombineVecMultiplyAccumulate(instruction)) {
2840 RecordSimplification();
2841 }
2842}
2843
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002844} // namespace art