blob: 789f07786c6eee05b0bd6295557488ea4b1085a9 [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 Marko5868ada2020-05-12 11:50:34 +010021#include "class_root-inl.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010022#include "data_type-inl.h"
Vladimir Marko9d31daa2022-04-14 10:48:44 +010023#include "driver/compiler_options.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080024#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025#include "intrinsics.h"
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +000026#include "intrinsics_utils.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027#include "mirror/class-inl.h"
Artem Serove91a9542021-10-25 16:23:27 +010028#include "optimizing/data_type.h"
Alex Light3a73ffb2021-01-25 14:11:05 +000029#include "optimizing/nodes.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070030#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070031#include "sharpening.h"
Vladimir Marko552a1342017-10-31 10:56:47 +000032#include "string_builder_append.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000033
Vladimir Marko0a516052019-10-14 13:00:44 +000034namespace art {
Nicolas Geoffray3c049742014-09-24 18:10:46 +010035
Artem Serovcced8ba2017-07-19 18:18:09 +010036// Whether to run an exhaustive test of individual HInstructions cloning when each instruction
37// is replaced with its copy if it is clonable.
38static constexpr bool kTestInstructionClonerExhaustively = false;
39
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010040class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000041 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000042 InstructionSimplifierVisitor(HGraph* graph,
43 CodeGenerator* codegen,
Evgeny Astigeevich6587d912020-06-12 10:51:43 +010044 OptimizingCompilerStats* stats,
45 bool be_loop_friendly)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010046 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000047 codegen_(codegen),
Evgeny Astigeevich6587d912020-06-12 10:51:43 +010048 stats_(stats),
49 be_loop_friendly_(be_loop_friendly) {}
Alexandre Rames188d4312015-04-09 18:30:21 +010050
Aart Bik24773202018-04-26 10:28:51 -070051 bool Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000052
53 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010054 void RecordSimplification() {
55 simplification_occurred_ = true;
56 simplifications_at_current_position_++;
Vladimir Markocd09e1f2017-11-24 15:02:40 +000057 MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010058 }
59
Scott Wakeling40a04bf2015-12-11 09:50:36 +000060 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
61 bool TryReplaceWithRotate(HBinaryOperation* instruction);
62 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
63 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
64 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
65
Alexandre Rames188d4312015-04-09 18:30:21 +010066 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000067 // `op` should be either HOr or HAnd.
68 // De Morgan's laws:
69 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
70 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010071 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
72 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020073 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Evgeny Astigeevich6587d912020-06-12 10:51:43 +010074 void TryToReuseDiv(HRem* rem);
Anton Kirilove14dc862016-05-13 17:56:15 +010075
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000076 void VisitShift(HBinaryOperation* shift);
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010077 void VisitEqual(HEqual* equal) override;
78 void VisitNotEqual(HNotEqual* equal) override;
79 void VisitBooleanNot(HBooleanNot* bool_not) override;
80 void VisitInstanceFieldSet(HInstanceFieldSet* equal) override;
81 void VisitStaticFieldSet(HStaticFieldSet* equal) override;
82 void VisitArraySet(HArraySet* equal) override;
83 void VisitTypeConversion(HTypeConversion* instruction) override;
84 void VisitNullCheck(HNullCheck* instruction) override;
85 void VisitArrayLength(HArrayLength* instruction) override;
86 void VisitCheckCast(HCheckCast* instruction) override;
87 void VisitAbs(HAbs* instruction) override;
88 void VisitAdd(HAdd* instruction) override;
89 void VisitAnd(HAnd* instruction) override;
90 void VisitCondition(HCondition* instruction) override;
91 void VisitGreaterThan(HGreaterThan* condition) override;
92 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) override;
93 void VisitLessThan(HLessThan* condition) override;
94 void VisitLessThanOrEqual(HLessThanOrEqual* condition) override;
95 void VisitBelow(HBelow* condition) override;
96 void VisitBelowOrEqual(HBelowOrEqual* condition) override;
97 void VisitAbove(HAbove* condition) override;
98 void VisitAboveOrEqual(HAboveOrEqual* condition) override;
99 void VisitDiv(HDiv* instruction) override;
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100100 void VisitRem(HRem* instruction) override;
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100101 void VisitMul(HMul* instruction) override;
102 void VisitNeg(HNeg* instruction) override;
103 void VisitNot(HNot* instruction) override;
104 void VisitOr(HOr* instruction) override;
105 void VisitShl(HShl* instruction) override;
106 void VisitShr(HShr* instruction) override;
107 void VisitSub(HSub* instruction) override;
108 void VisitUShr(HUShr* instruction) override;
109 void VisitXor(HXor* instruction) override;
110 void VisitSelect(HSelect* select) override;
111 void VisitIf(HIf* instruction) override;
112 void VisitInstanceOf(HInstanceOf* instruction) override;
113 void VisitInvoke(HInvoke* invoke) override;
114 void VisitDeoptimize(HDeoptimize* deoptimize) override;
115 void VisitVecMul(HVecMul* instruction) override;
Alex Light3a73ffb2021-01-25 14:11:05 +0000116 void VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet* instruction) override;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100117 void SimplifySystemArrayCopy(HInvoke* invoke);
118 void SimplifyStringEquals(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800119 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100120 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Marko5f846072020-04-09 13:20:11 +0100121 void SimplifyStringLength(HInvoke* invoke);
Vladimir Marko6fa44042018-03-19 18:42:49 +0000122 void SimplifyStringIndexOf(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800123 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800124 void SimplifyReturnThis(HInvoke* invoke);
125 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +0000126 void SimplifyVarHandleIntrinsic(HInvoke* invoke);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100127
Vladimir Marko9d31daa2022-04-14 10:48:44 +0100128 bool CanUseKnownBootImageVarHandle(HInvoke* invoke);
Ulya Trafimovich3676b362021-09-02 16:13:51 +0100129 static bool CanEnsureNotNullAt(HInstruction* input, HInstruction* at);
130
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000131 CodeGenerator* codegen_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000132 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100133 bool simplification_occurred_ = false;
134 int simplifications_at_current_position_ = 0;
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100135 // Prohibit optimizations which can affect HInductionVarAnalysis/HLoopOptimization
136 // and prevent loop optimizations:
137 // true - avoid such optimizations.
138 // false - allow such optimizations.
139 // Checked by the following optimizations:
140 // - TryToReuseDiv: simplification of Div+Rem into Div+Mul+Sub.
141 bool be_loop_friendly_;
Aart Bik2767f4b2016-10-28 15:03:53 -0700142 // We ensure we do not loop infinitely. The value should not be too high, since that
143 // would allow looping around the same basic block too many times. The value should
144 // not be too low either, however, since we want to allow revisiting a basic block
145 // with many statements and simplifications at least once.
146 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000147};
148
Aart Bik24773202018-04-26 10:28:51 -0700149bool InstructionSimplifier::Run() {
Artem Serovcced8ba2017-07-19 18:18:09 +0100150 if (kTestInstructionClonerExhaustively) {
151 CloneAndReplaceInstructionVisitor visitor(graph_);
152 visitor.VisitReversePostOrder();
153 }
154
Evgeny Astigeevich6587d912020-06-12 10:51:43 +0100155 bool be_loop_friendly = (use_all_optimizations_ == false);
156
157 InstructionSimplifierVisitor visitor(graph_, codegen_, stats_, be_loop_friendly);
Aart Bik24773202018-04-26 10:28:51 -0700158 return visitor.Run();
Alexandre Rames188d4312015-04-09 18:30:21 +0100159}
160
Aart Bik24773202018-04-26 10:28:51 -0700161bool InstructionSimplifierVisitor::Run() {
162 bool didSimplify = false;
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100163 // Iterate in reverse post order to open up more simplifications to users
164 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100165 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100166 // The simplification of an instruction to another instruction may yield
167 // possibilities for other simplifications. So although we perform a reverse
168 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100169 do {
170 simplification_occurred_ = false;
171 VisitBasicBlock(block);
Aart Bik24773202018-04-26 10:28:51 -0700172 if (simplification_occurred_) {
173 didSimplify = true;
174 }
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100175 } while (simplification_occurred_ &&
176 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100177 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100178 }
Aart Bik24773202018-04-26 10:28:51 -0700179 return didSimplify;
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100180}
181
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000182namespace {
183
184bool AreAllBitsSet(HConstant* constant) {
185 return Int64FromConstant(constant) == -1;
186}
187
188} // namespace
189
Alexandre Rames188d4312015-04-09 18:30:21 +0100190// Returns true if the code was simplified to use only one negation operation
191// after the binary operation instead of one on each of the inputs.
192bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
193 DCHECK(binop->IsAdd() || binop->IsSub());
194 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
195 HNeg* left_neg = binop->GetLeft()->AsNeg();
196 HNeg* right_neg = binop->GetRight()->AsNeg();
197 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
198 !right_neg->HasOnlyOneNonEnvironmentUse()) {
199 return false;
200 }
201 // Replace code looking like
202 // NEG tmp1, a
203 // NEG tmp2, b
204 // ADD dst, tmp1, tmp2
205 // with
206 // ADD tmp, a, b
207 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600208 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
209 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
210 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100211 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600212 return false;
213 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100214 binop->ReplaceInput(left_neg->GetInput(), 0);
215 binop->ReplaceInput(right_neg->GetInput(), 1);
216 left_neg->GetBlock()->RemoveInstruction(left_neg);
217 right_neg->GetBlock()->RemoveInstruction(right_neg);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100218 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(binop->GetType(), binop);
Alexandre Rames188d4312015-04-09 18:30:21 +0100219 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
220 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
221 RecordSimplification();
222 return true;
223}
224
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000225bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
226 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100227 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000228 HInstruction* left = op->GetLeft();
229 HInstruction* right = op->GetRight();
230
231 // We can apply De Morgan's laws if both inputs are Not's and are only used
232 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000233 if (((left->IsNot() && right->IsNot()) ||
234 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000235 left->HasOnlyOneNonEnvironmentUse() &&
236 right->HasOnlyOneNonEnvironmentUse()) {
237 // Replace code looking like
238 // NOT nota, a
239 // NOT notb, b
240 // AND dst, nota, notb (respectively OR)
241 // with
242 // OR or, a, b (respectively AND)
243 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000244 HInstruction* src_left = left->InputAt(0);
245 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000246 uint32_t dex_pc = op->GetDexPc();
247
248 // Remove the negations on the inputs.
249 left->ReplaceWith(src_left);
250 right->ReplaceWith(src_right);
251 left->GetBlock()->RemoveInstruction(left);
252 right->GetBlock()->RemoveInstruction(right);
253
254 // Replace the `HAnd` or `HOr`.
255 HBinaryOperation* hbin;
256 if (op->IsAnd()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100257 hbin = new (GetGraph()->GetAllocator()) HOr(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000258 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100259 hbin = new (GetGraph()->GetAllocator()) HAnd(type, src_left, src_right, dex_pc);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000260 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000261 HInstruction* hnot;
262 if (left->IsBooleanNot()) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100263 hnot = new (GetGraph()->GetAllocator()) HBooleanNot(hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000264 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100265 hnot = new (GetGraph()->GetAllocator()) HNot(type, hbin, dex_pc);
Alexandre Rames9f980252016-02-05 14:00:28 +0000266 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000267
268 op->GetBlock()->InsertInstructionBefore(hbin, op);
269 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
270
271 RecordSimplification();
272 return true;
273 }
274
275 return false;
276}
277
Lena Djokicbc5460b2017-07-20 16:07:36 +0200278bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100279 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200280 InstructionSet isa = codegen_->GetInstructionSet();
281 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000282 case InstructionSet::kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100283 if (!(type == DataType::Type::kUint8 ||
284 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100285 type == DataType::Type::kUint16 ||
286 type == DataType::Type::kInt16 ||
287 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200288 return false;
289 }
290 break;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200291 default:
292 return false;
293 }
294
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100295 ArenaAllocator* allocator = mul->GetBlock()->GetGraph()->GetAllocator();
Artem Serov8ba4de12019-12-04 21:10:23 +0000296 if (!mul->HasOnlyOneNonEnvironmentUse()) {
297 return false;
298 }
299 HInstruction* binop = mul->GetUses().front().GetUser();
300 if (!binop->IsVecAdd() && !binop->IsVecSub()) {
301 return false;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200302 }
303
Artem Serov8ba4de12019-12-04 21:10:23 +0000304 // Replace code looking like
305 // VECMUL tmp, x, y
306 // VECADD/SUB dst, acc, tmp
307 // with
308 // VECMULACC dst, acc, x, y
309 // Note that we do not want to (unconditionally) perform the merge when the
310 // multiplication has multiple uses and it can be merged in all of them.
311 // Multiple uses could happen on the same control-flow path, and we would
312 // then increase the amount of work. In the future we could try to evaluate
313 // whether all uses are on different control-flow paths (using dominance and
314 // reverse-dominance information) and only perform the merge when they are.
315 HInstruction* accumulator = nullptr;
316 HVecBinaryOperation* vec_binop = binop->AsVecBinaryOperation();
317 HInstruction* binop_left = vec_binop->GetLeft();
318 HInstruction* binop_right = vec_binop->GetRight();
319 // This is always true since the `HVecMul` has only one use (which is checked above).
320 DCHECK_NE(binop_left, binop_right);
321 if (binop_right == mul) {
322 accumulator = binop_left;
323 } else {
324 DCHECK_EQ(binop_left, mul);
325 // Only addition is commutative.
326 if (!binop->IsVecAdd()) {
327 return false;
328 }
329 accumulator = binop_right;
330 }
331
332 DCHECK(accumulator != nullptr);
333 HInstruction::InstructionKind kind =
334 binop->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
335
336 bool predicated_simd = vec_binop->IsPredicated();
337 if (predicated_simd && !HVecOperation::HaveSamePredicate(vec_binop, mul)) {
338 return false;
339 }
340
341 HVecMultiplyAccumulate* mulacc =
342 new (allocator) HVecMultiplyAccumulate(allocator,
343 kind,
344 accumulator,
345 mul->GetLeft(),
346 mul->GetRight(),
347 vec_binop->GetPackedType(),
348 vec_binop->GetVectorLength(),
349 vec_binop->GetDexPc());
350
351
352
353 vec_binop->GetBlock()->ReplaceAndRemoveInstructionWith(vec_binop, mulacc);
354 if (predicated_simd) {
355 mulacc->SetGoverningPredicate(vec_binop->GetGoverningPredicate(),
356 vec_binop->GetPredicationKind());
357 }
358
359 DCHECK(!mul->HasUses());
360 mul->GetBlock()->RemoveInstruction(mul);
361 return true;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200362}
363
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000364void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
365 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100366 HInstruction* shift_amount = instruction->GetRight();
367 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000368
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100369 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100370 ? kMaxLongShiftDistance
371 : kMaxIntShiftDistance;
372
373 if (shift_amount->IsConstant()) {
374 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700375 int64_t masked_cst = cst & implicit_mask;
376 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400377 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100378 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400379 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100380 // value
381 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400382 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100383 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100384 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700385 } else if (masked_cst != cst) {
386 // Replace code looking like
387 // SHL dst, value, cst
388 // where cst exceeds maximum distance with the equivalent
389 // SHL dst, value, cst & implicit_mask
390 // (as defined by shift semantics). This ensures other
391 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100392 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Andreas Gampe3db70682018-12-26 15:12:03 -0800393 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index= */ 1);
Aart Bik50e20d52017-05-05 14:07:29 -0700394 RecordSimplification();
395 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100396 }
397 }
398
399 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100400 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
401 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100402 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100403 // AND adjusted_shift, shift, <superset of implicit mask>
404 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
405 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
406 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100407 // with
408 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100409 if (shift_amount->IsAnd() ||
410 shift_amount->IsOr() ||
411 shift_amount->IsXor() ||
412 shift_amount->IsAdd() ||
413 shift_amount->IsSub()) {
414 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
415 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
416 HConstant* mask = bin_op->GetConstantRight();
417 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
418 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100419 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100420 return;
421 }
422 } else if (shift_amount->IsTypeConversion()) {
423 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
424 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
425 // Non-integral and 64-bit source types require an explicit type conversion.
426 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
427 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
428 RecordSimplification();
429 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400430 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000431 }
432}
433
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000434static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
435 return (sub->GetRight() == other &&
436 sub->GetLeft()->IsConstant() &&
437 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
438}
439
440bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
441 HUShr* ushr,
442 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000443 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
Vladimir Markoca6fff82017-10-03 14:49:14 +0100444 HRor* ror =
445 new (GetGraph()->GetAllocator()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000446 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
447 if (!ushr->HasUses()) {
448 ushr->GetBlock()->RemoveInstruction(ushr);
449 }
450 if (!ushr->GetRight()->HasUses()) {
451 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
452 }
453 if (!shl->HasUses()) {
454 shl->GetBlock()->RemoveInstruction(shl);
455 }
456 if (!shl->GetRight()->HasUses()) {
457 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
458 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100459 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000460 return true;
461}
462
463// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
464bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000465 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
466 HInstruction* left = op->GetLeft();
467 HInstruction* right = op->GetRight();
468 // If we have an UShr and a Shl (in either order).
469 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
470 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
471 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100472 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000473 if (ushr->GetType() == shl->GetType() &&
474 ushr->GetLeft() == shl->GetLeft()) {
475 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
476 // Shift distances are both constant, try replacing with Ror if they
477 // add up to the register size.
478 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
479 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
480 // Shift distances are potentially of the form x and (reg_size - x).
481 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
482 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
483 // Shift distances are potentially of the form d and -d.
484 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
485 }
486 }
487 }
488 return false;
489}
490
491// Try replacing code looking like (x >>> #rdist OP x << #ldist):
492// UShr dst, x, #rdist
493// Shl tmp, x, #ldist
494// OP dst, dst, tmp
495// or like (x >>> #rdist OP x << #-ldist):
496// UShr dst, x, #rdist
497// Shl tmp, x, #-ldist
498// OP dst, dst, tmp
499// with
500// Ror dst, x, #rdist
501bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
502 HUShr* ushr,
503 HShl* shl) {
504 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100505 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000506 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
507 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
508 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
509 ReplaceRotateWithRor(op, ushr, shl);
510 return true;
511 }
512 return false;
513}
514
515// Replace code looking like (x >>> -d OP x << d):
516// Neg neg, d
517// UShr dst, x, neg
518// Shl tmp, x, d
519// OP dst, dst, tmp
520// with
521// Neg neg, d
522// Ror dst, x, neg
523// *** OR ***
524// Replace code looking like (x >>> d OP x << -d):
525// UShr dst, x, d
526// Neg neg, d
527// Shl tmp, x, neg
528// OP dst, dst, tmp
529// with
530// Ror dst, x, d
531bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
532 HUShr* ushr,
533 HShl* shl) {
534 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
535 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
536 bool neg_is_left = shl->GetRight()->IsNeg();
537 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
538 // And the shift distance being negated is the distance being shifted the other way.
539 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
540 ReplaceRotateWithRor(op, ushr, shl);
541 }
542 return false;
543}
544
545// Try replacing code looking like (x >>> d OP x << (#bits - d)):
546// UShr dst, x, d
547// Sub ld, #bits, d
548// Shl tmp, x, ld
549// OP dst, dst, tmp
550// with
551// Ror dst, x, d
552// *** OR ***
553// Replace code looking like (x >>> (#bits - d) OP x << d):
554// Sub rd, #bits, d
555// UShr dst, x, rd
556// Shl tmp, x, d
557// OP dst, dst, tmp
558// with
559// Neg neg, d
560// Ror dst, x, neg
561bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
562 HUShr* ushr,
563 HShl* shl) {
564 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
565 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100566 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000567 HInstruction* shl_shift = shl->GetRight();
568 HInstruction* ushr_shift = ushr->GetRight();
569 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
570 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
571 return ReplaceRotateWithRor(op, ushr, shl);
572 }
573 return false;
574}
575
Calin Juravle10e244f2015-01-26 18:54:32 +0000576void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
577 HInstruction* obj = null_check->InputAt(0);
578 if (!obj->CanBeNull()) {
579 null_check->ReplaceWith(obj);
580 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000581 if (stats_ != nullptr) {
582 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
583 }
584 }
585}
586
Ulya Trafimovich3676b362021-09-02 16:13:51 +0100587bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) {
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100588 if (!input->CanBeNull()) {
589 return true;
590 }
591
Vladimir Marko46817b82016-03-29 12:21:58 +0100592 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
593 HInstruction* user = use.GetUser();
594 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100595 return true;
596 }
597 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100598
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100599 return false;
600}
601
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100602// Returns whether doing a type test between the class of `object` against `klass` has
603// a statically known outcome. The result of the test is stored in `outcome`.
Vladimir Marko175e7862018-03-27 09:03:13 +0000604static bool TypeCheckHasKnownOutcome(ReferenceTypeInfo class_rti,
605 HInstruction* object,
606 /*out*/bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000607 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
608 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
609 ScopedObjectAccess soa(Thread::Current());
610 if (!obj_rti.IsValid()) {
611 // We run the simplifier before the reference type propagation so type info might not be
612 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100613 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000614 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100615
Calin Juravle98893e12015-10-02 21:05:03 +0100616 if (!class_rti.IsValid()) {
617 // Happens when the loaded class is unresolved.
Alex Lightbb550e42021-04-21 17:04:13 -0700618 if (obj_rti.IsExact()) {
619 // outcome == 'true' && obj_rti is valid implies that class_rti is valid.
620 // Since that's a contradiction we must not pass this check.
621 *outcome = false;
622 return true;
623 } else {
624 // We aren't able to say anything in particular since we don't know the
625 // exact type of the object.
626 return false;
627 }
Calin Juravle98893e12015-10-02 21:05:03 +0100628 }
629 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000630 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100631 *outcome = true;
632 return true;
633 } else if (obj_rti.IsExact()) {
634 // The test failed at compile time so will also fail at runtime.
635 *outcome = false;
636 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100637 } else if (!class_rti.IsInterface()
638 && !obj_rti.IsInterface()
639 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100640 // Different type hierarchy. The test will fail.
641 *outcome = false;
642 return true;
643 }
644 return false;
645}
646
647void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
648 HInstruction* object = check_cast->InputAt(0);
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100649 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100650 check_cast->ClearMustDoNullCheck();
651 }
652
653 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000654 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700655 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100656 return;
657 }
658
Alex Lightbb550e42021-04-21 17:04:13 -0700659 // Minor correctness check.
660 DCHECK(check_cast->GetTargetClass()->StrictlyDominates(check_cast))
661 << "Illegal graph!\n"
662 << check_cast->DumpWithArgs();
663
Roland Levillain05e34f42018-05-24 13:19:05 +0000664 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
665 // the return value check with the `outcome` check, b/27651442.
Vladimir Markoa65ed302016-03-14 21:21:29 +0000666 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000667 if (TypeCheckHasKnownOutcome(check_cast->GetTargetClassRTI(), object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100668 if (outcome) {
669 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700670 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Vladimir Marko175e7862018-03-27 09:03:13 +0000671 if (check_cast->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
672 HLoadClass* load_class = check_cast->GetTargetClass();
Alex Lightbb550e42021-04-21 17:04:13 -0700673 if (!load_class->HasUses() && !load_class->NeedsAccessCheck()) {
Vladimir Marko175e7862018-03-27 09:03:13 +0000674 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
Alex Lightbb550e42021-04-21 17:04:13 -0700675 // However, here we know that it cannot because the checkcast was successful, hence
Vladimir Marko175e7862018-03-27 09:03:13 +0000676 // the class was already loaded.
677 load_class->GetBlock()->RemoveInstruction(load_class);
678 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700679 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100680 } else {
Alex Lightbb550e42021-04-21 17:04:13 -0700681 // TODO Don't do anything for exceptional cases for now. Ideally we should
682 // remove all instructions and blocks this instruction dominates and
683 // replace it with a manual throw.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100684 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000685 }
686}
687
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100688void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100689 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100690
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100691 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100692 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100693 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100694 instruction->ClearMustDoNullCheck();
695 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100696
697 HGraph* graph = GetGraph();
698 if (object->IsNullConstant()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000699 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100700 instruction->ReplaceWith(graph->GetIntConstant(0));
701 instruction->GetBlock()->RemoveInstruction(instruction);
702 RecordSimplification();
703 return;
704 }
705
Alex Lightbb550e42021-04-21 17:04:13 -0700706 // Minor correctness check.
707 DCHECK(instruction->GetTargetClass()->StrictlyDominates(instruction))
708 << "Illegal graph!\n"
709 << instruction->DumpWithArgs();
710
Roland Levillain05e34f42018-05-24 13:19:05 +0000711 // Historical note: The `outcome` was initialized to please Valgrind - the compiler can reorder
712 // the return value check with the `outcome` check, b/27651442.
Vladimir Marko24bd8952016-03-15 10:40:33 +0000713 bool outcome = false;
Vladimir Marko175e7862018-03-27 09:03:13 +0000714 if (TypeCheckHasKnownOutcome(instruction->GetTargetClassRTI(), object, &outcome)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000715 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100716 if (outcome && can_be_null) {
717 // Type test will succeed, we just need a null test.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100718 HNotEqual* test = new (graph->GetAllocator()) HNotEqual(graph->GetNullConstant(), object);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100719 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
720 instruction->ReplaceWith(test);
721 } else {
722 // We've statically determined the result of the instanceof.
723 instruction->ReplaceWith(graph->GetIntConstant(outcome));
724 }
725 RecordSimplification();
726 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko175e7862018-03-27 09:03:13 +0000727 if (outcome && instruction->GetTypeCheckKind() != TypeCheckKind::kBitstringCheck) {
728 HLoadClass* load_class = instruction->GetTargetClass();
Alex Lightbb550e42021-04-21 17:04:13 -0700729 if (!load_class->HasUses() && !load_class->NeedsAccessCheck()) {
730 // We cannot rely on DCE to remove the class because the `HLoadClass`
731 // thinks it can throw. However, here we know that it cannot because the
732 // instanceof check was successful and we don't need to check the
733 // access, hence the class was already loaded.
Vladimir Marko175e7862018-03-27 09:03:13 +0000734 load_class->GetBlock()->RemoveInstruction(load_class);
735 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700736 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100737 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100738}
739
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100740void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100741 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100742 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100743 instruction->ClearValueCanBeNull();
744 }
745}
746
747void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100748 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100749 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100750 instruction->ClearValueCanBeNull();
751 }
752}
753
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100754static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* allocator, HInstruction* cond) {
Anton Shaminbdd79352016-02-15 12:48:36 +0600755 HInstruction *lhs = cond->InputAt(0);
756 HInstruction *rhs = cond->InputAt(1);
757 switch (cond->GetKind()) {
758 case HInstruction::kEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100759 return new (allocator) HEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600760 case HInstruction::kNotEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100761 return new (allocator) HNotEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600762 case HInstruction::kLessThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100763 return new (allocator) HGreaterThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600764 case HInstruction::kLessThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100765 return new (allocator) HGreaterThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600766 case HInstruction::kGreaterThan:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100767 return new (allocator) HLessThan(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600768 case HInstruction::kGreaterThanOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100769 return new (allocator) HLessThanOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600770 case HInstruction::kBelow:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100771 return new (allocator) HAbove(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600772 case HInstruction::kBelowOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100773 return new (allocator) HAboveOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600774 case HInstruction::kAbove:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100775 return new (allocator) HBelow(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600776 case HInstruction::kAboveOrEqual:
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100777 return new (allocator) HBelowOrEqual(rhs, lhs);
Anton Shaminbdd79352016-02-15 12:48:36 +0600778 default:
779 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
Elliott Hughesc1896c92018-11-29 11:33:18 -0800780 UNREACHABLE();
Anton Shaminbdd79352016-02-15 12:48:36 +0600781 }
Anton Shaminbdd79352016-02-15 12:48:36 +0600782}
783
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000784void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100785 HInstruction* input_const = equal->GetConstantRight();
786 if (input_const != nullptr) {
787 HInstruction* input_value = equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100788 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100789 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100790 // We are comparing the boolean to a constant which is of type int and can
791 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000792 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100793 // Replace (bool_value == true) with bool_value
794 equal->ReplaceWith(input_value);
795 block->RemoveInstruction(equal);
796 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000797 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700798 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500799 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
800 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100801 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100802 } else {
803 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
804 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
805 block->RemoveInstruction(equal);
806 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100807 }
Mark Mendellc4701932015-04-10 13:18:51 -0400808 } else {
809 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100810 }
Mark Mendellc4701932015-04-10 13:18:51 -0400811 } else {
812 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100813 }
814}
815
David Brazdil0d13fee2015-04-17 14:52:19 +0100816void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
817 HInstruction* input_const = not_equal->GetConstantRight();
818 if (input_const != nullptr) {
819 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Nicolas Geoffrayeb104c82019-06-03 17:58:34 +0100820 if ((input_value->GetType() == DataType::Type::kBool) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100821 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100822 // We are comparing the boolean to a constant which is of type int and can
823 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000824 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700825 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500826 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
827 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100828 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000829 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100830 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100831 not_equal->ReplaceWith(input_value);
832 block->RemoveInstruction(not_equal);
833 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100834 } else {
835 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
836 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
837 block->RemoveInstruction(not_equal);
838 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100839 }
Mark Mendellc4701932015-04-10 13:18:51 -0400840 } else {
841 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100842 }
Mark Mendellc4701932015-04-10 13:18:51 -0400843 } else {
844 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100845 }
846}
847
848void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000849 HInstruction* input = bool_not->InputAt(0);
850 HInstruction* replace_with = nullptr;
851
852 if (input->IsIntConstant()) {
853 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000854 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000855 replace_with = GetGraph()->GetIntConstant(0);
856 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000857 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000858 replace_with = GetGraph()->GetIntConstant(1);
859 }
860 } else if (input->IsBooleanNot()) {
861 // Replace (!(!bool_value)) with bool_value.
862 replace_with = input->InputAt(0);
863 } else if (input->IsCondition() &&
864 // Don't change FP compares. The definition of compares involving
865 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100866 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000867 // Replace condition with its opposite.
868 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
869 }
870
871 if (replace_with != nullptr) {
872 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100873 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000874 RecordSimplification();
875 }
876}
877
Aart Bik4f7dd342017-09-12 13:12:57 -0700878// Constructs a new ABS(x) node in the HIR.
Vladimir Markoe764d2e2017-10-05 14:35:55 +0100879static HInstruction* NewIntegralAbs(ArenaAllocator* allocator,
880 HInstruction* x,
881 HInstruction* cursor) {
Aart Bik2286da22018-03-22 10:50:22 -0700882 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik3dad3412018-02-28 12:01:46 -0800883 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik142b9132018-03-14 15:12:59 -0700884 HAbs* abs = new (allocator) HAbs(type, x, cursor->GetDexPc());
Aart Bik3dad3412018-02-28 12:01:46 -0800885 cursor->GetBlock()->InsertInstructionBefore(abs, cursor);
886 return abs;
Aart Bik4f7dd342017-09-12 13:12:57 -0700887}
888
Aart Bik142b9132018-03-14 15:12:59 -0700889// Constructs a new MIN/MAX(x, y) node in the HIR.
890static HInstruction* NewIntegralMinMax(ArenaAllocator* allocator,
891 HInstruction* x,
892 HInstruction* y,
893 HInstruction* cursor,
894 bool is_min) {
Aart Bik2286da22018-03-22 10:50:22 -0700895 DataType::Type type = DataType::Kind(x->GetType());
Aart Bik142b9132018-03-14 15:12:59 -0700896 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
897 HBinaryOperation* minmax = nullptr;
898 if (is_min) {
899 minmax = new (allocator) HMin(type, x, y, cursor->GetDexPc());
900 } else {
901 minmax = new (allocator) HMax(type, x, y, cursor->GetDexPc());
902 }
903 cursor->GetBlock()->InsertInstructionBefore(minmax, cursor);
904 return minmax;
905}
906
Aart Bik4f7dd342017-09-12 13:12:57 -0700907// Returns true if operands a and b consists of widening type conversions
908// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100909static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700910 if (a->IsTypeConversion() && a->GetType() == to_type) {
911 a = a->InputAt(0);
912 }
913 if (b->IsTypeConversion() && b->GetType() == to_type) {
914 b = b->InputAt(0);
915 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100916 DataType::Type type1 = a->GetType();
917 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100918 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
919 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
920 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
921 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
922 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100923 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700924}
925
Aart Bik1d746de2018-03-28 16:30:02 -0700926// Returns an acceptable substitution for "a" on the select
927// construct "a <cmp> b ? c : .." during MIN/MAX recognition.
928static HInstruction* AllowInMinMax(IfCondition cmp,
929 HInstruction* a,
930 HInstruction* b,
931 HInstruction* c) {
932 int64_t value = 0;
933 if (IsInt64AndGet(b, /*out*/ &value) &&
934 (((cmp == kCondLT || cmp == kCondLE) && c->IsMax()) ||
935 ((cmp == kCondGT || cmp == kCondGE) && c->IsMin()))) {
936 HConstant* other = c->AsBinaryOperation()->GetConstantRight();
937 if (other != nullptr && a == c->AsBinaryOperation()->GetLeastConstantLeft()) {
938 int64_t other_value = Int64FromConstant(other);
939 bool is_max = (cmp == kCondLT || cmp == kCondLE);
940 // Allow the max for a < 100 ? max(a, -100) : ..
941 // or the min for a > -100 ? min(a, 100) : ..
942 if (is_max ? (value >= other_value) : (value <= other_value)) {
943 return c;
944 }
945 }
946 }
947 return nullptr;
948}
949
Alex Light3a73ffb2021-01-25 14:11:05 +0000950// TODO This should really be done by LSE itself since there is significantly
951// more information available there.
952void InstructionSimplifierVisitor::VisitPredicatedInstanceFieldGet(
953 HPredicatedInstanceFieldGet* pred_get) {
954 HInstruction* target = pred_get->GetTarget();
955 HInstruction* default_val = pred_get->GetDefaultValue();
Alex Lightba320162021-04-22 15:15:13 -0700956 if (target->IsNullConstant()) {
957 pred_get->ReplaceWith(default_val);
958 pred_get->GetBlock()->RemoveInstruction(pred_get);
959 RecordSimplification();
Alex Light3a73ffb2021-01-25 14:11:05 +0000960 return;
Alex Lightba320162021-04-22 15:15:13 -0700961 } else if (!target->CanBeNull()) {
Alex Light74328052021-03-29 18:11:23 -0700962 HInstruction* replace_with = new (GetGraph()->GetAllocator())
963 HInstanceFieldGet(pred_get->GetTarget(),
964 pred_get->GetFieldInfo().GetField(),
965 pred_get->GetFieldType(),
966 pred_get->GetFieldOffset(),
967 pred_get->IsVolatile(),
968 pred_get->GetFieldInfo().GetFieldIndex(),
969 pred_get->GetFieldInfo().GetDeclaringClassDefIndex(),
970 pred_get->GetFieldInfo().GetDexFile(),
971 pred_get->GetDexPc());
972 if (pred_get->GetType() == DataType::Type::kReference) {
973 replace_with->SetReferenceTypeInfo(pred_get->GetReferenceTypeInfo());
974 }
975 pred_get->GetBlock()->InsertInstructionBefore(replace_with, pred_get);
976 pred_get->ReplaceWith(replace_with);
977 pred_get->GetBlock()->RemoveInstruction(pred_get);
978 RecordSimplification();
Alex Lightba320162021-04-22 15:15:13 -0700979 return;
980 }
981 if (!target->IsPhi() || !default_val->IsPhi() || default_val->GetBlock() != target->GetBlock()) {
982 // The iget has already been reduced. We know the target or the phi
983 // selection will differ between the target and default.
984 return;
985 }
986 DCHECK_EQ(default_val->InputCount(), target->InputCount());
987 // In the same block both phis only one non-null we can remove the phi from default_val.
988 HInstruction* single_value = nullptr;
989 auto inputs = target->GetInputs();
990 for (auto [input, idx] : ZipCount(MakeIterationRange(inputs))) {
991 if (input->CanBeNull()) {
992 if (single_value == nullptr) {
993 single_value = default_val->InputAt(idx);
994 } else if (single_value != default_val->InputAt(idx) &&
995 !single_value->Equals(default_val->InputAt(idx))) {
996 // Multiple values are associated with potential nulls, can't combine.
997 return;
998 }
999 }
1000 }
1001 DCHECK(single_value != nullptr) << "All target values are non-null but the phi as a whole still"
1002 << " can be null? This should not be possible." << std::endl
1003 << pred_get->DumpWithArgs();
1004 if (single_value->StrictlyDominates(pred_get)) {
Alex Light3a73ffb2021-01-25 14:11:05 +00001005 // Combine all the maybe null values into one.
1006 pred_get->ReplaceInput(single_value, 0);
Alex Light74328052021-03-29 18:11:23 -07001007 RecordSimplification();
Alex Light3a73ffb2021-01-25 14:11:05 +00001008 }
1009}
1010
David Brazdil74eb1b22015-12-14 11:44:01 +00001011void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
1012 HInstruction* replace_with = nullptr;
1013 HInstruction* condition = select->GetCondition();
1014 HInstruction* true_value = select->GetTrueValue();
1015 HInstruction* false_value = select->GetFalseValue();
1016
1017 if (condition->IsBooleanNot()) {
1018 // Change ((!cond) ? x : y) to (cond ? y : x).
1019 condition = condition->InputAt(0);
1020 std::swap(true_value, false_value);
1021 select->ReplaceInput(false_value, 0);
1022 select->ReplaceInput(true_value, 1);
1023 select->ReplaceInput(condition, 2);
1024 RecordSimplification();
1025 }
1026
1027 if (true_value == false_value) {
1028 // Replace (cond ? x : x) with (x).
1029 replace_with = true_value;
1030 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001031 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +00001032 // Replace (true ? x : y) with (x).
1033 replace_with = true_value;
1034 } else {
1035 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +00001036 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +00001037 replace_with = false_value;
1038 }
1039 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00001040 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +00001041 // Replace (cond ? true : false) with (cond).
1042 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +00001043 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +00001044 // Replace (cond ? false : true) with (!cond).
1045 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
1046 }
Aart Bik4f7dd342017-09-12 13:12:57 -07001047 } else if (condition->IsCondition()) {
1048 IfCondition cmp = condition->AsCondition()->GetCondition();
1049 HInstruction* a = condition->InputAt(0);
1050 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001051 DataType::Type t_type = true_value->GetType();
1052 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -07001053 // Here we have a <cmp> b ? true_value : false_value.
Aart Bik1d746de2018-03-28 16:30:02 -07001054 // Test if both values are compatible integral types (resulting MIN/MAX/ABS
1055 // type will be int or long, like the condition). Replacements are general,
1056 // but assume conditions prefer constants on the right.
Aart Bik2286da22018-03-22 10:50:22 -07001057 if (DataType::IsIntegralType(t_type) && DataType::Kind(t_type) == DataType::Kind(f_type)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001058 // Allow a < 100 ? max(a, -100) : ..
1059 // or a > -100 ? min(a, 100) : ..
1060 // to use min/max instead of a to detect nested min/max expressions.
1061 HInstruction* new_a = AllowInMinMax(cmp, a, b, true_value);
1062 if (new_a != nullptr) {
1063 a = new_a;
1064 }
Aart Bik142b9132018-03-14 15:12:59 -07001065 // Try to replace typical integral MIN/MAX/ABS constructs.
1066 if ((cmp == kCondLT || cmp == kCondLE || cmp == kCondGT || cmp == kCondGE) &&
1067 ((a == true_value && b == false_value) ||
1068 (b == true_value && a == false_value))) {
1069 // Found a < b ? a : b (MIN) or a < b ? b : a (MAX)
1070 // or a > b ? a : b (MAX) or a > b ? b : a (MIN).
1071 bool is_min = (cmp == kCondLT || cmp == kCondLE) == (a == true_value);
1072 replace_with = NewIntegralMinMax(GetGraph()->GetAllocator(), a, b, select, is_min);
Aart Bik1d746de2018-03-28 16:30:02 -07001073 } else if (((cmp == kCondLT || cmp == kCondLE) && true_value->IsNeg()) ||
1074 ((cmp == kCondGT || cmp == kCondGE) && false_value->IsNeg())) {
1075 bool negLeft = (cmp == kCondLT || cmp == kCondLE);
1076 HInstruction* the_negated = negLeft ? true_value->InputAt(0) : false_value->InputAt(0);
1077 HInstruction* not_negated = negLeft ? false_value : true_value;
1078 if (a == the_negated && a == not_negated && IsInt64Value(b, 0)) {
1079 // Found a < 0 ? -a : a
1080 // or a > 0 ? a : -a
1081 // which can be replaced by ABS(a).
1082 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), a, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001083 }
1084 } else if (true_value->IsSub() && false_value->IsSub()) {
1085 HInstruction* true_sub1 = true_value->InputAt(0);
1086 HInstruction* true_sub2 = true_value->InputAt(1);
1087 HInstruction* false_sub1 = false_value->InputAt(0);
1088 HInstruction* false_sub2 = false_value->InputAt(1);
1089 if ((((cmp == kCondGT || cmp == kCondGE) &&
1090 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
1091 ((cmp == kCondLT || cmp == kCondLE) &&
1092 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
1093 AreLowerPrecisionArgs(t_type, a, b)) {
Aart Bik1d746de2018-03-28 16:30:02 -07001094 // Found a > b ? a - b : b - a
1095 // or a < b ? b - a : a - b
Aart Bik4f7dd342017-09-12 13:12:57 -07001096 // which can be replaced by ABS(a - b) for lower precision operands a, b.
Vladimir Markoca6fff82017-10-03 14:49:14 +01001097 replace_with = NewIntegralAbs(GetGraph()->GetAllocator(), true_value, select);
Aart Bik4f7dd342017-09-12 13:12:57 -07001098 }
1099 }
1100 }
David Brazdil74eb1b22015-12-14 11:44:01 +00001101 }
1102
1103 if (replace_with != nullptr) {
1104 select->ReplaceWith(replace_with);
1105 select->GetBlock()->RemoveInstruction(select);
1106 RecordSimplification();
1107 }
1108}
1109
1110void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
1111 HInstruction* condition = instruction->InputAt(0);
1112 if (condition->IsBooleanNot()) {
1113 // Swap successors if input is negated.
1114 instruction->ReplaceInput(condition->InputAt(0), 0);
1115 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +01001116 RecordSimplification();
1117 }
1118}
1119
Mingyao Yang0304e182015-01-30 16:41:29 -08001120void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
1121 HInstruction* input = instruction->InputAt(0);
1122 // If the array is a NewArray with constant size, replace the array length
1123 // with the constant instruction. This helps the bounds check elimination phase.
1124 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001125 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001126 if (input->IsIntConstant()) {
1127 instruction->ReplaceWith(input);
1128 }
1129 }
1130}
1131
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +00001132void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001133 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001134 if (value->GetType() != DataType::Type::kReference) {
1135 return;
1136 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001137
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001138 if (CanEnsureNotNullAt(value, instruction)) {
1139 instruction->ClearValueCanBeNull();
1140 }
1141
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001142 if (value->IsArrayGet()) {
1143 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1144 // If the code is just swapping elements in the array, no need for a type check.
1145 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001146 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001147 }
1148 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001149
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001150 if (value->IsNullConstant()) {
1151 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001152 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001153 }
1154
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001155 ScopedObjectAccess soa(Thread::Current());
1156 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1157 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1158 if (!array_rti.IsValid()) {
1159 return;
1160 }
1161
1162 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1163 instruction->ClearNeedsTypeCheck();
1164 return;
1165 }
1166
1167 if (array_rti.IsObjectArray()) {
1168 if (array_rti.IsExact()) {
1169 instruction->ClearNeedsTypeCheck();
1170 return;
1171 }
1172 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001173 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001174}
1175
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001176static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Aart Bikdab69072017-10-23 13:30:39 -07001177 // Make sure all implicit conversions have been simplified and no new ones have been introduced.
1178 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type))
1179 << input_type << "," << result_type;
Vladimir Markob52bbde2016-02-12 12:06:05 +00001180 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001181 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001182 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1183 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001184 // Note: The size check excludes Uint8 as the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001185 return DataType::Size(result_type) > DataType::Size(input_type) &&
1186 result_type != DataType::Type::kUint16 &&
1187 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001188}
1189
Artem Serove91a9542021-10-25 16:23:27 +01001190static bool CanRemoveRedundantAnd(HConstant* and_right,
1191 HConstant* shr_right,
1192 DataType::Type result_type) {
1193 int64_t and_cst = Int64FromConstant(and_right);
1194 int64_t shr_cst = Int64FromConstant(shr_right);
1195
1196 // In the following sequence A is the input value, D is the result:
1197 // B := A & x
1198 // C := B >> r
1199 // D := TypeConv(n-bit type) C
1200
1201 // The value of D is entirely dependent on the bits [n-1:0] of C, which in turn are dependent
1202 // on bits [r+n-1:r] of B.
1203 // Therefore, if the AND does not change bits [r+n-1:r] of A then it will not affect D.
1204 // This can be checked by ensuring that bits [r+n-1:r] of the AND Constant are 1.
1205
1206 // For example: return (byte) ((value & 0xff00) >> 8)
1207 // return (byte) ((value & 0xff000000) >> 31)
1208
1209 // The mask sets bits [r+n-1:r] to 1, and all others to 0.
1210 int64_t mask = DataType::MaxValueOfIntegralType(DataType::ToUnsigned(result_type)) << shr_cst;
1211
1212 // If the result of a bitwise AND between the mask and the AND constant is the original mask, then
1213 // the AND does not change bits [r+n-1:r], meaning that it is redundant and can be removed.
1214 return ((and_cst & mask) == mask);
1215}
1216
Vladimir Marko61b92282017-10-11 13:23:17 +01001217static inline bool TryReplaceFieldOrArrayGetType(HInstruction* maybe_get, DataType::Type new_type) {
1218 if (maybe_get->IsInstanceFieldGet()) {
1219 maybe_get->AsInstanceFieldGet()->SetType(new_type);
1220 return true;
Alex Light3a73ffb2021-01-25 14:11:05 +00001221 } else if (maybe_get->IsPredicatedInstanceFieldGet()) {
1222 maybe_get->AsPredicatedInstanceFieldGet()->SetType(new_type);
1223 return true;
Vladimir Marko61b92282017-10-11 13:23:17 +01001224 } else if (maybe_get->IsStaticFieldGet()) {
1225 maybe_get->AsStaticFieldGet()->SetType(new_type);
1226 return true;
1227 } else if (maybe_get->IsArrayGet() && !maybe_get->AsArrayGet()->IsStringCharAt()) {
1228 maybe_get->AsArrayGet()->SetType(new_type);
1229 return true;
1230 } else {
1231 return false;
1232 }
1233}
1234
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001235// The type conversion is only used for storing into a field/element of the
1236// same/narrower size.
1237static bool IsTypeConversionForStoringIntoNoWiderFieldOnly(HTypeConversion* type_conversion) {
1238 if (type_conversion->HasEnvironmentUses()) {
1239 return false;
1240 }
1241 DataType::Type input_type = type_conversion->GetInputType();
1242 DataType::Type result_type = type_conversion->GetResultType();
1243 if (!DataType::IsIntegralType(input_type) ||
1244 !DataType::IsIntegralType(result_type) ||
1245 input_type == DataType::Type::kInt64 ||
1246 result_type == DataType::Type::kInt64) {
1247 // Type conversion is needed if non-integer types are involved, or 64-bit
1248 // types are involved, which may use different number of registers.
1249 return false;
1250 }
1251 if (DataType::Size(input_type) >= DataType::Size(result_type)) {
1252 // Type conversion is not necessary when storing to a field/element of the
1253 // same/smaller size.
1254 } else {
1255 // We do not handle this case here.
1256 return false;
1257 }
1258
1259 // Check if the converted value is only used for storing into heap.
1260 for (const HUseListNode<HInstruction*>& use : type_conversion->GetUses()) {
1261 HInstruction* instruction = use.GetUser();
1262 if (instruction->IsInstanceFieldSet() &&
1263 instruction->AsInstanceFieldSet()->GetFieldType() == result_type) {
1264 DCHECK_EQ(instruction->AsInstanceFieldSet()->GetValue(), type_conversion);
1265 continue;
1266 }
1267 if (instruction->IsStaticFieldSet() &&
1268 instruction->AsStaticFieldSet()->GetFieldType() == result_type) {
1269 DCHECK_EQ(instruction->AsStaticFieldSet()->GetValue(), type_conversion);
1270 continue;
1271 }
1272 if (instruction->IsArraySet() &&
1273 instruction->AsArraySet()->GetComponentType() == result_type &&
1274 // not index use.
1275 instruction->AsArraySet()->GetIndex() != type_conversion) {
1276 DCHECK_EQ(instruction->AsArraySet()->GetValue(), type_conversion);
1277 continue;
1278 }
1279 // The use is not as a store value, or the field/element type is not the
1280 // same as the result_type, keep the type conversion.
1281 return false;
1282 }
1283 // Codegen automatically handles the type conversion during the store.
1284 return true;
1285}
1286
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001287void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001288 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001289 DataType::Type input_type = input->GetType();
1290 DataType::Type result_type = instruction->GetResultType();
Nicolas Geoffrayacc56ac2018-10-09 08:45:24 +01001291 if (instruction->IsImplicitConversion()) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001292 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001293 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001294 RecordSimplification();
1295 return;
1296 }
1297
1298 if (input->IsTypeConversion()) {
1299 HTypeConversion* input_conversion = input->AsTypeConversion();
1300 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001301 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001302
1303 // When the first conversion is lossless, a direct conversion from the original type
1304 // to the final type yields the same result, even for a lossy second conversion, for
1305 // example float->double->int or int->double->float.
1306 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1307
1308 // For integral conversions, see if the first conversion loses only bits that the second
1309 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1310 // conversion yields the same result, for example long->int->short or int->char->short.
1311 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001312 DataType::IsIntegralType(input_type) &&
1313 DataType::IsIntegralType(original_type) &&
1314 DataType::IsIntegralType(result_type) &&
1315 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001316
1317 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1318 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001319 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001320 instruction->ReplaceWith(original_input);
1321 instruction->GetBlock()->RemoveInstruction(instruction);
1322 if (!input_conversion->HasUses()) {
1323 // Don't wait for DCE.
1324 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1325 }
1326 RecordSimplification();
1327 return;
1328 }
1329 // Otherwise simplify only if the first conversion has no other use.
1330 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1331 input_conversion->ReplaceWith(original_input);
1332 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1333 RecordSimplification();
1334 return;
1335 }
1336 }
Artem Serove91a9542021-10-25 16:23:27 +01001337 } else if (input->IsShr() && DataType::IsIntegralType(result_type) &&
1338 // Optimization only applies to lossy Type Conversions.
1339 !IsTypeConversionLossless(input_type, result_type)) {
1340 DCHECK(DataType::IsIntegralType(input_type));
1341 HShr* shr_op = input->AsShr();
1342 HConstant* shr_right = shr_op->GetConstantRight();
1343 HInstruction* shr_left = shr_op->GetLeastConstantLeft();
1344 if (shr_right != nullptr && shr_left->IsAnd()) {
1345 // Optimization needs AND -> SHR -> TypeConversion pattern.
1346 HAnd* and_op = shr_left->AsAnd();
1347 HConstant* and_right = and_op->GetConstantRight();
1348 HInstruction* and_left = and_op->GetLeastConstantLeft();
1349 if (and_right != nullptr &&
1350 !DataType::IsUnsignedType(and_left->GetType()) &&
1351 !DataType::IsUnsignedType(result_type) &&
1352 !DataType::IsUnsignedType(and_right->GetType()) &&
1353 (DataType::Size(and_left->GetType()) < 8) &&
1354 (DataType::Size(result_type) == 1)) {
1355 // TODO: Support Unsigned Types.
1356 // TODO: Support Long Types.
1357 // TODO: Support result types other than byte.
1358 if (and_op->HasOnlyOneNonEnvironmentUse() &&
1359 CanRemoveRedundantAnd(and_right, shr_right, result_type)) {
1360 and_op->ReplaceWith(and_left);
1361 and_op->GetBlock()->RemoveInstruction(and_op);
1362 RecordSimplification();
1363 return;
1364 }
1365 }
1366 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001367 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1368 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001369 HAnd* input_and = input->AsAnd();
1370 HConstant* constant = input_and->GetConstantRight();
1371 if (constant != nullptr) {
1372 int64_t value = Int64FromConstant(constant);
1373 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1374 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001375 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001376 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001377 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001378 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001379 instruction->ReplaceWith(original_input);
1380 instruction->GetBlock()->RemoveInstruction(instruction);
1381 RecordSimplification();
1382 return;
1383 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1384 input_and->ReplaceWith(original_input);
1385 input_and->GetBlock()->RemoveInstruction(input_and);
1386 RecordSimplification();
1387 return;
1388 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001389 }
1390 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001391 } else if (input->HasOnlyOneNonEnvironmentUse() &&
1392 ((input_type == DataType::Type::kInt8 && result_type == DataType::Type::kUint8) ||
1393 (input_type == DataType::Type::kUint8 && result_type == DataType::Type::kInt8) ||
1394 (input_type == DataType::Type::kInt16 && result_type == DataType::Type::kUint16) ||
1395 (input_type == DataType::Type::kUint16 && result_type == DataType::Type::kInt16))) {
1396 // Try to modify the type of the load to `result_type` and remove the explicit type conversion.
1397 if (TryReplaceFieldOrArrayGetType(input, result_type)) {
1398 instruction->ReplaceWith(input);
1399 instruction->GetBlock()->RemoveInstruction(instruction);
1400 RecordSimplification();
1401 return;
1402 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001403 }
Mingyao Yang3bcb7512017-11-16 15:40:46 -08001404
1405 if (IsTypeConversionForStoringIntoNoWiderFieldOnly(instruction)) {
1406 instruction->ReplaceWith(input);
1407 instruction->GetBlock()->RemoveInstruction(instruction);
1408 RecordSimplification();
1409 return;
1410 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001411}
1412
Aart Bikc6eec4b2018-03-29 17:22:00 -07001413void InstructionSimplifierVisitor::VisitAbs(HAbs* instruction) {
1414 HInstruction* input = instruction->GetInput();
1415 if (DataType::IsZeroExtension(input->GetType(), instruction->GetResultType())) {
1416 // Zero extension from narrow to wide can never set sign bit in the wider
1417 // operand, making the subsequent Abs redundant (e.g., abs(b & 0xff) for byte b).
1418 instruction->ReplaceWith(input);
1419 instruction->GetBlock()->RemoveInstruction(instruction);
1420 RecordSimplification();
1421 }
1422}
1423
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001424void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1425 HConstant* input_cst = instruction->GetConstantRight();
1426 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001427 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001428 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001429 // Replace code looking like
1430 // ADD dst, src, 0
1431 // with
1432 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001433 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1434 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1435 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001436 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001437 instruction->ReplaceWith(input_other);
1438 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001439 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001440 return;
1441 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001442 }
1443
1444 HInstruction* left = instruction->GetLeft();
1445 HInstruction* right = instruction->GetRight();
1446 bool left_is_neg = left->IsNeg();
1447 bool right_is_neg = right->IsNeg();
1448
1449 if (left_is_neg && right_is_neg) {
1450 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1451 return;
1452 }
1453 }
1454
1455 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
Andreas Gampe654698d2018-09-20 13:34:35 -07001456 if (left_is_neg != right_is_neg && neg->HasOnlyOneNonEnvironmentUse()) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001457 // Replace code looking like
1458 // NEG tmp, b
1459 // ADD dst, a, tmp
1460 // with
1461 // SUB dst, a, b
1462 // We do not perform the optimization if the input negation has environment
1463 // uses or multiple non-environment uses as it could lead to worse code. In
1464 // particular, we do not want the live range of `b` to be extended if we are
1465 // not sure the initial 'NEG' instruction can be removed.
1466 HInstruction* other = left_is_neg ? right : left;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001467 HSub* sub =
1468 new(GetGraph()->GetAllocator()) HSub(instruction->GetType(), other, neg->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01001469 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1470 RecordSimplification();
1471 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001472 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001473 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001474
Anton Kirilove14dc862016-05-13 17:56:15 +01001475 if (TryReplaceWithRotate(instruction)) {
1476 return;
1477 }
1478
1479 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1480 // so no need to return.
1481 TryHandleAssociativeAndCommutativeOperation(instruction);
1482
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001483 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001484 TrySubtractionChainSimplification(instruction)) {
1485 return;
1486 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001487
1488 if (integral_type) {
1489 // Replace code patterns looking like
1490 // SUB dst1, x, y SUB dst1, x, y
1491 // ADD dst2, dst1, y ADD dst2, y, dst1
1492 // with
1493 // SUB dst1, x, y
1494 // ADD instruction is not needed in this case, we may use
1495 // one of inputs of SUB instead.
1496 if (left->IsSub() && left->InputAt(1) == right) {
1497 instruction->ReplaceWith(left->InputAt(0));
1498 RecordSimplification();
1499 instruction->GetBlock()->RemoveInstruction(instruction);
1500 return;
1501 } else if (right->IsSub() && right->InputAt(1) == left) {
1502 instruction->ReplaceWith(right->InputAt(0));
1503 RecordSimplification();
1504 instruction->GetBlock()->RemoveInstruction(instruction);
1505 return;
1506 }
1507 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001508}
1509
1510void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
Vladimir Marko61b92282017-10-11 13:23:17 +01001511 DCHECK(DataType::IsIntegralType(instruction->GetType()));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001512 HConstant* input_cst = instruction->GetConstantRight();
1513 HInstruction* input_other = instruction->GetLeastConstantLeft();
1514
Vladimir Marko452c1b62015-09-25 14:44:17 +01001515 if (input_cst != nullptr) {
1516 int64_t value = Int64FromConstant(input_cst);
Aart Bikdab69072017-10-23 13:30:39 -07001517 if (value == -1 ||
1518 // Similar cases under zero extension.
1519 (DataType::IsUnsignedType(input_other->GetType()) &&
1520 ((DataType::MaxValueOfIntegralType(input_other->GetType()) & ~value) == 0))) {
Vladimir Marko452c1b62015-09-25 14:44:17 +01001521 // Replace code looking like
1522 // AND dst, src, 0xFFF...FF
1523 // with
1524 // src
1525 instruction->ReplaceWith(input_other);
1526 instruction->GetBlock()->RemoveInstruction(instruction);
1527 RecordSimplification();
1528 return;
1529 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001530 if (input_other->IsTypeConversion() &&
1531 input_other->GetType() == DataType::Type::kInt64 &&
1532 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1533 IsInt<32>(value) &&
1534 input_other->HasOnlyOneNonEnvironmentUse()) {
1535 // The AND can be reordered before the TypeConversion. Replace
1536 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1537 // TypeConversion<Int64> tmp, src
1538 // AND dst, tmp, cst
1539 // with
1540 // IntConstant cst, <32-bit-constant>
1541 // AND tmp, src, cst
1542 // TypeConversion<Int64> dst, tmp
1543 // This helps 32-bit targets and does not hurt 64-bit targets.
1544 // This also simplifies detection of other patterns, such as Uint8 loads.
1545 HInstruction* new_and_input = input_other->InputAt(0);
1546 // Implicit conversion Int64->Int64 would have been removed previously.
1547 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1548 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1549 HAnd* new_and =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001550 new (GetGraph()->GetAllocator()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001551 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1552 HTypeConversion* new_conversion =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001553 new (GetGraph()->GetAllocator()) HTypeConversion(DataType::Type::kInt64, new_and);
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001554 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1555 input_other->GetBlock()->RemoveInstruction(input_other);
1556 RecordSimplification();
1557 // Try to process the new And now, do not wait for the next round of simplifications.
1558 instruction = new_and;
1559 input_other = new_and_input;
1560 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001561 // Eliminate And from UShr+And if the And-mask contains all the bits that
1562 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1563 // precisely clears the shifted-in sign bits.
1564 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001565 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001566 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1567 size_t num_tail_bits_set = CTZ(value + 1);
1568 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1569 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1570 instruction->ReplaceWith(input_other);
1571 instruction->GetBlock()->RemoveInstruction(instruction);
1572 RecordSimplification();
1573 return;
1574 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1575 input_other->HasOnlyOneNonEnvironmentUse()) {
1576 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1577 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
Vladimir Markoca6fff82017-10-03 14:49:14 +01001578 HUShr* ushr = new (GetGraph()->GetAllocator()) HUShr(instruction->GetType(),
Vladimir Marko69d310e2017-10-09 14:12:23 +01001579 input_other->InputAt(0),
1580 input_other->InputAt(1),
1581 input_other->GetDexPc());
Vladimir Marko452c1b62015-09-25 14:44:17 +01001582 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1583 input_other->GetBlock()->RemoveInstruction(input_other);
1584 RecordSimplification();
1585 return;
1586 }
1587 }
Vladimir Marko61b92282017-10-11 13:23:17 +01001588 if ((value == 0xff || value == 0xffff) && instruction->GetType() != DataType::Type::kInt64) {
1589 // Transform AND to a type conversion to Uint8/Uint16. If `input_other` is a field
1590 // or array Get with only a single use, short-circuit the subsequent simplification
1591 // of the Get+TypeConversion and change the Get's type to `new_type` instead.
1592 DataType::Type new_type = (value == 0xff) ? DataType::Type::kUint8 : DataType::Type::kUint16;
1593 DataType::Type find_type = (value == 0xff) ? DataType::Type::kInt8 : DataType::Type::kInt16;
1594 if (input_other->GetType() == find_type &&
1595 input_other->HasOnlyOneNonEnvironmentUse() &&
1596 TryReplaceFieldOrArrayGetType(input_other, new_type)) {
1597 instruction->ReplaceWith(input_other);
1598 instruction->GetBlock()->RemoveInstruction(instruction);
Aart Bikdab69072017-10-23 13:30:39 -07001599 } else if (DataType::IsTypeConversionImplicit(input_other->GetType(), new_type)) {
1600 instruction->ReplaceWith(input_other);
1601 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Marko61b92282017-10-11 13:23:17 +01001602 } else {
1603 HTypeConversion* type_conversion = new (GetGraph()->GetAllocator()) HTypeConversion(
1604 new_type, input_other, instruction->GetDexPc());
1605 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, type_conversion);
1606 }
1607 RecordSimplification();
1608 return;
1609 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001610 }
1611
1612 // We assume that GVN has run before, so we only perform a pointer comparison.
1613 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001614 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001615 if (instruction->GetLeft() == instruction->GetRight()) {
1616 // Replace code looking like
1617 // AND dst, src, src
1618 // with
1619 // src
1620 instruction->ReplaceWith(instruction->GetLeft());
1621 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001622 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001623 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001624 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001625
Anton Kirilove14dc862016-05-13 17:56:15 +01001626 if (TryDeMorganNegationFactoring(instruction)) {
1627 return;
1628 }
1629
1630 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1631 // so no need to return.
1632 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001633}
1634
Mark Mendellc4701932015-04-10 13:18:51 -04001635void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1636 VisitCondition(condition);
1637}
1638
1639void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1640 VisitCondition(condition);
1641}
1642
1643void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1644 VisitCondition(condition);
1645}
1646
1647void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1648 VisitCondition(condition);
1649}
1650
Anton Shaminbdd79352016-02-15 12:48:36 +06001651void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1652 VisitCondition(condition);
1653}
1654
1655void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1656 VisitCondition(condition);
1657}
1658
1659void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1660 VisitCondition(condition);
1661}
1662
1663void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1664 VisitCondition(condition);
1665}
Aart Bike9f37602015-10-09 11:15:55 -07001666
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001667// Recognize the following pattern:
1668// obj.getClass() ==/!= Foo.class
1669// And replace it with a constant value if the type of `obj` is statically known.
1670static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1671 HInstruction* input_one = condition->InputAt(0);
1672 HInstruction* input_two = condition->InputAt(1);
1673 HLoadClass* load_class = input_one->IsLoadClass()
1674 ? input_one->AsLoadClass()
1675 : input_two->AsLoadClass();
1676 if (load_class == nullptr) {
1677 return false;
1678 }
1679
1680 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1681 if (!class_rti.IsValid()) {
1682 // Unresolved class.
1683 return false;
1684 }
1685
1686 HInstanceFieldGet* field_get = (load_class == input_one)
1687 ? input_two->AsInstanceFieldGet()
1688 : input_one->AsInstanceFieldGet();
1689 if (field_get == nullptr) {
1690 return false;
1691 }
1692
1693 HInstruction* receiver = field_get->InputAt(0);
1694 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1695 if (!receiver_type.IsExact()) {
1696 return false;
1697 }
1698
1699 {
1700 ScopedObjectAccess soa(Thread::Current());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001701 ArtField* field = GetClassRoot<mirror::Object>()->GetInstanceField(0);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001702 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1703 if (field_get->GetFieldInfo().GetField() != field) {
1704 return false;
1705 }
1706
1707 // We can replace the compare.
1708 int value = 0;
1709 if (receiver_type.IsEqual(class_rti)) {
1710 value = condition->IsEqual() ? 1 : 0;
1711 } else {
1712 value = condition->IsNotEqual() ? 1 : 0;
1713 }
1714 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1715 return true;
1716 }
1717}
1718
Mark Mendellc4701932015-04-10 13:18:51 -04001719void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001720 if (condition->IsEqual() || condition->IsNotEqual()) {
1721 if (RecognizeAndSimplifyClassCheck(condition)) {
1722 return;
1723 }
1724 }
1725
Anton Shaminbdd79352016-02-15 12:48:36 +06001726 // Reverse condition if left is constant. Our code generators prefer constant
1727 // on the right hand side.
1728 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1729 HBasicBlock* block = condition->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001730 HCondition* replacement =
1731 GetOppositeConditionSwapOps(block->GetGraph()->GetAllocator(), condition);
Anton Shaminbdd79352016-02-15 12:48:36 +06001732 // If it is a fp we must set the opposite bias.
1733 if (replacement != nullptr) {
1734 if (condition->IsLtBias()) {
1735 replacement->SetBias(ComparisonBias::kGtBias);
1736 } else if (condition->IsGtBias()) {
1737 replacement->SetBias(ComparisonBias::kLtBias);
1738 }
1739 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1740 RecordSimplification();
1741
1742 condition = replacement;
1743 }
1744 }
Mark Mendellc4701932015-04-10 13:18:51 -04001745
Mark Mendellc4701932015-04-10 13:18:51 -04001746 HInstruction* left = condition->GetLeft();
1747 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001748
1749 // Try to fold an HCompare into this HCondition.
1750
Mark Mendellc4701932015-04-10 13:18:51 -04001751 // We can only replace an HCondition which compares a Compare to 0.
1752 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1753 // condition with a long, float or double comparison as input.
1754 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1755 // Conversion is not possible.
1756 return;
1757 }
1758
1759 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001760 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001761 // Someone else also wants the result of the compare.
1762 return;
1763 }
1764
Vladimir Marko46817b82016-03-29 12:21:58 +01001765 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001766 // There is a reference to the compare result in an environment. Do we really need it?
1767 if (GetGraph()->IsDebuggable()) {
1768 return;
1769 }
1770
1771 // We have to ensure that there are no deopt points in the sequence.
1772 if (left->HasAnyEnvironmentUseBefore(condition)) {
1773 return;
1774 }
1775 }
1776
1777 // Clean up any environment uses from the HCompare, if any.
1778 left->RemoveEnvironmentUsers();
1779
1780 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1781 condition->SetBias(left->AsCompare()->GetBias());
1782
1783 // Replace the operands of the HCondition.
1784 condition->ReplaceInput(left->InputAt(0), 0);
1785 condition->ReplaceInput(left->InputAt(1), 1);
1786
1787 // Remove the HCompare.
1788 left->GetBlock()->RemoveInstruction(left);
1789
1790 RecordSimplification();
1791}
1792
Andreas Gampe9186ced2016-12-12 14:28:21 -08001793// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1794static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1795 // True, if the most significant bits of divisor are 0.
1796 return ((divisor & 0x7fffff) == 0);
1797}
1798
1799// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1800static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1801 // True, if the most significant bits of divisor are 0.
1802 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1803}
1804
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001805void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1806 HConstant* input_cst = instruction->GetConstantRight();
1807 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001808 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001809
1810 if ((input_cst != nullptr) && input_cst->IsOne()) {
1811 // Replace code looking like
1812 // DIV dst, src, 1
1813 // with
1814 // src
1815 instruction->ReplaceWith(input_other);
1816 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001817 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001818 return;
1819 }
1820
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001821 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001822 // Replace code looking like
1823 // DIV dst, src, -1
1824 // with
1825 // NEG dst, src
1826 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001827 instruction, new (GetGraph()->GetAllocator()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001828 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001829 return;
1830 }
1831
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001832 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001833 // Try replacing code looking like
1834 // DIV dst, src, constant
1835 // with
1836 // MUL dst, src, 1 / constant
1837 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001838 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001839 double value = input_cst->AsDoubleConstant()->GetValue();
1840 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1841 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1842 }
1843 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001844 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001845 float value = input_cst->AsFloatConstant()->GetValue();
1846 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1847 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1848 }
1849 }
1850
1851 if (reciprocal != nullptr) {
1852 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001853 instruction, new (GetGraph()->GetAllocator()) HMul(type, input_other, reciprocal));
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001854 RecordSimplification();
1855 return;
1856 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001857 }
1858}
1859
Evgeny Astigeevich6587d912020-06-12 10:51:43 +01001860
1861// Search HDiv having the specified dividend and divisor which is in the specified basic block.
1862// Return nullptr if nothing has been found.
1863static HInstruction* FindDivWithInputsInBasicBlock(HInstruction* dividend,
1864 HInstruction* divisor,
1865 HBasicBlock* basic_block) {
1866 for (const HUseListNode<HInstruction*>& use : dividend->GetUses()) {
1867 HInstruction* user = use.GetUser();
1868 if (user->GetBlock() == basic_block && user->IsDiv() && user->InputAt(1) == divisor) {
1869 return user;
1870 }
1871 }
1872 return nullptr;
1873}
1874
1875// If there is Div with the same inputs as Rem and in the same basic block, it can be reused.
1876// Rem is replaced with Mul+Sub which use the found Div.
1877void InstructionSimplifierVisitor::TryToReuseDiv(HRem* rem) {
1878 // As the optimization replaces Rem with Mul+Sub they prevent some loop optimizations
1879 // if the Rem is in a loop.
1880 // Check if it is allowed to optimize such Rems.
1881 if (rem->IsInLoop() && be_loop_friendly_) {
1882 return;
1883 }
1884 DataType::Type type = rem->GetResultType();
1885 if (!DataType::IsIntOrLongType(type)) {
1886 return;
1887 }
1888
1889 HBasicBlock* basic_block = rem->GetBlock();
1890 HInstruction* dividend = rem->GetLeft();
1891 HInstruction* divisor = rem->GetRight();
1892
1893 if (divisor->IsConstant()) {
1894 HConstant* input_cst = rem->GetConstantRight();
1895 DCHECK(input_cst->IsIntConstant() || input_cst->IsLongConstant());
1896 int64_t cst_value = Int64FromConstant(input_cst);
1897 if (cst_value == std::numeric_limits<int64_t>::min() || IsPowerOfTwo(std::abs(cst_value))) {
1898 // Such cases are usually handled in the code generator because they don't need Div at all.
1899 return;
1900 }
1901 }
1902
1903 HInstruction* quotient = FindDivWithInputsInBasicBlock(dividend, divisor, basic_block);
1904 if (quotient == nullptr) {
1905 return;
1906 }
1907 if (!quotient->StrictlyDominates(rem)) {
1908 quotient->MoveBefore(rem);
1909 }
1910
1911 ArenaAllocator* allocator = GetGraph()->GetAllocator();
1912 HInstruction* mul = new (allocator) HMul(type, quotient, divisor);
1913 basic_block->InsertInstructionBefore(mul, rem);
1914 HInstruction* sub = new (allocator) HSub(type, dividend, mul);
1915 basic_block->InsertInstructionBefore(sub, rem);
1916 rem->ReplaceWith(sub);
1917 basic_block->RemoveInstruction(rem);
1918 RecordSimplification();
1919}
1920
1921void InstructionSimplifierVisitor::VisitRem(HRem* rem) {
1922 TryToReuseDiv(rem);
1923}
1924
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001925void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1926 HConstant* input_cst = instruction->GetConstantRight();
1927 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001928 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001929 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001930 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001931
1932 if (input_cst == nullptr) {
1933 return;
1934 }
1935
1936 if (input_cst->IsOne()) {
1937 // Replace code looking like
1938 // MUL dst, src, 1
1939 // with
1940 // src
1941 instruction->ReplaceWith(input_other);
1942 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001943 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001944 return;
1945 }
1946
1947 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001948 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001949 // Replace code looking like
1950 // MUL dst, src, -1
1951 // with
1952 // NEG dst, src
1953 HNeg* neg = new (allocator) HNeg(type, input_other);
1954 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001955 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001956 return;
1957 }
1958
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001959 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001960 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1961 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1962 // Replace code looking like
1963 // FP_MUL dst, src, 2.0
1964 // with
1965 // FP_ADD dst, src, src
1966 // The 'int' and 'long' cases are handled below.
1967 block->ReplaceAndRemoveInstructionWith(instruction,
1968 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001969 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001970 return;
1971 }
1972
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001973 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001974 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001975 // Even though constant propagation also takes care of the zero case, other
1976 // optimizations can lead to having a zero multiplication.
1977 if (factor == 0) {
1978 // Replace code looking like
1979 // MUL dst, src, 0
1980 // with
1981 // 0
1982 instruction->ReplaceWith(input_cst);
1983 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001984 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001985 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001986 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001987 // Replace code looking like
1988 // MUL dst, src, pow_of_2
1989 // with
1990 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001991 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001992 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001993 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001994 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001995 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001996 } else if (IsPowerOfTwo(factor - 1)) {
1997 // Transform code looking like
1998 // MUL dst, src, (2^n + 1)
1999 // into
2000 // SHL tmp, src, n
2001 // ADD dst, src, tmp
2002 HShl* shl = new (allocator) HShl(type,
2003 input_other,
2004 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
2005 HAdd* add = new (allocator) HAdd(type, input_other, shl);
2006
2007 block->InsertInstructionBefore(shl, instruction);
2008 block->ReplaceAndRemoveInstructionWith(instruction, add);
2009 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01002010 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00002011 } else if (IsPowerOfTwo(factor + 1)) {
2012 // Transform code looking like
2013 // MUL dst, src, (2^n - 1)
2014 // into
2015 // SHL tmp, src, n
2016 // SUB dst, tmp, src
2017 HShl* shl = new (allocator) HShl(type,
2018 input_other,
2019 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
2020 HSub* sub = new (allocator) HSub(type, shl, input_other);
2021
2022 block->InsertInstructionBefore(shl, instruction);
2023 block->ReplaceAndRemoveInstructionWith(instruction, sub);
2024 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01002025 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002026 }
2027 }
Anton Kirilove14dc862016-05-13 17:56:15 +01002028
2029 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2030 // so no need to return.
2031 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002032}
2033
Alexandre Rames188d4312015-04-09 18:30:21 +01002034void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
2035 HInstruction* input = instruction->GetInput();
2036 if (input->IsNeg()) {
2037 // Replace code looking like
2038 // NEG tmp, src
2039 // NEG dst, tmp
2040 // with
2041 // src
2042 HNeg* previous_neg = input->AsNeg();
2043 instruction->ReplaceWith(previous_neg->GetInput());
2044 instruction->GetBlock()->RemoveInstruction(instruction);
2045 // We perform the optimization even if the input negation has environment
2046 // uses since it allows removing the current instruction. But we only delete
2047 // the input negation only if it is does not have any uses left.
2048 if (!previous_neg->HasUses()) {
2049 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
2050 }
2051 RecordSimplification();
2052 return;
2053 }
2054
Serguei Katkov339dfc22015-04-20 12:29:32 +06002055 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002056 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01002057 // Replace code looking like
2058 // SUB tmp, a, b
2059 // NEG dst, tmp
2060 // with
2061 // SUB dst, b, a
2062 // We do not perform the optimization if the input subtraction has
2063 // environment uses or multiple non-environment uses as it could lead to
2064 // worse code. In particular, we do not want the live ranges of `a` and `b`
2065 // to be extended if we are not sure the initial 'SUB' instruction can be
2066 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06002067 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01002068 HSub* sub = input->AsSub();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002069 HSub* new_sub = new (GetGraph()->GetAllocator()) HSub(
2070 instruction->GetType(), sub->GetRight(), sub->GetLeft());
Alexandre Rames188d4312015-04-09 18:30:21 +01002071 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
2072 if (!sub->HasUses()) {
2073 sub->GetBlock()->RemoveInstruction(sub);
2074 }
2075 RecordSimplification();
2076 }
2077}
2078
2079void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
2080 HInstruction* input = instruction->GetInput();
2081 if (input->IsNot()) {
2082 // Replace code looking like
2083 // NOT tmp, src
2084 // NOT dst, tmp
2085 // with
2086 // src
2087 // We perform the optimization even if the input negation has environment
2088 // uses since it allows removing the current instruction. But we only delete
2089 // the input negation only if it is does not have any uses left.
2090 HNot* previous_not = input->AsNot();
2091 instruction->ReplaceWith(previous_not->GetInput());
2092 instruction->GetBlock()->RemoveInstruction(instruction);
2093 if (!previous_not->HasUses()) {
2094 previous_not->GetBlock()->RemoveInstruction(previous_not);
2095 }
2096 RecordSimplification();
2097 }
2098}
2099
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002100void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
2101 HConstant* input_cst = instruction->GetConstantRight();
2102 HInstruction* input_other = instruction->GetLeastConstantLeft();
2103
Roland Levillain1a653882016-03-18 18:05:57 +00002104 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002105 // Replace code looking like
2106 // OR dst, src, 0
2107 // with
2108 // src
2109 instruction->ReplaceWith(input_other);
2110 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002111 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002112 return;
2113 }
2114
2115 // We assume that GVN has run before, so we only perform a pointer comparison.
2116 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01002117 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002118 if (instruction->GetLeft() == instruction->GetRight()) {
2119 // Replace code looking like
2120 // OR dst, src, src
2121 // with
2122 // src
2123 instruction->ReplaceWith(instruction->GetLeft());
2124 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002125 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002126 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002127 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002128
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002129 if (TryDeMorganNegationFactoring(instruction)) return;
2130
Anton Kirilove14dc862016-05-13 17:56:15 +01002131 if (TryReplaceWithRotate(instruction)) {
2132 return;
2133 }
2134
2135 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2136 // so no need to return.
2137 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002138}
2139
2140void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
2141 VisitShift(instruction);
2142}
2143
2144void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
2145 VisitShift(instruction);
2146}
2147
2148void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
2149 HConstant* input_cst = instruction->GetConstantRight();
2150 HInstruction* input_other = instruction->GetLeastConstantLeft();
2151
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002152 DataType::Type type = instruction->GetType();
2153 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06002154 return;
2155 }
2156
Roland Levillain1a653882016-03-18 18:05:57 +00002157 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002158 // Replace code looking like
2159 // SUB dst, src, 0
2160 // with
2161 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06002162 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
2163 // `x` is `-0.0`, the former expression yields `0.0`, while the later
2164 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002165 instruction->ReplaceWith(input_other);
2166 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002167 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002168 return;
2169 }
2170
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002171 HBasicBlock* block = instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01002172 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002173
Alexandre Rames188d4312015-04-09 18:30:21 +01002174 HInstruction* left = instruction->GetLeft();
2175 HInstruction* right = instruction->GetRight();
2176 if (left->IsConstant()) {
2177 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002178 // Replace code looking like
2179 // SUB dst, 0, src
2180 // with
2181 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01002182 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002183 // `x` is `0.0`, the former expression yields `0.0`, while the later
2184 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01002185 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002186 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01002187 RecordSimplification();
2188 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002189 }
2190 }
Alexandre Rames188d4312015-04-09 18:30:21 +01002191
2192 if (left->IsNeg() && right->IsNeg()) {
2193 if (TryMoveNegOnInputsAfterBinop(instruction)) {
2194 return;
2195 }
2196 }
2197
2198 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
2199 // Replace code looking like
2200 // NEG tmp, b
2201 // SUB dst, a, tmp
2202 // with
2203 // ADD dst, a, b
Vladimir Markoca6fff82017-10-03 14:49:14 +01002204 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left, right->AsNeg()->GetInput());
Alexandre Rames188d4312015-04-09 18:30:21 +01002205 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
2206 RecordSimplification();
2207 right->GetBlock()->RemoveInstruction(right);
2208 return;
2209 }
2210
2211 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
2212 // Replace code looking like
2213 // NEG tmp, a
2214 // SUB dst, tmp, b
2215 // with
2216 // ADD tmp, a, b
2217 // NEG dst, tmp
2218 // The second version is not intrinsically better, but enables more
2219 // transformations.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002220 HAdd* add = new(GetGraph()->GetAllocator()) HAdd(type, left->AsNeg()->GetInput(), right);
Alexandre Rames188d4312015-04-09 18:30:21 +01002221 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002222 HNeg* neg = new (GetGraph()->GetAllocator()) HNeg(instruction->GetType(), add);
Alexandre Rames188d4312015-04-09 18:30:21 +01002223 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
2224 instruction->ReplaceWith(neg);
2225 instruction->GetBlock()->RemoveInstruction(instruction);
2226 RecordSimplification();
2227 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01002228 return;
2229 }
2230
2231 if (TrySubtractionChainSimplification(instruction)) {
2232 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01002233 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002234
2235 if (left->IsAdd()) {
2236 // Replace code patterns looking like
2237 // ADD dst1, x, y ADD dst1, x, y
2238 // SUB dst2, dst1, y SUB dst2, dst1, x
2239 // with
2240 // ADD dst1, x, y
2241 // SUB instruction is not needed in this case, we may use
2242 // one of inputs of ADD instead.
2243 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002244 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06002245 if (left->InputAt(1) == right) {
2246 instruction->ReplaceWith(left->InputAt(0));
2247 RecordSimplification();
2248 instruction->GetBlock()->RemoveInstruction(instruction);
2249 return;
2250 } else if (left->InputAt(0) == right) {
2251 instruction->ReplaceWith(left->InputAt(1));
2252 RecordSimplification();
2253 instruction->GetBlock()->RemoveInstruction(instruction);
2254 return;
2255 }
2256 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002257}
2258
2259void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
2260 VisitShift(instruction);
2261}
2262
2263void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
2264 HConstant* input_cst = instruction->GetConstantRight();
2265 HInstruction* input_other = instruction->GetLeastConstantLeft();
2266
Roland Levillain1a653882016-03-18 18:05:57 +00002267 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002268 // Replace code looking like
2269 // XOR dst, src, 0
2270 // with
2271 // src
2272 instruction->ReplaceWith(input_other);
2273 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01002274 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002275 return;
2276 }
2277
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002278 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002279 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002280 // Replace code looking like
2281 // XOR dst, src, 1
2282 // with
2283 // BOOLEAN_NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002284 HBooleanNot* boolean_not = new (GetGraph()->GetAllocator()) HBooleanNot(input_other);
Sebastien Hertz9837caf2016-08-01 11:09:50 +02002285 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
2286 RecordSimplification();
2287 return;
2288 }
2289
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002290 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
2291 // Replace code looking like
2292 // XOR dst, src, 0xFFF...FF
2293 // with
2294 // NOT dst, src
Vladimir Markoca6fff82017-10-03 14:49:14 +01002295 HNot* bitwise_not = new (GetGraph()->GetAllocator()) HNot(instruction->GetType(), input_other);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002296 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01002297 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002298 return;
2299 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00002300
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002301 HInstruction* left = instruction->GetLeft();
2302 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00002303 if (((left->IsNot() && right->IsNot()) ||
2304 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002305 left->HasOnlyOneNonEnvironmentUse() &&
2306 right->HasOnlyOneNonEnvironmentUse()) {
2307 // Replace code looking like
2308 // NOT nota, a
2309 // NOT notb, b
2310 // XOR dst, nota, notb
2311 // with
2312 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00002313 instruction->ReplaceInput(left->InputAt(0), 0);
2314 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00002315 left->GetBlock()->RemoveInstruction(left);
2316 right->GetBlock()->RemoveInstruction(right);
2317 RecordSimplification();
2318 return;
2319 }
2320
Anton Kirilove14dc862016-05-13 17:56:15 +01002321 if (TryReplaceWithRotate(instruction)) {
2322 return;
2323 }
2324
2325 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
2326 // so no need to return.
2327 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00002328}
2329
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002330void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
2331 HInstruction* argument = instruction->InputAt(1);
2332 HInstruction* receiver = instruction->InputAt(0);
2333 if (receiver == argument) {
2334 // Because String.equals is an instance call, the receiver is
2335 // a null check if we don't know it's null. The argument however, will
2336 // be the actual object. So we cannot end up in a situation where both
2337 // are equal but could be null.
2338 DCHECK(CanEnsureNotNullAt(argument, instruction));
2339 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
2340 instruction->GetBlock()->RemoveInstruction(instruction);
2341 } else {
2342 StringEqualsOptimizations optimizations(instruction);
2343 if (CanEnsureNotNullAt(argument, instruction)) {
2344 optimizations.SetArgumentNotNull();
2345 }
2346 ScopedObjectAccess soa(Thread::Current());
2347 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
2348 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
2349 optimizations.SetArgumentIsString();
2350 }
2351 }
2352}
2353
2354static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2355 if (potential_length->IsArrayLength()) {
2356 return potential_length->InputAt(0) == potential_array;
2357 }
2358
2359 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002360 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002361 }
2362
2363 return false;
2364}
2365
2366void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2367 HInstruction* source = instruction->InputAt(0);
2368 HInstruction* destination = instruction->InputAt(2);
2369 HInstruction* count = instruction->InputAt(4);
2370 SystemArrayCopyOptimizations optimizations(instruction);
2371 if (CanEnsureNotNullAt(source, instruction)) {
2372 optimizations.SetSourceIsNotNull();
2373 }
2374 if (CanEnsureNotNullAt(destination, instruction)) {
2375 optimizations.SetDestinationIsNotNull();
2376 }
2377 if (destination == source) {
2378 optimizations.SetDestinationIsSource();
2379 }
2380
2381 if (IsArrayLengthOf(count, source)) {
2382 optimizations.SetCountIsSourceLength();
2383 }
2384
2385 if (IsArrayLengthOf(count, destination)) {
2386 optimizations.SetCountIsDestinationLength();
2387 }
2388
2389 {
2390 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002391 DataType::Type source_component_type = DataType::Type::kVoid;
2392 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002393 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2394 if (destination_rti.IsValid()) {
2395 if (destination_rti.IsObjectArray()) {
2396 if (destination_rti.IsExact()) {
2397 optimizations.SetDoesNotNeedTypeCheck();
2398 }
2399 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002400 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002401 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002402 destination_component_type = DataTypeFromPrimitive(
2403 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002404 optimizations.SetDestinationIsPrimitiveArray();
2405 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2406 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002407 }
2408 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002409 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2410 if (source_rti.IsValid()) {
2411 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2412 optimizations.SetDoesNotNeedTypeCheck();
2413 }
2414 if (source_rti.IsPrimitiveArrayClass()) {
2415 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002416 source_component_type = DataTypeFromPrimitive(
2417 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002418 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2419 optimizations.SetSourceIsNonPrimitiveArray();
2420 }
2421 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002422 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002423 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002424 (source_component_type == destination_component_type)) {
2425 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2426 PointerSize image_size = class_linker->GetImagePointerSize();
2427 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
Vladimir Markod93e3742018-07-18 10:58:13 +01002428 ObjPtr<mirror::Class> system = invoke->GetResolvedMethod()->GetDeclaringClass();
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002429 ArtMethod* method = nullptr;
2430 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002431 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002432 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002433 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002434 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002435 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002436 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002437 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002438 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002439 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002440 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002441 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002442 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002443 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002444 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002445 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002446 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002447 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002448 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002449 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002450 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002451 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002452 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002453 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002454 break;
2455 default:
2456 LOG(FATAL) << "Unreachable";
2457 }
2458 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002459 DCHECK(method->IsStatic());
2460 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002461 invoke->SetResolvedMethod(method);
2462 // Sharpen the new invoke. Note that we do not update the dex method index of
2463 // the invoke, as we would need to look it up in the current dex file, and it
2464 // is unlikely that it exists. The most usual situation for such typed
2465 // arraycopy methods is a direct pointer to the boot image.
Nicolas Geoffrayd5a86952021-01-19 10:35:54 +00002466 invoke->SetDispatchInfo(HSharpening::SharpenLoadMethod(
2467 method,
2468 /* has_method_id= */ true,
2469 /* for_interface_call= */ false,
2470 codegen_));
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002471 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002472 }
2473}
2474
Aart Bik2a6aad92016-02-25 11:32:32 -08002475void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2476 DCHECK(invoke->IsInvokeStaticOrDirect());
2477 uint32_t dex_pc = invoke->GetDexPc();
2478 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002479 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002480 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2481 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002482 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002483 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2484 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00002485 kNeedsEnvironment,
Aart Bik2a6aad92016-02-25 11:32:32 -08002486 kNoSideEffects,
2487 kNoThrow);
2488 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002489 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002490 nan = GetGraph()->GetIntConstant(0x7fc00000);
2491 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00002492 kNeedsEnvironment,
Aart Bik2a6aad92016-02-25 11:32:32 -08002493 kNoSideEffects,
2494 kNoThrow);
2495 }
2496 // Test IsNaN(x), which is the same as x != x.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002497 HCondition* condition = new (GetGraph()->GetAllocator()) HNotEqual(x, x, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002498 condition->SetBias(ComparisonBias::kLtBias);
2499 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2500 // Select between the two.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002501 HInstruction* select = new (GetGraph()->GetAllocator()) HSelect(condition, nan, invoke, dex_pc);
Aart Bik2a6aad92016-02-25 11:32:32 -08002502 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2503 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2504}
2505
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002506void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2507 HInstruction* str = invoke->InputAt(0);
2508 HInstruction* index = invoke->InputAt(1);
2509 uint32_t dex_pc = invoke->GetDexPc();
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002510 ArenaAllocator* allocator = GetGraph()->GetAllocator();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002511 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2512 // so create the HArrayLength, HBoundsCheck and HArrayGet.
Andreas Gampe3db70682018-12-26 15:12:03 -08002513 HArrayLength* length = new (allocator) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002514 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002515 HBoundsCheck* bounds_check = new (allocator) HBoundsCheck(
Andreas Gampe3db70682018-12-26 15:12:03 -08002516 index, length, dex_pc, /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002517 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01002518 HArrayGet* array_get = new (allocator) HArrayGet(str,
2519 bounds_check,
2520 DataType::Type::kUint16,
2521 SideEffects::None(), // Strings are immutable.
2522 dex_pc,
Andreas Gampe3db70682018-12-26 15:12:03 -08002523 /* is_string_char_at= */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002524 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2525 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2526 GetGraph()->SetHasBoundsChecks(true);
2527}
2528
Vladimir Marko5f846072020-04-09 13:20:11 +01002529void InstructionSimplifierVisitor::SimplifyStringLength(HInvoke* invoke) {
Vladimir Markodce016e2016-04-28 13:10:02 +01002530 HInstruction* str = invoke->InputAt(0);
2531 uint32_t dex_pc = invoke->GetDexPc();
2532 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2533 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002534 HArrayLength* length =
Andreas Gampe3db70682018-12-26 15:12:03 -08002535 new (GetGraph()->GetAllocator()) HArrayLength(str, dex_pc, /* is_string_length= */ true);
Vladimir Marko5f846072020-04-09 13:20:11 +01002536 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, length);
Vladimir Markodce016e2016-04-28 13:10:02 +01002537}
2538
Vladimir Marko6fa44042018-03-19 18:42:49 +00002539void InstructionSimplifierVisitor::SimplifyStringIndexOf(HInvoke* invoke) {
2540 DCHECK(invoke->GetIntrinsic() == Intrinsics::kStringIndexOf ||
2541 invoke->GetIntrinsic() == Intrinsics::kStringIndexOfAfter);
2542 if (invoke->InputAt(0)->IsLoadString()) {
2543 HLoadString* load_string = invoke->InputAt(0)->AsLoadString();
2544 const DexFile& dex_file = load_string->GetDexFile();
2545 uint32_t utf16_length;
2546 const char* data =
2547 dex_file.StringDataAndUtf16LengthByIdx(load_string->GetStringIndex(), &utf16_length);
2548 if (utf16_length == 0) {
2549 invoke->ReplaceWith(GetGraph()->GetIntConstant(-1));
2550 invoke->GetBlock()->RemoveInstruction(invoke);
2551 RecordSimplification();
2552 return;
2553 }
2554 if (utf16_length == 1 && invoke->GetIntrinsic() == Intrinsics::kStringIndexOf) {
2555 // Simplify to HSelect(HEquals(., load_string.charAt(0)), 0, -1).
2556 // If the sought character is supplementary, this gives the correct result, i.e. -1.
2557 uint32_t c = GetUtf16FromUtf8(&data);
2558 DCHECK_EQ(GetTrailingUtf16Char(c), 0u);
2559 DCHECK_EQ(GetLeadingUtf16Char(c), c);
2560 uint32_t dex_pc = invoke->GetDexPc();
2561 ArenaAllocator* allocator = GetGraph()->GetAllocator();
2562 HEqual* equal =
2563 new (allocator) HEqual(invoke->InputAt(1), GetGraph()->GetIntConstant(c), dex_pc);
2564 invoke->GetBlock()->InsertInstructionBefore(equal, invoke);
2565 HSelect* result = new (allocator) HSelect(equal,
2566 GetGraph()->GetIntConstant(0),
2567 GetGraph()->GetIntConstant(-1),
2568 dex_pc);
2569 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, result);
2570 RecordSimplification();
2571 return;
2572 }
2573 }
2574}
2575
Aart Bikff7d89c2016-11-07 08:49:28 -08002576// This method should only be used on intrinsics whose sole way of throwing an
2577// exception is raising a NPE when the nth argument is null. If that argument
2578// is provably non-null, we can clear the flag.
2579void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2580 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002581 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002582 invoke->SetCanThrow(false);
2583 }
2584}
2585
Aart Bik71bf7b42016-11-16 10:17:46 -08002586// Methods that return "this" can replace the returned value with the receiver.
2587void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2588 if (invoke->HasUses()) {
2589 HInstruction* receiver = invoke->InputAt(0);
2590 invoke->ReplaceWith(receiver);
2591 RecordSimplification();
2592 }
2593}
2594
2595// Helper method for StringBuffer escape analysis.
2596static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2597 if (user->IsInvokeStaticOrDirect()) {
2598 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002599 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2600 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002601 user->InputAt(0) == reference;
2602 } else if (user->IsInvokeVirtual()) {
2603 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2604 case Intrinsics::kStringBufferLength:
2605 case Intrinsics::kStringBufferToString:
2606 DCHECK_EQ(user->InputAt(0), reference);
2607 return true;
2608 case Intrinsics::kStringBufferAppend:
2609 // Returns "this", so only okay if no further uses.
2610 DCHECK_EQ(user->InputAt(0), reference);
2611 DCHECK_NE(user->InputAt(1), reference);
2612 return !user->HasUses();
2613 default:
2614 break;
2615 }
2616 }
2617 return false;
2618}
2619
Vladimir Marko552a1342017-10-31 10:56:47 +00002620static bool TryReplaceStringBuilderAppend(HInvoke* invoke) {
2621 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringBuilderToString);
2622 if (invoke->CanThrowIntoCatchBlock()) {
2623 return false;
2624 }
2625
2626 HBasicBlock* block = invoke->GetBlock();
2627 HInstruction* sb = invoke->InputAt(0);
2628
2629 // We support only a new StringBuilder, otherwise we cannot ensure that
2630 // the StringBuilder data does not need to be populated for other users.
2631 if (!sb->IsNewInstance()) {
2632 return false;
2633 }
2634
2635 // For now, we support only single-block recognition.
2636 // (Ternary operators feeding the append could be implemented.)
2637 for (const HUseListNode<HInstruction*>& use : sb->GetUses()) {
2638 if (use.GetUser()->GetBlock() != block) {
2639 return false;
2640 }
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002641 // The append pattern uses the StringBuilder only as the first argument.
2642 if (use.GetIndex() != 0u) {
2643 return false;
2644 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002645 }
2646
2647 // Collect args and check for unexpected uses.
2648 // We expect one call to a constructor with no arguments, one constructor fence (unless
2649 // eliminated), some number of append calls and one call to StringBuilder.toString().
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002650 bool constructor_inlined = false;
Vladimir Marko552a1342017-10-31 10:56:47 +00002651 bool seen_constructor = false;
2652 bool seen_constructor_fence = false;
2653 bool seen_to_string = false;
2654 uint32_t format = 0u;
2655 uint32_t num_args = 0u;
2656 HInstruction* args[StringBuilderAppend::kMaxArgs]; // Added in reverse order.
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002657 // When inlining, `maybe_new_array` tracks an environment use that we want to allow.
2658 HInstruction* maybe_new_array = nullptr;
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002659 for (HBackwardInstructionIterator iter(block->GetInstructions()); !iter.Done(); iter.Advance()) {
2660 HInstruction* user = iter.Current();
2661 // Instructions of interest apply to `sb`, skip those that do not involve `sb`.
2662 if (user->InputCount() == 0u || user->InputAt(0u) != sb) {
2663 continue;
Vladimir Marko552a1342017-10-31 10:56:47 +00002664 }
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002665 // We visit the uses in reverse order, so the StringBuilder.toString() must come first.
Vladimir Marko552a1342017-10-31 10:56:47 +00002666 if (!seen_to_string) {
Vladimir Markoa18f5ae2019-12-13 12:53:39 +00002667 if (user == invoke) {
Vladimir Marko552a1342017-10-31 10:56:47 +00002668 seen_to_string = true;
2669 continue;
2670 } else {
2671 return false;
2672 }
2673 }
2674 // Then we should see the arguments.
2675 if (user->IsInvokeVirtual()) {
2676 HInvokeVirtual* as_invoke_virtual = user->AsInvokeVirtual();
2677 DCHECK(!seen_constructor);
2678 DCHECK(!seen_constructor_fence);
2679 StringBuilderAppend::Argument arg;
2680 switch (as_invoke_virtual->GetIntrinsic()) {
2681 case Intrinsics::kStringBuilderAppendObject:
2682 // TODO: Unimplemented, needs to call String.valueOf().
2683 return false;
2684 case Intrinsics::kStringBuilderAppendString:
2685 arg = StringBuilderAppend::Argument::kString;
2686 break;
2687 case Intrinsics::kStringBuilderAppendCharArray:
2688 // TODO: Unimplemented, StringBuilder.append(char[]) can throw NPE and we would
2689 // not have the correct stack trace for it.
2690 return false;
2691 case Intrinsics::kStringBuilderAppendBoolean:
2692 arg = StringBuilderAppend::Argument::kBoolean;
2693 break;
2694 case Intrinsics::kStringBuilderAppendChar:
2695 arg = StringBuilderAppend::Argument::kChar;
2696 break;
2697 case Intrinsics::kStringBuilderAppendInt:
2698 arg = StringBuilderAppend::Argument::kInt;
2699 break;
2700 case Intrinsics::kStringBuilderAppendLong:
2701 arg = StringBuilderAppend::Argument::kLong;
2702 break;
2703 case Intrinsics::kStringBuilderAppendCharSequence: {
2704 ReferenceTypeInfo rti = user->AsInvokeVirtual()->InputAt(1)->GetReferenceTypeInfo();
2705 if (!rti.IsValid()) {
2706 return false;
2707 }
2708 ScopedObjectAccess soa(Thread::Current());
2709 Handle<mirror::Class> input_type = rti.GetTypeHandle();
2710 DCHECK(input_type != nullptr);
2711 if (input_type.Get() == GetClassRoot<mirror::String>()) {
2712 arg = StringBuilderAppend::Argument::kString;
2713 } else {
2714 // TODO: Check and implement for StringBuilder. We could find the StringBuilder's
2715 // internal char[] inconsistent with the length, or the string compression
2716 // of the result could be compromised with a concurrent modification, and
2717 // we would need to throw appropriate exceptions.
2718 return false;
2719 }
2720 break;
2721 }
2722 case Intrinsics::kStringBuilderAppendFloat:
2723 case Intrinsics::kStringBuilderAppendDouble:
2724 // TODO: Unimplemented, needs to call FloatingDecimal.getBinaryToASCIIConverter().
2725 return false;
2726 default: {
2727 return false;
2728 }
2729 }
2730 // Uses of the append return value should have been replaced with the first input.
2731 DCHECK(!as_invoke_virtual->HasUses());
2732 DCHECK(!as_invoke_virtual->HasEnvironmentUses());
2733 if (num_args == StringBuilderAppend::kMaxArgs) {
2734 return false;
2735 }
2736 format = (format << StringBuilderAppend::kBitsPerArg) | static_cast<uint32_t>(arg);
2737 args[num_args] = as_invoke_virtual->InputAt(1u);
2738 ++num_args;
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002739 } else if (!seen_constructor) {
2740 // At this point, we should see the constructor. However, we might have inlined it so we have
2741 // to take care of both cases. We accept only the constructor with no extra arguments. This
2742 // means that if we inline it, we have to check it is setting its field to a new array.
2743 if (user->IsInvokeStaticOrDirect() &&
2744 user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2745 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
2746 user->AsInvokeStaticOrDirect()->GetNumberOfArguments() == 1u) {
2747 constructor_inlined = false;
2748 } else if (user->IsInstanceFieldSet() &&
2749 user->AsInstanceFieldSet()->GetFieldType() == DataType::Type::kReference &&
2750 user->AsInstanceFieldSet()->InputAt(0) == sb &&
2751 user->AsInstanceFieldSet()->GetValue()->IsNewArray()) {
2752 maybe_new_array = user->AsInstanceFieldSet()->GetValue();
2753 constructor_inlined = true;
2754 } else {
2755 // We were expecting a constructor but we haven't seen it. Abort optimization.
2756 return false;
2757 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002758 DCHECK(!seen_constructor_fence);
2759 seen_constructor = true;
2760 } else if (user->IsConstructorFence()) {
2761 // The last use we see is the constructor fence.
2762 DCHECK(seen_constructor);
2763 DCHECK(!seen_constructor_fence);
2764 seen_constructor_fence = true;
2765 } else {
2766 return false;
2767 }
2768 }
2769
2770 if (num_args == 0u) {
2771 return false;
2772 }
2773
2774 // Check environment uses.
2775 for (const HUseListNode<HEnvironment*>& use : sb->GetEnvUses()) {
2776 HInstruction* holder = use.GetUser()->GetHolder();
2777 if (holder->GetBlock() != block) {
2778 return false;
2779 }
2780 // Accept only calls on the StringBuilder (which shall all be removed).
2781 // TODO: Carve-out for const-string? Or rely on environment pruning (to be implemented)?
2782 if (holder->InputCount() == 0 || holder->InputAt(0) != sb) {
Nicolas Geoffraye25f13a2022-03-14 13:14:41 +00002783 // When inlining the constructor, we have a NewArray and may have a LoadClass as an
2784 // environment use.
2785 if (constructor_inlined) {
2786 if (holder == maybe_new_array) {
2787 continue;
2788 }
2789 if (holder == maybe_new_array->InputAt(0)) {
2790 DCHECK(holder->IsLoadClass());
2791 continue;
2792 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002793 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002794 return false;
2795 }
2796 }
2797
2798 // Create replacement instruction.
2799 HIntConstant* fmt = block->GetGraph()->GetIntConstant(static_cast<int32_t>(format));
2800 ArenaAllocator* allocator = block->GetGraph()->GetAllocator();
2801 HStringBuilderAppend* append =
2802 new (allocator) HStringBuilderAppend(fmt, num_args, allocator, invoke->GetDexPc());
2803 append->SetReferenceTypeInfo(invoke->GetReferenceTypeInfo());
2804 for (size_t i = 0; i != num_args; ++i) {
2805 append->SetArgumentAt(i, args[num_args - 1u - i]);
2806 }
2807 block->InsertInstructionBefore(append, invoke);
Vladimir Markob1fe5e12020-03-10 14:30:49 +00002808 DCHECK(!invoke->CanBeNull());
2809 DCHECK(!append->CanBeNull());
Vladimir Marko552a1342017-10-31 10:56:47 +00002810 invoke->ReplaceWith(append);
2811 // Copy environment, except for the StringBuilder uses.
Vladimir Marko56f13322019-11-15 14:07:19 +00002812 for (HEnvironment* env = invoke->GetEnvironment(); env != nullptr; env = env->GetParent()) {
2813 for (size_t i = 0, size = env->Size(); i != size; ++i) {
2814 if (env->GetInstructionAt(i) == sb) {
2815 env->RemoveAsUserOfInput(i);
2816 env->SetRawEnvAt(i, /*instruction=*/ nullptr);
2817 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002818 }
2819 }
2820 append->CopyEnvironmentFrom(invoke->GetEnvironment());
2821 // Remove the old instruction.
2822 block->RemoveInstruction(invoke);
2823 // Remove the StringBuilder's uses and StringBuilder.
2824 while (sb->HasNonEnvironmentUses()) {
2825 block->RemoveInstruction(sb->GetUses().front().GetUser());
2826 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002827 if (constructor_inlined) {
Nicolas Geoffraye25f13a2022-03-14 13:14:41 +00002828 // We need to remove the inlined constructor instructions,
2829 // and all remaining environment uses (if any).
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002830 DCHECK(sb->HasEnvironmentUses());
2831 DCHECK(maybe_new_array != nullptr);
2832 DCHECK(maybe_new_array->IsNewArray());
2833 DCHECK(maybe_new_array->HasNonEnvironmentUses());
2834 HInstruction* fence = maybe_new_array->GetUses().front().GetUser();
2835 DCHECK(fence->IsConstructorFence());
2836 block->RemoveInstruction(fence);
2837 block->RemoveInstruction(maybe_new_array);
Nicolas Geoffraye25f13a2022-03-14 13:14:41 +00002838 if (sb->HasEnvironmentUses()) {
2839 // We know the only remaining uses are from the LoadClass.
2840 HInstruction* load_class = maybe_new_array->InputAt(0);
2841 DCHECK(load_class->IsLoadClass());
2842 for (HEnvironment* env = load_class->GetEnvironment();
2843 env != nullptr;
2844 env = env->GetParent()) {
2845 for (size_t i = 0, size = env->Size(); i != size; ++i) {
2846 if (env->GetInstructionAt(i) == sb) {
2847 env->RemoveAsUserOfInput(i);
2848 env->SetRawEnvAt(i, /*instruction=*/ nullptr);
2849 }
2850 }
2851 }
2852 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00002853 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002854 DCHECK(!sb->HasEnvironmentUses());
2855 block->RemoveInstruction(sb);
2856 return true;
2857}
2858
Aart Bik71bf7b42016-11-16 10:17:46 -08002859// Certain allocation intrinsics are not removed by dead code elimination
2860// because of potentially throwing an OOM exception or other side effects.
2861// This method removes such intrinsics when special circumstances allow.
2862void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2863 if (!invoke->HasUses()) {
2864 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2865 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2866 // call does not escape since only thread-local synchronization may be removed.
2867 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2868 HInstruction* receiver = invoke->InputAt(0);
2869 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2870 invoke->GetBlock()->RemoveInstruction(invoke);
2871 RecordSimplification();
2872 }
Vladimir Marko552a1342017-10-31 10:56:47 +00002873 } else if (invoke->GetIntrinsic() == Intrinsics::kStringBuilderToString &&
2874 TryReplaceStringBuilderAppend(invoke)) {
2875 RecordSimplification();
Aart Bik71bf7b42016-11-16 10:17:46 -08002876 }
2877}
2878
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002879void InstructionSimplifierVisitor::SimplifyVarHandleIntrinsic(HInvoke* invoke) {
2880 DCHECK(invoke->IsInvokePolymorphic());
2881 VarHandleOptimizations optimizations(invoke);
2882
2883 if (optimizations.GetDoNotIntrinsify()) {
2884 // Preceding static checks disabled intrinsic, so no need to analyze further.
2885 return;
2886 }
2887
2888 size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002889 if (expected_coordinates_count != 0u) {
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002890 HInstruction* object = invoke->InputAt(1);
Ulya Trafimovich3676b362021-09-02 16:13:51 +01002891 // The following has been ensured by static checks in the instruction builder.
2892 DCHECK(object->GetType() == DataType::Type::kReference);
2893 // Re-check for null constant, as this might have changed after the inliner.
2894 if (object->IsNullConstant()) {
2895 optimizations.SetDoNotIntrinsify();
2896 return;
2897 }
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00002898 // Test whether we can avoid the null check on the object.
2899 if (CanEnsureNotNullAt(object, invoke)) {
2900 optimizations.SetSkipObjectNullCheck();
2901 }
2902 }
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002903
2904 if (CanUseKnownBootImageVarHandle(invoke)) {
2905 optimizations.SetUseKnownBootImageVarHandle();
2906 }
2907}
2908
2909bool InstructionSimplifierVisitor::CanUseKnownBootImageVarHandle(HInvoke* invoke) {
2910 // If the `VarHandle` comes from a static final field of an initialized class in
2911 // the boot image, we can do the checks at compile time. We do this optimization only
2912 // for AOT and only for field handles when we can avoid all checks. This avoids the
2913 // possibility of the code concurrently messing with the `VarHandle` using reflection,
2914 // we simply perform the operation with the `VarHandle` as seen at compile time.
2915 // TODO: Extend this to arrays to support the `AtomicIntegerArray` class.
2916 const CompilerOptions& compiler_options = codegen_->GetCompilerOptions();
2917 if (!compiler_options.IsAotCompiler()) {
2918 return false;
2919 }
2920 size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
2921 if (expected_coordinates_count == 2u) {
2922 return false;
2923 }
2924 HInstruction* var_handle_instruction = invoke->InputAt(0);
2925 if (var_handle_instruction->IsNullCheck()) {
2926 var_handle_instruction = var_handle_instruction->InputAt(0);
2927 }
2928 if (!var_handle_instruction->IsStaticFieldGet()) {
2929 return false;
2930 }
2931 ArtField* field = var_handle_instruction->AsStaticFieldGet()->GetFieldInfo().GetField();
2932 DCHECK(field->IsStatic());
2933 if (!field->IsFinal()) {
2934 return false;
2935 }
2936 ScopedObjectAccess soa(Thread::Current());
2937 ObjPtr<mirror::Class> declaring_class = field->GetDeclaringClass();
2938 if (!declaring_class->IsVisiblyInitialized()) {
2939 // During AOT compilation, dex2oat ensures that initialized classes are visibly initialized.
2940 DCHECK(!declaring_class->IsInitialized());
2941 return false;
2942 }
Vladimir Markoc05a32a2022-04-29 09:34:04 +01002943 HInstruction* load_class = var_handle_instruction->InputAt(0);
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002944 if (kIsDebugBuild) {
2945 bool is_in_boot_image = false;
2946 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(declaring_class)) {
2947 is_in_boot_image = true;
2948 } else if (compiler_options.IsBootImage() || compiler_options.IsBootImageExtension()) {
2949 std::string storage;
2950 const char* descriptor = declaring_class->GetDescriptor(&storage);
2951 is_in_boot_image = compiler_options.IsImageClass(descriptor);
2952 }
Vladimir Marko1fbfa9b2022-04-28 15:46:40 +01002953 CHECK_EQ(is_in_boot_image,
2954 load_class->IsLoadClass() && load_class->AsLoadClass()->IsInBootImage());
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002955 }
Vladimir Marko1fbfa9b2022-04-28 15:46:40 +01002956 if (!load_class->IsLoadClass() || !load_class->AsLoadClass()->IsInBootImage()) {
Vladimir Marko9d31daa2022-04-14 10:48:44 +01002957 return false;
2958 }
2959
2960 // Get the `VarHandle` object and check its class.
2961 ObjPtr<mirror::Class> expected_var_handle_class;
2962 switch (expected_coordinates_count) {
2963 case 0:
2964 expected_var_handle_class = GetClassRoot<mirror::StaticFieldVarHandle>();
2965 break;
2966 default:
2967 DCHECK_EQ(expected_coordinates_count, 1u);
2968 expected_var_handle_class = GetClassRoot<mirror::FieldVarHandle>();
2969 break;
2970 }
2971 ObjPtr<mirror::Object> var_handle_object = field->GetObject(declaring_class);
2972 if (var_handle_object == nullptr || var_handle_object->GetClass() != expected_var_handle_class) {
2973 return false;
2974 }
2975 ObjPtr<mirror::VarHandle> var_handle = ObjPtr<mirror::VarHandle>::DownCast(var_handle_object);
2976
2977 // Check access mode.
2978 mirror::VarHandle::AccessMode access_mode =
2979 mirror::VarHandle::GetAccessModeByIntrinsic(invoke->GetIntrinsic());
2980 if (!var_handle->IsAccessModeSupported(access_mode)) {
2981 return false;
2982 }
2983
2984 // Check argument types.
2985 ObjPtr<mirror::Class> var_type = var_handle->GetVarType();
2986 mirror::VarHandle::AccessModeTemplate access_mode_template =
2987 mirror::VarHandle::GetAccessModeTemplate(access_mode);
2988 // Note: The data type of input arguments does not need to match the type from shorty
2989 // due to implicit conversions or avoiding unnecessary conversions before narrow stores.
2990 DataType::Type type = (access_mode_template == mirror::VarHandle::AccessModeTemplate::kGet)
2991 ? invoke->GetType()
2992 : GetDataTypeFromShorty(invoke, invoke->GetNumberOfArguments() - 1u);
2993 if (type != DataTypeFromPrimitive(var_type->GetPrimitiveType())) {
2994 return false;
2995 }
2996 if (type == DataType::Type::kReference) {
2997 uint32_t arguments_start = /* VarHandle object */ 1u + expected_coordinates_count;
2998 uint32_t number_of_arguments = invoke->GetNumberOfArguments();
2999 for (size_t arg_index = arguments_start; arg_index != number_of_arguments; ++arg_index) {
3000 HInstruction* arg = invoke->InputAt(arg_index);
3001 DCHECK_EQ(arg->GetType(), DataType::Type::kReference);
3002 if (!arg->IsNullConstant()) {
3003 ReferenceTypeInfo arg_type_info = arg->GetReferenceTypeInfo();
3004 if (!arg_type_info.IsValid() ||
3005 !var_type->IsAssignableFrom(arg_type_info.GetTypeHandle().Get())) {
3006 return false;
3007 }
3008 }
3009 }
3010 }
3011
3012 // Check the first coordinate.
3013 if (expected_coordinates_count != 0u) {
3014 ObjPtr<mirror::Class> coordinate0_type = var_handle->GetCoordinateType0();
3015 DCHECK(coordinate0_type != nullptr);
3016 ReferenceTypeInfo object_type_info = invoke->InputAt(1)->GetReferenceTypeInfo();
3017 if (!object_type_info.IsValid() ||
3018 !coordinate0_type->IsAssignableFrom(object_type_info.GetTypeHandle().Get())) {
3019 return false;
3020 }
3021 }
3022
3023 // All required checks passed.
3024 return true;
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00003025}
3026
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01003027void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08003028 switch (instruction->GetIntrinsic()) {
3029 case Intrinsics::kStringEquals:
3030 SimplifyStringEquals(instruction);
3031 break;
3032 case Intrinsics::kSystemArrayCopy:
3033 SimplifySystemArrayCopy(instruction);
3034 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08003035 case Intrinsics::kFloatFloatToIntBits:
3036 case Intrinsics::kDoubleDoubleToLongBits:
3037 SimplifyFP2Int(instruction);
3038 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01003039 case Intrinsics::kStringCharAt:
Vladimir Marko5f846072020-04-09 13:20:11 +01003040 // Instruction builder creates intermediate representation directly
3041 // but the inliner can sharpen CharSequence.charAt() to String.charAt().
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01003042 SimplifyStringCharAt(instruction);
3043 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01003044 case Intrinsics::kStringLength:
Vladimir Marko5f846072020-04-09 13:20:11 +01003045 // Instruction builder creates intermediate representation directly
3046 // but the inliner can sharpen CharSequence.length() to String.length().
3047 SimplifyStringLength(instruction);
Vladimir Markodce016e2016-04-28 13:10:02 +01003048 break;
Vladimir Marko6fa44042018-03-19 18:42:49 +00003049 case Intrinsics::kStringIndexOf:
3050 case Intrinsics::kStringIndexOfAfter:
3051 SimplifyStringIndexOf(instruction);
3052 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08003053 case Intrinsics::kStringStringIndexOf:
3054 case Intrinsics::kStringStringIndexOfAfter:
3055 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
3056 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08003057 case Intrinsics::kStringBufferAppend:
Vladimir Markod4561172017-10-30 17:48:25 +00003058 case Intrinsics::kStringBuilderAppendObject:
3059 case Intrinsics::kStringBuilderAppendString:
3060 case Intrinsics::kStringBuilderAppendCharSequence:
3061 case Intrinsics::kStringBuilderAppendCharArray:
3062 case Intrinsics::kStringBuilderAppendBoolean:
3063 case Intrinsics::kStringBuilderAppendChar:
3064 case Intrinsics::kStringBuilderAppendInt:
3065 case Intrinsics::kStringBuilderAppendLong:
3066 case Intrinsics::kStringBuilderAppendFloat:
3067 case Intrinsics::kStringBuilderAppendDouble:
Aart Bik71bf7b42016-11-16 10:17:46 -08003068 SimplifyReturnThis(instruction);
3069 break;
3070 case Intrinsics::kStringBufferToString:
3071 case Intrinsics::kStringBuilderToString:
3072 SimplifyAllocationIntrinsic(instruction);
3073 break;
Ulyana Trafimovich98f01d12021-07-28 14:33:34 +00003074 case Intrinsics::kVarHandleCompareAndExchange:
3075 case Intrinsics::kVarHandleCompareAndExchangeAcquire:
3076 case Intrinsics::kVarHandleCompareAndExchangeRelease:
3077 case Intrinsics::kVarHandleCompareAndSet:
3078 case Intrinsics::kVarHandleGet:
3079 case Intrinsics::kVarHandleGetAcquire:
3080 case Intrinsics::kVarHandleGetAndAdd:
3081 case Intrinsics::kVarHandleGetAndAddAcquire:
3082 case Intrinsics::kVarHandleGetAndAddRelease:
3083 case Intrinsics::kVarHandleGetAndBitwiseAnd:
3084 case Intrinsics::kVarHandleGetAndBitwiseAndAcquire:
3085 case Intrinsics::kVarHandleGetAndBitwiseAndRelease:
3086 case Intrinsics::kVarHandleGetAndBitwiseOr:
3087 case Intrinsics::kVarHandleGetAndBitwiseOrAcquire:
3088 case Intrinsics::kVarHandleGetAndBitwiseOrRelease:
3089 case Intrinsics::kVarHandleGetAndBitwiseXor:
3090 case Intrinsics::kVarHandleGetAndBitwiseXorAcquire:
3091 case Intrinsics::kVarHandleGetAndBitwiseXorRelease:
3092 case Intrinsics::kVarHandleGetAndSet:
3093 case Intrinsics::kVarHandleGetAndSetAcquire:
3094 case Intrinsics::kVarHandleGetAndSetRelease:
3095 case Intrinsics::kVarHandleGetOpaque:
3096 case Intrinsics::kVarHandleGetVolatile:
3097 case Intrinsics::kVarHandleSet:
3098 case Intrinsics::kVarHandleSetOpaque:
3099 case Intrinsics::kVarHandleSetRelease:
3100 case Intrinsics::kVarHandleSetVolatile:
3101 case Intrinsics::kVarHandleWeakCompareAndSet:
3102 case Intrinsics::kVarHandleWeakCompareAndSetAcquire:
3103 case Intrinsics::kVarHandleWeakCompareAndSetPlain:
3104 case Intrinsics::kVarHandleWeakCompareAndSetRelease:
3105 SimplifyVarHandleIntrinsic(instruction);
3106 break;
Vladimir Marko5f846072020-04-09 13:20:11 +01003107 case Intrinsics::kIntegerRotateRight:
3108 case Intrinsics::kLongRotateRight:
3109 case Intrinsics::kIntegerRotateLeft:
3110 case Intrinsics::kLongRotateLeft:
3111 case Intrinsics::kIntegerCompare:
3112 case Intrinsics::kLongCompare:
3113 case Intrinsics::kIntegerSignum:
3114 case Intrinsics::kLongSignum:
3115 case Intrinsics::kFloatIsNaN:
3116 case Intrinsics::kDoubleIsNaN:
3117 case Intrinsics::kStringIsEmpty:
Aart Bik11932592016-03-08 12:42:25 -08003118 case Intrinsics::kUnsafeLoadFence:
Aart Bik11932592016-03-08 12:42:25 -08003119 case Intrinsics::kUnsafeStoreFence:
Aart Bik11932592016-03-08 12:42:25 -08003120 case Intrinsics::kUnsafeFullFence:
Sorin Basca2f01e8e2021-06-18 06:44:07 +00003121 case Intrinsics::kJdkUnsafeLoadFence:
3122 case Intrinsics::kJdkUnsafeStoreFence:
3123 case Intrinsics::kJdkUnsafeFullFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003124 case Intrinsics::kVarHandleFullFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003125 case Intrinsics::kVarHandleAcquireFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003126 case Intrinsics::kVarHandleReleaseFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003127 case Intrinsics::kVarHandleLoadLoadFence:
Orion Hodson4a4610a2017-09-28 16:57:55 +01003128 case Intrinsics::kVarHandleStoreStoreFence:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003129 case Intrinsics::kMathMinIntInt:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003130 case Intrinsics::kMathMinLongLong:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003131 case Intrinsics::kMathMinFloatFloat:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003132 case Intrinsics::kMathMinDoubleDouble:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003133 case Intrinsics::kMathMaxIntInt:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003134 case Intrinsics::kMathMaxLongLong:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003135 case Intrinsics::kMathMaxFloatFloat:
Aart Bik1f8d51b2018-02-15 10:42:37 -08003136 case Intrinsics::kMathMaxDoubleDouble:
Aart Bik3dad3412018-02-28 12:01:46 -08003137 case Intrinsics::kMathAbsInt:
Aart Bik3dad3412018-02-28 12:01:46 -08003138 case Intrinsics::kMathAbsLong:
Aart Bik3dad3412018-02-28 12:01:46 -08003139 case Intrinsics::kMathAbsFloat:
Aart Bik3dad3412018-02-28 12:01:46 -08003140 case Intrinsics::kMathAbsDouble:
Vladimir Marko5f846072020-04-09 13:20:11 +01003141 // These are replaced by intermediate representation in the instruction builder.
3142 LOG(FATAL) << "Unexpected " << static_cast<Intrinsics>(instruction->GetIntrinsic());
3143 UNREACHABLE();
Aart Bik2a6aad92016-02-25 11:32:32 -08003144 default:
3145 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003146 }
3147}
3148
Aart Bikbb245d12015-10-19 11:05:03 -07003149void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
3150 HInstruction* cond = deoptimize->InputAt(0);
3151 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00003152 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07003153 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00003154 if (deoptimize->GuardsAnInput()) {
3155 deoptimize->ReplaceWith(deoptimize->GuardedInput());
3156 }
Aart Bikbb245d12015-10-19 11:05:03 -07003157 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
3158 } else {
3159 // Always deopt.
3160 }
3161 }
3162}
3163
Anton Kirilove14dc862016-05-13 17:56:15 +01003164// Replace code looking like
3165// OP y, x, const1
3166// OP z, y, const2
3167// with
3168// OP z, x, const3
3169// where OP is both an associative and a commutative operation.
3170bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
3171 HBinaryOperation* instruction) {
3172 DCHECK(instruction->IsCommutative());
3173
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003174 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003175 return false;
3176 }
3177
3178 HInstruction* left = instruction->GetLeft();
3179 HInstruction* right = instruction->GetRight();
3180 // Variable names as described above.
3181 HConstant* const2;
3182 HBinaryOperation* y;
3183
Vladimir Marko0dcccd82018-05-04 13:32:25 +01003184 if (instruction->GetKind() == left->GetKind() && right->IsConstant()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003185 const2 = right->AsConstant();
3186 y = left->AsBinaryOperation();
Vladimir Marko0dcccd82018-05-04 13:32:25 +01003187 } else if (left->IsConstant() && instruction->GetKind() == right->GetKind()) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003188 const2 = left->AsConstant();
3189 y = right->AsBinaryOperation();
3190 } else {
3191 // The node does not match the pattern.
3192 return false;
3193 }
3194
3195 // If `y` has more than one use, we do not perform the optimization
3196 // because it might increase code size (e.g. if the new constant is
3197 // no longer encodable as an immediate operand in the target ISA).
3198 if (!y->HasOnlyOneNonEnvironmentUse()) {
3199 return false;
3200 }
3201
3202 // GetConstantRight() can return both left and right constants
3203 // for commutative operations.
3204 HConstant* const1 = y->GetConstantRight();
3205 if (const1 == nullptr) {
3206 return false;
3207 }
3208
3209 instruction->ReplaceInput(const1, 0);
3210 instruction->ReplaceInput(const2, 1);
3211 HConstant* const3 = instruction->TryStaticEvaluation();
3212 DCHECK(const3 != nullptr);
3213 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
3214 instruction->ReplaceInput(const3, 1);
3215 RecordSimplification();
3216 return true;
3217}
3218
3219static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
3220 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
3221}
3222
3223// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003224static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003225 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003226 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003227 return HAdd::Compute<int32_t>(x, y);
3228 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003229 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01003230 return HAdd::Compute<int64_t>(x, y);
3231 }
3232}
3233
3234// Helper function that handles the child classes of HConstant
3235// and returns an integer with the appropriate sign.
3236static int64_t GetValue(HConstant* constant, bool is_negated) {
3237 int64_t ret = Int64FromConstant(constant);
3238 return is_negated ? -ret : ret;
3239}
3240
3241// Replace code looking like
3242// OP1 y, x, const1
3243// OP2 z, y, const2
3244// with
3245// OP3 z, x, const3
3246// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
3247bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
3248 HBinaryOperation* instruction) {
3249 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
3250
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003251 DataType::Type type = instruction->GetType();
3252 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01003253 return false;
3254 }
3255
3256 HInstruction* left = instruction->GetLeft();
3257 HInstruction* right = instruction->GetRight();
3258 // Variable names as described above.
3259 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
3260 if (const2 == nullptr) {
3261 return false;
3262 }
3263
3264 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
3265 ? left->AsBinaryOperation()
3266 : AsAddOrSub(right);
3267 // If y has more than one use, we do not perform the optimization because
3268 // it might increase code size (e.g. if the new constant is no longer
3269 // encodable as an immediate operand in the target ISA).
3270 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
3271 return false;
3272 }
3273
3274 left = y->GetLeft();
3275 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
3276 if (const1 == nullptr) {
3277 return false;
3278 }
3279
3280 HInstruction* x = (const1 == left) ? y->GetRight() : left;
3281 // If both inputs are constants, let the constant folding pass deal with it.
3282 if (x->IsConstant()) {
3283 return false;
3284 }
3285
3286 bool is_const2_negated = (const2 == right) && instruction->IsSub();
3287 int64_t const2_val = GetValue(const2, is_const2_negated);
3288 bool is_y_negated = (y == right) && instruction->IsSub();
3289 right = y->GetRight();
3290 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
3291 int64_t const1_val = GetValue(const1, is_const1_negated);
3292 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
3293 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
3294 HBasicBlock* block = instruction->GetBlock();
3295 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
Vladimir Markoe764d2e2017-10-05 14:35:55 +01003296 ArenaAllocator* allocator = instruction->GetAllocator();
Anton Kirilove14dc862016-05-13 17:56:15 +01003297 HInstruction* z;
3298
3299 if (is_x_negated) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01003300 z = new (allocator) HSub(type, const3, x, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01003301 } else {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01003302 z = new (allocator) HAdd(type, x, const3, instruction->GetDexPc());
Anton Kirilove14dc862016-05-13 17:56:15 +01003303 }
3304
3305 block->ReplaceAndRemoveInstructionWith(instruction, z);
3306 RecordSimplification();
3307 return true;
3308}
3309
Lena Djokicbc5460b2017-07-20 16:07:36 +02003310void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
3311 if (TryCombineVecMultiplyAccumulate(instruction)) {
3312 RecordSimplification();
3313 }
3314}
3315
Nicolas Geoffray3c049742014-09-24 18:10:46 +01003316} // namespace art