blob: 6610bcc713cd343decdf8844236dba4c4efda937 [file] [log] [blame]
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_simplifier.h"
18
Andreas Gampec6ea7d02017-02-01 16:46:28 -080019#include "art_method-inl.h"
20#include "class_linker-inl.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010021#include "data_type-inl.h"
Aart Bik71bf7b42016-11-16 10:17:46 -080022#include "escape.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010023#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070025#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070026#include "sharpening.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027
Nicolas Geoffray3c049742014-09-24 18:10:46 +010028namespace art {
29
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010030class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000031 public:
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000032 InstructionSimplifierVisitor(HGraph* graph,
33 CodeGenerator* codegen,
Vladimir Marko65979462017-05-19 17:25:12 +010034 CompilerDriver* compiler_driver,
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000035 OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010036 : HGraphDelegateVisitor(graph),
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +000037 codegen_(codegen),
Vladimir Marko65979462017-05-19 17:25:12 +010038 compiler_driver_(compiler_driver),
Alexandre Rames188d4312015-04-09 18:30:21 +010039 stats_(stats) {}
40
41 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000042
43 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010044 void RecordSimplification() {
45 simplification_occurred_ = true;
46 simplifications_at_current_position_++;
Igor Murashkin1e065a52017-08-09 13:20:34 -070047 MaybeRecordStat(stats_, kInstructionSimplifications);
Alexandre Rames188d4312015-04-09 18:30:21 +010048 }
49
Scott Wakeling40a04bf2015-12-11 09:50:36 +000050 bool ReplaceRotateWithRor(HBinaryOperation* op, HUShr* ushr, HShl* shl);
51 bool TryReplaceWithRotate(HBinaryOperation* instruction);
52 bool TryReplaceWithRotateConstantPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
53 bool TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
54 bool TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op, HUShr* ushr, HShl* shl);
55
Alexandre Rames188d4312015-04-09 18:30:21 +010056 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +000057 // `op` should be either HOr or HAnd.
58 // De Morgan's laws:
59 // ~a & ~b = ~(a | b) and ~a | ~b = ~(a & b)
60 bool TryDeMorganNegationFactoring(HBinaryOperation* op);
Anton Kirilove14dc862016-05-13 17:56:15 +010061 bool TryHandleAssociativeAndCommutativeOperation(HBinaryOperation* instruction);
62 bool TrySubtractionChainSimplification(HBinaryOperation* instruction);
Lena Djokicbc5460b2017-07-20 16:07:36 +020063 bool TryCombineVecMultiplyAccumulate(HVecMul* mul);
Anton Kirilove14dc862016-05-13 17:56:15 +010064
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000065 void VisitShift(HBinaryOperation* shift);
66
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000067 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010068 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
69 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010070 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
71 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000072 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000073 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000074 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080075 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000076 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000077 void VisitAdd(HAdd* instruction) OVERRIDE;
78 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040079 void VisitCondition(HCondition* instruction) OVERRIDE;
80 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
81 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
82 void VisitLessThan(HLessThan* condition) OVERRIDE;
83 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Anton Shaminbdd79352016-02-15 12:48:36 +060084 void VisitBelow(HBelow* condition) OVERRIDE;
85 void VisitBelowOrEqual(HBelowOrEqual* condition) OVERRIDE;
86 void VisitAbove(HAbove* condition) OVERRIDE;
87 void VisitAboveOrEqual(HAboveOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000088 void VisitDiv(HDiv* instruction) OVERRIDE;
89 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010090 void VisitNeg(HNeg* instruction) OVERRIDE;
91 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000092 void VisitOr(HOr* instruction) OVERRIDE;
93 void VisitShl(HShl* instruction) OVERRIDE;
94 void VisitShr(HShr* instruction) OVERRIDE;
95 void VisitSub(HSub* instruction) OVERRIDE;
96 void VisitUShr(HUShr* instruction) OVERRIDE;
97 void VisitXor(HXor* instruction) OVERRIDE;
David Brazdil74eb1b22015-12-14 11:44:01 +000098 void VisitSelect(HSelect* select) OVERRIDE;
99 void VisitIf(HIf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100100 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +0100101 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Aart Bikbb245d12015-10-19 11:05:03 -0700102 void VisitDeoptimize(HDeoptimize* deoptimize) OVERRIDE;
Lena Djokicbc5460b2017-07-20 16:07:36 +0200103 void VisitVecMul(HVecMul* instruction) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100104
105 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +0000106
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100107 void SimplifyRotate(HInvoke* invoke, bool is_left, DataType::Type type);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100108 void SimplifySystemArrayCopy(HInvoke* invoke);
109 void SimplifyStringEquals(HInvoke* invoke);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 void SimplifyCompare(HInvoke* invoke, bool is_signum, DataType::Type type);
Aart Bik75a38b22016-02-17 10:41:50 -0800111 void SimplifyIsNaN(HInvoke* invoke);
Aart Bik2a6aad92016-02-25 11:32:32 -0800112 void SimplifyFP2Int(HInvoke* invoke);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100113 void SimplifyStringCharAt(HInvoke* invoke);
Vladimir Markodce016e2016-04-28 13:10:02 +0100114 void SimplifyStringIsEmptyOrLength(HInvoke* invoke);
Aart Bikff7d89c2016-11-07 08:49:28 -0800115 void SimplifyNPEOnArgN(HInvoke* invoke, size_t);
Aart Bik71bf7b42016-11-16 10:17:46 -0800116 void SimplifyReturnThis(HInvoke* invoke);
117 void SimplifyAllocationIntrinsic(HInvoke* invoke);
Aart Bik11932592016-03-08 12:42:25 -0800118 void SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind);
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +0100119
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000120 CodeGenerator* codegen_;
Vladimir Marko65979462017-05-19 17:25:12 +0100121 CompilerDriver* compiler_driver_;
Calin Juravleacf735c2015-02-12 15:25:22 +0000122 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +0100123 bool simplification_occurred_ = false;
124 int simplifications_at_current_position_ = 0;
Aart Bik2767f4b2016-10-28 15:03:53 -0700125 // We ensure we do not loop infinitely. The value should not be too high, since that
126 // would allow looping around the same basic block too many times. The value should
127 // not be too low either, however, since we want to allow revisiting a basic block
128 // with many statements and simplifications at least once.
129 static constexpr int kMaxSamePositionSimplifications = 50;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000130};
131
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100132void InstructionSimplifier::Run() {
Vladimir Marko65979462017-05-19 17:25:12 +0100133 InstructionSimplifierVisitor visitor(graph_, codegen_, compiler_driver_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +0100134 visitor.Run();
135}
136
137void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100138 // Iterate in reverse post order to open up more simplifications to users
139 // of instructions that got simplified.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100140 for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100141 // The simplification of an instruction to another instruction may yield
142 // possibilities for other simplifications. So although we perform a reverse
143 // post order visit, we sometimes need to revisit an instruction index.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100144 do {
145 simplification_occurred_ = false;
146 VisitBasicBlock(block);
147 } while (simplification_occurred_ &&
148 (simplifications_at_current_position_ < kMaxSamePositionSimplifications));
Alexandre Rames188d4312015-04-09 18:30:21 +0100149 simplifications_at_current_position_ = 0;
Alexandre Rames188d4312015-04-09 18:30:21 +0100150 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100151}
152
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000153namespace {
154
155bool AreAllBitsSet(HConstant* constant) {
156 return Int64FromConstant(constant) == -1;
157}
158
159} // namespace
160
Alexandre Rames188d4312015-04-09 18:30:21 +0100161// Returns true if the code was simplified to use only one negation operation
162// after the binary operation instead of one on each of the inputs.
163bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
164 DCHECK(binop->IsAdd() || binop->IsSub());
165 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
166 HNeg* left_neg = binop->GetLeft()->AsNeg();
167 HNeg* right_neg = binop->GetRight()->AsNeg();
168 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
169 !right_neg->HasOnlyOneNonEnvironmentUse()) {
170 return false;
171 }
172 // Replace code looking like
173 // NEG tmp1, a
174 // NEG tmp2, b
175 // ADD dst, tmp1, tmp2
176 // with
177 // ADD tmp, a, b
178 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600179 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
180 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
181 // while the later yields `-0.0`.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100182 if (!DataType::IsIntegralType(binop->GetType())) {
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600183 return false;
184 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100185 binop->ReplaceInput(left_neg->GetInput(), 0);
186 binop->ReplaceInput(right_neg->GetInput(), 1);
187 left_neg->GetBlock()->RemoveInstruction(left_neg);
188 right_neg->GetBlock()->RemoveInstruction(right_neg);
189 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
190 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
191 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
192 RecordSimplification();
193 return true;
194}
195
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000196bool InstructionSimplifierVisitor::TryDeMorganNegationFactoring(HBinaryOperation* op) {
197 DCHECK(op->IsAnd() || op->IsOr()) << op->DebugName();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100198 DataType::Type type = op->GetType();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000199 HInstruction* left = op->GetLeft();
200 HInstruction* right = op->GetRight();
201
202 // We can apply De Morgan's laws if both inputs are Not's and are only used
203 // by `op`.
Alexandre Rames9f980252016-02-05 14:00:28 +0000204 if (((left->IsNot() && right->IsNot()) ||
205 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000206 left->HasOnlyOneNonEnvironmentUse() &&
207 right->HasOnlyOneNonEnvironmentUse()) {
208 // Replace code looking like
209 // NOT nota, a
210 // NOT notb, b
211 // AND dst, nota, notb (respectively OR)
212 // with
213 // OR or, a, b (respectively AND)
214 // NOT dest, or
Alexandre Rames9f980252016-02-05 14:00:28 +0000215 HInstruction* src_left = left->InputAt(0);
216 HInstruction* src_right = right->InputAt(0);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000217 uint32_t dex_pc = op->GetDexPc();
218
219 // Remove the negations on the inputs.
220 left->ReplaceWith(src_left);
221 right->ReplaceWith(src_right);
222 left->GetBlock()->RemoveInstruction(left);
223 right->GetBlock()->RemoveInstruction(right);
224
225 // Replace the `HAnd` or `HOr`.
226 HBinaryOperation* hbin;
227 if (op->IsAnd()) {
228 hbin = new (GetGraph()->GetArena()) HOr(type, src_left, src_right, dex_pc);
229 } else {
230 hbin = new (GetGraph()->GetArena()) HAnd(type, src_left, src_right, dex_pc);
231 }
Alexandre Rames9f980252016-02-05 14:00:28 +0000232 HInstruction* hnot;
233 if (left->IsBooleanNot()) {
234 hnot = new (GetGraph()->GetArena()) HBooleanNot(hbin, dex_pc);
235 } else {
236 hnot = new (GetGraph()->GetArena()) HNot(type, hbin, dex_pc);
237 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +0000238
239 op->GetBlock()->InsertInstructionBefore(hbin, op);
240 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, hnot);
241
242 RecordSimplification();
243 return true;
244 }
245
246 return false;
247}
248
Lena Djokicbc5460b2017-07-20 16:07:36 +0200249bool InstructionSimplifierVisitor::TryCombineVecMultiplyAccumulate(HVecMul* mul) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100250 DataType::Type type = mul->GetPackedType();
Lena Djokicbc5460b2017-07-20 16:07:36 +0200251 InstructionSet isa = codegen_->GetInstructionSet();
252 switch (isa) {
253 case kArm64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100254 if (!(type == DataType::Type::kUint8 ||
255 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100256 type == DataType::Type::kUint16 ||
257 type == DataType::Type::kInt16 ||
258 type == DataType::Type::kInt32)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200259 return false;
260 }
261 break;
262 case kMips:
263 case kMips64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100264 if (!(type == DataType::Type::kUint8 ||
265 type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 type == DataType::Type::kUint16 ||
267 type == DataType::Type::kInt16 ||
268 type == DataType::Type::kInt32 ||
269 type == DataType::Type::kInt64)) {
Lena Djokicbc5460b2017-07-20 16:07:36 +0200270 return false;
271 }
272 break;
273 default:
274 return false;
275 }
276
277 ArenaAllocator* arena = mul->GetBlock()->GetGraph()->GetArena();
278
279 if (mul->HasOnlyOneNonEnvironmentUse()) {
280 HInstruction* use = mul->GetUses().front().GetUser();
281 if (use->IsVecAdd() || use->IsVecSub()) {
282 // Replace code looking like
283 // VECMUL tmp, x, y
284 // VECADD/SUB dst, acc, tmp
285 // with
286 // VECMULACC dst, acc, x, y
287 // Note that we do not want to (unconditionally) perform the merge when the
288 // multiplication has multiple uses and it can be merged in all of them.
289 // Multiple uses could happen on the same control-flow path, and we would
290 // then increase the amount of work. In the future we could try to evaluate
291 // whether all uses are on different control-flow paths (using dominance and
292 // reverse-dominance information) and only perform the merge when they are.
293 HInstruction* accumulator = nullptr;
294 HVecBinaryOperation* binop = use->AsVecBinaryOperation();
295 HInstruction* binop_left = binop->GetLeft();
296 HInstruction* binop_right = binop->GetRight();
297 // This is always true since the `HVecMul` has only one use (which is checked above).
298 DCHECK_NE(binop_left, binop_right);
299 if (binop_right == mul) {
300 accumulator = binop_left;
301 } else if (use->IsVecAdd()) {
302 DCHECK_EQ(binop_left, mul);
303 accumulator = binop_right;
304 }
305
306 HInstruction::InstructionKind kind =
307 use->IsVecAdd() ? HInstruction::kAdd : HInstruction::kSub;
308 if (accumulator != nullptr) {
309 HVecMultiplyAccumulate* mulacc =
310 new (arena) HVecMultiplyAccumulate(arena,
311 kind,
312 accumulator,
313 mul->GetLeft(),
314 mul->GetRight(),
315 binop->GetPackedType(),
Aart Bik46b6dbc2017-10-03 11:37:37 -0700316 binop->GetVectorLength(),
317 binop->GetDexPc());
Lena Djokicbc5460b2017-07-20 16:07:36 +0200318
319 binop->GetBlock()->ReplaceAndRemoveInstructionWith(binop, mulacc);
320 DCHECK(!mul->HasUses());
321 mul->GetBlock()->RemoveInstruction(mul);
322 return true;
323 }
324 }
325 }
326
327 return false;
328}
329
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000330void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
331 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
Alexandre Rames50518442016-06-27 11:39:19 +0100332 HInstruction* shift_amount = instruction->GetRight();
333 HInstruction* value = instruction->GetLeft();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000334
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100335 int64_t implicit_mask = (value->GetType() == DataType::Type::kInt64)
Alexandre Rames50518442016-06-27 11:39:19 +0100336 ? kMaxLongShiftDistance
337 : kMaxIntShiftDistance;
338
339 if (shift_amount->IsConstant()) {
340 int64_t cst = Int64FromConstant(shift_amount->AsConstant());
Aart Bik50e20d52017-05-05 14:07:29 -0700341 int64_t masked_cst = cst & implicit_mask;
342 if (masked_cst == 0) {
Mark Mendellba56d062015-05-05 21:34:03 -0400343 // Replace code looking like
Alexandre Rames50518442016-06-27 11:39:19 +0100344 // SHL dst, value, 0
Mark Mendellba56d062015-05-05 21:34:03 -0400345 // with
Alexandre Rames50518442016-06-27 11:39:19 +0100346 // value
347 instruction->ReplaceWith(value);
Mark Mendellba56d062015-05-05 21:34:03 -0400348 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100349 RecordSimplification();
Alexandre Rames50518442016-06-27 11:39:19 +0100350 return;
Aart Bik50e20d52017-05-05 14:07:29 -0700351 } else if (masked_cst != cst) {
352 // Replace code looking like
353 // SHL dst, value, cst
354 // where cst exceeds maximum distance with the equivalent
355 // SHL dst, value, cst & implicit_mask
356 // (as defined by shift semantics). This ensures other
357 // optimizations do not need to special case for such situations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100358 DCHECK_EQ(shift_amount->GetType(), DataType::Type::kInt32);
Aart Bik50e20d52017-05-05 14:07:29 -0700359 instruction->ReplaceInput(GetGraph()->GetIntConstant(masked_cst), /* index */ 1);
360 RecordSimplification();
361 return;
Alexandre Rames50518442016-06-27 11:39:19 +0100362 }
363 }
364
365 // Shift operations implicitly mask the shift amount according to the type width. Get rid of
Vladimir Marko7033d492017-09-28 16:32:24 +0100366 // unnecessary And/Or/Xor/Add/Sub/TypeConversion operations on the shift amount that do not
367 // affect the relevant bits.
Alexandre Rames50518442016-06-27 11:39:19 +0100368 // Replace code looking like
Vladimir Marko7033d492017-09-28 16:32:24 +0100369 // AND adjusted_shift, shift, <superset of implicit mask>
370 // [OR/XOR/ADD/SUB adjusted_shift, shift, <value not overlapping with implicit mask>]
371 // [<conversion-from-integral-non-64-bit-type> adjusted_shift, shift]
372 // SHL dst, value, adjusted_shift
Alexandre Rames50518442016-06-27 11:39:19 +0100373 // with
374 // SHL dst, value, shift
Vladimir Marko7033d492017-09-28 16:32:24 +0100375 if (shift_amount->IsAnd() ||
376 shift_amount->IsOr() ||
377 shift_amount->IsXor() ||
378 shift_amount->IsAdd() ||
379 shift_amount->IsSub()) {
380 int64_t required_result = shift_amount->IsAnd() ? implicit_mask : 0;
381 HBinaryOperation* bin_op = shift_amount->AsBinaryOperation();
382 HConstant* mask = bin_op->GetConstantRight();
383 if (mask != nullptr && (Int64FromConstant(mask) & implicit_mask) == required_result) {
384 instruction->ReplaceInput(bin_op->GetLeastConstantLeft(), 1);
Alexandre Rames50518442016-06-27 11:39:19 +0100385 RecordSimplification();
Vladimir Marko7033d492017-09-28 16:32:24 +0100386 return;
387 }
388 } else if (shift_amount->IsTypeConversion()) {
389 DCHECK_NE(shift_amount->GetType(), DataType::Type::kBool); // We never convert to bool.
390 DataType::Type source_type = shift_amount->InputAt(0)->GetType();
391 // Non-integral and 64-bit source types require an explicit type conversion.
392 if (DataType::IsIntegralType(source_type) && !DataType::Is64BitType(source_type)) {
393 instruction->ReplaceInput(shift_amount->AsTypeConversion()->GetInput(), 1);
394 RecordSimplification();
395 return;
Mark Mendellba56d062015-05-05 21:34:03 -0400396 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000397 }
398}
399
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000400static bool IsSubRegBitsMinusOther(HSub* sub, size_t reg_bits, HInstruction* other) {
401 return (sub->GetRight() == other &&
402 sub->GetLeft()->IsConstant() &&
403 (Int64FromConstant(sub->GetLeft()->AsConstant()) & (reg_bits - 1)) == 0);
404}
405
406bool InstructionSimplifierVisitor::ReplaceRotateWithRor(HBinaryOperation* op,
407 HUShr* ushr,
408 HShl* shl) {
Roland Levillain22c49222016-03-18 14:04:28 +0000409 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr()) << op->DebugName();
410 HRor* ror = new (GetGraph()->GetArena()) HRor(ushr->GetType(), ushr->GetLeft(), ushr->GetRight());
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000411 op->GetBlock()->ReplaceAndRemoveInstructionWith(op, ror);
412 if (!ushr->HasUses()) {
413 ushr->GetBlock()->RemoveInstruction(ushr);
414 }
415 if (!ushr->GetRight()->HasUses()) {
416 ushr->GetRight()->GetBlock()->RemoveInstruction(ushr->GetRight());
417 }
418 if (!shl->HasUses()) {
419 shl->GetBlock()->RemoveInstruction(shl);
420 }
421 if (!shl->GetRight()->HasUses()) {
422 shl->GetRight()->GetBlock()->RemoveInstruction(shl->GetRight());
423 }
Alexandre Ramesc5809c32016-05-25 15:01:06 +0100424 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000425 return true;
426}
427
428// Try to replace a binary operation flanked by one UShr and one Shl with a bitfield rotation.
429bool InstructionSimplifierVisitor::TryReplaceWithRotate(HBinaryOperation* op) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000430 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
431 HInstruction* left = op->GetLeft();
432 HInstruction* right = op->GetRight();
433 // If we have an UShr and a Shl (in either order).
434 if ((left->IsUShr() && right->IsShl()) || (left->IsShl() && right->IsUShr())) {
435 HUShr* ushr = left->IsUShr() ? left->AsUShr() : right->AsUShr();
436 HShl* shl = left->IsShl() ? left->AsShl() : right->AsShl();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100437 DCHECK(DataType::IsIntOrLongType(ushr->GetType()));
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000438 if (ushr->GetType() == shl->GetType() &&
439 ushr->GetLeft() == shl->GetLeft()) {
440 if (ushr->GetRight()->IsConstant() && shl->GetRight()->IsConstant()) {
441 // Shift distances are both constant, try replacing with Ror if they
442 // add up to the register size.
443 return TryReplaceWithRotateConstantPattern(op, ushr, shl);
444 } else if (ushr->GetRight()->IsSub() || shl->GetRight()->IsSub()) {
445 // Shift distances are potentially of the form x and (reg_size - x).
446 return TryReplaceWithRotateRegisterSubPattern(op, ushr, shl);
447 } else if (ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg()) {
448 // Shift distances are potentially of the form d and -d.
449 return TryReplaceWithRotateRegisterNegPattern(op, ushr, shl);
450 }
451 }
452 }
453 return false;
454}
455
456// Try replacing code looking like (x >>> #rdist OP x << #ldist):
457// UShr dst, x, #rdist
458// Shl tmp, x, #ldist
459// OP dst, dst, tmp
460// or like (x >>> #rdist OP x << #-ldist):
461// UShr dst, x, #rdist
462// Shl tmp, x, #-ldist
463// OP dst, dst, tmp
464// with
465// Ror dst, x, #rdist
466bool InstructionSimplifierVisitor::TryReplaceWithRotateConstantPattern(HBinaryOperation* op,
467 HUShr* ushr,
468 HShl* shl) {
469 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100470 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000471 size_t rdist = Int64FromConstant(ushr->GetRight()->AsConstant());
472 size_t ldist = Int64FromConstant(shl->GetRight()->AsConstant());
473 if (((ldist + rdist) & (reg_bits - 1)) == 0) {
474 ReplaceRotateWithRor(op, ushr, shl);
475 return true;
476 }
477 return false;
478}
479
480// Replace code looking like (x >>> -d OP x << d):
481// Neg neg, d
482// UShr dst, x, neg
483// Shl tmp, x, d
484// OP dst, dst, tmp
485// with
486// Neg neg, d
487// Ror dst, x, neg
488// *** OR ***
489// Replace code looking like (x >>> d OP x << -d):
490// UShr dst, x, d
491// Neg neg, d
492// Shl tmp, x, neg
493// OP dst, dst, tmp
494// with
495// Ror dst, x, d
496bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterNegPattern(HBinaryOperation* op,
497 HUShr* ushr,
498 HShl* shl) {
499 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
500 DCHECK(ushr->GetRight()->IsNeg() || shl->GetRight()->IsNeg());
501 bool neg_is_left = shl->GetRight()->IsNeg();
502 HNeg* neg = neg_is_left ? shl->GetRight()->AsNeg() : ushr->GetRight()->AsNeg();
503 // And the shift distance being negated is the distance being shifted the other way.
504 if (neg->InputAt(0) == (neg_is_left ? ushr->GetRight() : shl->GetRight())) {
505 ReplaceRotateWithRor(op, ushr, shl);
506 }
507 return false;
508}
509
510// Try replacing code looking like (x >>> d OP x << (#bits - d)):
511// UShr dst, x, d
512// Sub ld, #bits, d
513// Shl tmp, x, ld
514// OP dst, dst, tmp
515// with
516// Ror dst, x, d
517// *** OR ***
518// Replace code looking like (x >>> (#bits - d) OP x << d):
519// Sub rd, #bits, d
520// UShr dst, x, rd
521// Shl tmp, x, d
522// OP dst, dst, tmp
523// with
524// Neg neg, d
525// Ror dst, x, neg
526bool InstructionSimplifierVisitor::TryReplaceWithRotateRegisterSubPattern(HBinaryOperation* op,
527 HUShr* ushr,
528 HShl* shl) {
529 DCHECK(op->IsAdd() || op->IsXor() || op->IsOr());
530 DCHECK(ushr->GetRight()->IsSub() || shl->GetRight()->IsSub());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100531 size_t reg_bits = DataType::Size(ushr->GetType()) * kBitsPerByte;
Scott Wakeling40a04bf2015-12-11 09:50:36 +0000532 HInstruction* shl_shift = shl->GetRight();
533 HInstruction* ushr_shift = ushr->GetRight();
534 if ((shl_shift->IsSub() && IsSubRegBitsMinusOther(shl_shift->AsSub(), reg_bits, ushr_shift)) ||
535 (ushr_shift->IsSub() && IsSubRegBitsMinusOther(ushr_shift->AsSub(), reg_bits, shl_shift))) {
536 return ReplaceRotateWithRor(op, ushr, shl);
537 }
538 return false;
539}
540
Calin Juravle10e244f2015-01-26 18:54:32 +0000541void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
542 HInstruction* obj = null_check->InputAt(0);
543 if (!obj->CanBeNull()) {
544 null_check->ReplaceWith(obj);
545 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000546 if (stats_ != nullptr) {
547 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
548 }
549 }
550}
551
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100552bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
553 if (!input->CanBeNull()) {
554 return true;
555 }
556
Vladimir Marko46817b82016-03-29 12:21:58 +0100557 for (const HUseListNode<HInstruction*>& use : input->GetUses()) {
558 HInstruction* user = use.GetUser();
559 if (user->IsNullCheck() && user->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100560 return true;
561 }
562 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100563
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100564 return false;
565}
566
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100567// Returns whether doing a type test between the class of `object` against `klass` has
568// a statically known outcome. The result of the test is stored in `outcome`.
569static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000570 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
571 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
572 ScopedObjectAccess soa(Thread::Current());
573 if (!obj_rti.IsValid()) {
574 // We run the simplifier before the reference type propagation so type info might not be
575 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100576 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000577 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100578
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100579 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100580 if (!class_rti.IsValid()) {
581 // Happens when the loaded class is unresolved.
582 return false;
583 }
584 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000585 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100586 *outcome = true;
587 return true;
588 } else if (obj_rti.IsExact()) {
589 // The test failed at compile time so will also fail at runtime.
590 *outcome = false;
591 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100592 } else if (!class_rti.IsInterface()
593 && !obj_rti.IsInterface()
594 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100595 // Different type hierarchy. The test will fail.
596 *outcome = false;
597 return true;
598 }
599 return false;
600}
601
602void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
603 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100604 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
605 if (load_class->NeedsAccessCheck()) {
606 // If we need to perform an access check we cannot remove the instruction.
607 return;
608 }
609
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100610 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100611 check_cast->ClearMustDoNullCheck();
612 }
613
614 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000615 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700616 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100617 return;
618 }
619
Vladimir Markoa65ed302016-03-14 21:21:29 +0000620 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
621 // the return value check with the `outcome` check, b/27651442 .
622 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700623 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100624 if (outcome) {
625 check_cast->GetBlock()->RemoveInstruction(check_cast);
Igor Murashkin1e065a52017-08-09 13:20:34 -0700626 MaybeRecordStat(stats_, MethodCompilationStat::kRemovedCheckedCast);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700627 if (!load_class->HasUses()) {
628 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
629 // However, here we know that it cannot because the checkcast was successfull, hence
630 // the class was already loaded.
631 load_class->GetBlock()->RemoveInstruction(load_class);
632 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100633 } else {
634 // Don't do anything for exceptional cases for now. Ideally we should remove
635 // all instructions and blocks this instruction dominates.
636 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000637 }
638}
639
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100640void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100641 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100642 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
643 if (load_class->NeedsAccessCheck()) {
644 // If we need to perform an access check we cannot remove the instruction.
645 return;
646 }
647
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100648 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100649 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100650 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100651 instruction->ClearMustDoNullCheck();
652 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100653
654 HGraph* graph = GetGraph();
655 if (object->IsNullConstant()) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700656 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100657 instruction->ReplaceWith(graph->GetIntConstant(0));
658 instruction->GetBlock()->RemoveInstruction(instruction);
659 RecordSimplification();
660 return;
661 }
662
Vladimir Marko24bd8952016-03-15 10:40:33 +0000663 // Note: The `outcome` is initialized to please valgrind - the compiler can reorder
664 // the return value check with the `outcome` check, b/27651442 .
665 bool outcome = false;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700666 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Igor Murashkin1e065a52017-08-09 13:20:34 -0700667 MaybeRecordStat(stats_, kRemovedInstanceOf);
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100668 if (outcome && can_be_null) {
669 // Type test will succeed, we just need a null test.
670 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
671 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
672 instruction->ReplaceWith(test);
673 } else {
674 // We've statically determined the result of the instanceof.
675 instruction->ReplaceWith(graph->GetIntConstant(outcome));
676 }
677 RecordSimplification();
678 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700679 if (outcome && !load_class->HasUses()) {
680 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
681 // However, here we know that it cannot because the instanceof check was successfull, hence
682 // the class was already loaded.
683 load_class->GetBlock()->RemoveInstruction(load_class);
684 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100685 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100686}
687
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100688void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100689 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100690 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100691 instruction->ClearValueCanBeNull();
692 }
693}
694
695void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100696 if ((instruction->GetValue()->GetType() == DataType::Type::kReference)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100697 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100698 instruction->ClearValueCanBeNull();
699 }
700}
701
Anton Shaminbdd79352016-02-15 12:48:36 +0600702static HCondition* GetOppositeConditionSwapOps(ArenaAllocator* arena, HInstruction* cond) {
703 HInstruction *lhs = cond->InputAt(0);
704 HInstruction *rhs = cond->InputAt(1);
705 switch (cond->GetKind()) {
706 case HInstruction::kEqual:
707 return new (arena) HEqual(rhs, lhs);
708 case HInstruction::kNotEqual:
709 return new (arena) HNotEqual(rhs, lhs);
710 case HInstruction::kLessThan:
711 return new (arena) HGreaterThan(rhs, lhs);
712 case HInstruction::kLessThanOrEqual:
713 return new (arena) HGreaterThanOrEqual(rhs, lhs);
714 case HInstruction::kGreaterThan:
715 return new (arena) HLessThan(rhs, lhs);
716 case HInstruction::kGreaterThanOrEqual:
717 return new (arena) HLessThanOrEqual(rhs, lhs);
718 case HInstruction::kBelow:
719 return new (arena) HAbove(rhs, lhs);
720 case HInstruction::kBelowOrEqual:
721 return new (arena) HAboveOrEqual(rhs, lhs);
722 case HInstruction::kAbove:
723 return new (arena) HBelow(rhs, lhs);
724 case HInstruction::kAboveOrEqual:
725 return new (arena) HBelowOrEqual(rhs, lhs);
726 default:
727 LOG(FATAL) << "Unknown ConditionType " << cond->GetKind();
728 }
729 return nullptr;
730}
731
Aart Bik2767f4b2016-10-28 15:03:53 -0700732static bool CmpHasBoolType(HInstruction* input, HInstruction* cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100733 if (input->GetType() == DataType::Type::kBool) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700734 return true; // input has direct boolean type
735 } else if (cmp->GetUses().HasExactlyOneElement()) {
736 // Comparison also has boolean type if both its input and the instruction
737 // itself feed into the same phi node.
738 HInstruction* user = cmp->GetUses().front().GetUser();
739 return user->IsPhi() && user->HasInput(input) && user->HasInput(cmp);
740 }
741 return false;
742}
743
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000744void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100745 HInstruction* input_const = equal->GetConstantRight();
746 if (input_const != nullptr) {
747 HInstruction* input_value = equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700748 if (CmpHasBoolType(input_value, equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100749 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100750 // We are comparing the boolean to a constant which is of type int and can
751 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000752 if (input_const->AsIntConstant()->IsTrue()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100753 // Replace (bool_value == true) with bool_value
754 equal->ReplaceWith(input_value);
755 block->RemoveInstruction(equal);
756 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000757 } else if (input_const->AsIntConstant()->IsFalse()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700758 // Replace (bool_value == false) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500759 equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, equal));
760 block->RemoveInstruction(equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100761 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100762 } else {
763 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
764 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
765 block->RemoveInstruction(equal);
766 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100767 }
Mark Mendellc4701932015-04-10 13:18:51 -0400768 } else {
769 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100770 }
Mark Mendellc4701932015-04-10 13:18:51 -0400771 } else {
772 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100773 }
774}
775
David Brazdil0d13fee2015-04-17 14:52:19 +0100776void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
777 HInstruction* input_const = not_equal->GetConstantRight();
778 if (input_const != nullptr) {
779 HInstruction* input_value = not_equal->GetLeastConstantLeft();
Aart Bik2767f4b2016-10-28 15:03:53 -0700780 if (CmpHasBoolType(input_value, not_equal) && input_const->IsIntConstant()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100781 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100782 // We are comparing the boolean to a constant which is of type int and can
783 // be any constant.
Roland Levillain1a653882016-03-18 18:05:57 +0000784 if (input_const->AsIntConstant()->IsTrue()) {
Aart Bik2767f4b2016-10-28 15:03:53 -0700785 // Replace (bool_value != true) with !bool_value
Mark Mendellf6529172015-11-17 11:16:56 -0500786 not_equal->ReplaceWith(GetGraph()->InsertOppositeCondition(input_value, not_equal));
787 block->RemoveInstruction(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100788 RecordSimplification();
Roland Levillain1a653882016-03-18 18:05:57 +0000789 } else if (input_const->AsIntConstant()->IsFalse()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100790 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100791 not_equal->ReplaceWith(input_value);
792 block->RemoveInstruction(not_equal);
793 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100794 } else {
795 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
796 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
797 block->RemoveInstruction(not_equal);
798 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100799 }
Mark Mendellc4701932015-04-10 13:18:51 -0400800 } else {
801 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100802 }
Mark Mendellc4701932015-04-10 13:18:51 -0400803 } else {
804 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100805 }
806}
807
808void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000809 HInstruction* input = bool_not->InputAt(0);
810 HInstruction* replace_with = nullptr;
811
812 if (input->IsIntConstant()) {
813 // Replace !(true/false) with false/true.
Roland Levillain1a653882016-03-18 18:05:57 +0000814 if (input->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000815 replace_with = GetGraph()->GetIntConstant(0);
816 } else {
Roland Levillain1a653882016-03-18 18:05:57 +0000817 DCHECK(input->AsIntConstant()->IsFalse()) << input->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000818 replace_with = GetGraph()->GetIntConstant(1);
819 }
820 } else if (input->IsBooleanNot()) {
821 // Replace (!(!bool_value)) with bool_value.
822 replace_with = input->InputAt(0);
823 } else if (input->IsCondition() &&
824 // Don't change FP compares. The definition of compares involving
825 // NaNs forces the compares to be done as written by the user.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100826 !DataType::IsFloatingPointType(input->InputAt(0)->GetType())) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000827 // Replace condition with its opposite.
828 replace_with = GetGraph()->InsertOppositeCondition(input->AsCondition(), bool_not);
829 }
830
831 if (replace_with != nullptr) {
832 bool_not->ReplaceWith(replace_with);
David Brazdil0d13fee2015-04-17 14:52:19 +0100833 bool_not->GetBlock()->RemoveInstruction(bool_not);
David Brazdil74eb1b22015-12-14 11:44:01 +0000834 RecordSimplification();
835 }
836}
837
Aart Bik4f7dd342017-09-12 13:12:57 -0700838// Constructs a new ABS(x) node in the HIR.
839static HInstruction* NewIntegralAbs(ArenaAllocator* arena, HInstruction* x, HInstruction* cursor) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100840 DataType::Type type = x->GetType();
841 DCHECK(type == DataType::Type::kInt32 || type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700842 // Construct a fake intrinsic with as much context as is needed to allocate one.
843 // The intrinsic will always be lowered into code later anyway.
844 // TODO: b/65164101 : moving towards a real HAbs node makes more sense.
845 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
846 HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress,
847 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
848 0u
849 };
850 HInvokeStaticOrDirect* invoke = new (arena) HInvokeStaticOrDirect(
851 arena,
852 1,
853 type,
854 x->GetDexPc(),
855 /*method_idx*/ -1,
856 /*resolved_method*/ nullptr,
857 dispatch_info,
858 kStatic,
859 MethodReference(nullptr, dex::kDexNoIndex),
860 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
861 invoke->SetArgumentAt(0, x);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100862 invoke->SetIntrinsic(type == DataType::Type::kInt32 ? Intrinsics::kMathAbsInt
863 : Intrinsics::kMathAbsLong,
Aart Bik4f7dd342017-09-12 13:12:57 -0700864 kNoEnvironmentOrCache,
865 kNoSideEffects,
866 kNoThrow);
867 cursor->GetBlock()->InsertInstructionBefore(invoke, cursor);
868 return invoke;
869}
870
871// Returns true if operands a and b consists of widening type conversions
872// (either explicit or implicit) to the given to_type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100873static bool AreLowerPrecisionArgs(DataType::Type to_type, HInstruction* a, HInstruction* b) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700874 if (a->IsTypeConversion() && a->GetType() == to_type) {
875 a = a->InputAt(0);
876 }
877 if (b->IsTypeConversion() && b->GetType() == to_type) {
878 b = b->InputAt(0);
879 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100880 DataType::Type type1 = a->GetType();
881 DataType::Type type2 = b->GetType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100882 return (type1 == DataType::Type::kUint8 && type2 == DataType::Type::kUint8) ||
883 (type1 == DataType::Type::kInt8 && type2 == DataType::Type::kInt8) ||
884 (type1 == DataType::Type::kInt16 && type2 == DataType::Type::kInt16) ||
885 (type1 == DataType::Type::kUint16 && type2 == DataType::Type::kUint16) ||
886 (type1 == DataType::Type::kInt32 && type2 == DataType::Type::kInt32 &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100887 to_type == DataType::Type::kInt64);
Aart Bik4f7dd342017-09-12 13:12:57 -0700888}
889
David Brazdil74eb1b22015-12-14 11:44:01 +0000890void InstructionSimplifierVisitor::VisitSelect(HSelect* select) {
891 HInstruction* replace_with = nullptr;
892 HInstruction* condition = select->GetCondition();
893 HInstruction* true_value = select->GetTrueValue();
894 HInstruction* false_value = select->GetFalseValue();
895
896 if (condition->IsBooleanNot()) {
897 // Change ((!cond) ? x : y) to (cond ? y : x).
898 condition = condition->InputAt(0);
899 std::swap(true_value, false_value);
900 select->ReplaceInput(false_value, 0);
901 select->ReplaceInput(true_value, 1);
902 select->ReplaceInput(condition, 2);
903 RecordSimplification();
904 }
905
906 if (true_value == false_value) {
907 // Replace (cond ? x : x) with (x).
908 replace_with = true_value;
909 } else if (condition->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000910 if (condition->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000911 // Replace (true ? x : y) with (x).
912 replace_with = true_value;
913 } else {
914 // Replace (false ? x : y) with (y).
Roland Levillain1a653882016-03-18 18:05:57 +0000915 DCHECK(condition->AsIntConstant()->IsFalse()) << condition->AsIntConstant()->GetValue();
David Brazdil74eb1b22015-12-14 11:44:01 +0000916 replace_with = false_value;
917 }
918 } else if (true_value->IsIntConstant() && false_value->IsIntConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +0000919 if (true_value->AsIntConstant()->IsTrue() && false_value->AsIntConstant()->IsFalse()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000920 // Replace (cond ? true : false) with (cond).
921 replace_with = condition;
Roland Levillain1a653882016-03-18 18:05:57 +0000922 } else if (true_value->AsIntConstant()->IsFalse() && false_value->AsIntConstant()->IsTrue()) {
David Brazdil74eb1b22015-12-14 11:44:01 +0000923 // Replace (cond ? false : true) with (!cond).
924 replace_with = GetGraph()->InsertOppositeCondition(condition, select);
925 }
Aart Bik4f7dd342017-09-12 13:12:57 -0700926 } else if (condition->IsCondition()) {
927 IfCondition cmp = condition->AsCondition()->GetCondition();
928 HInstruction* a = condition->InputAt(0);
929 HInstruction* b = condition->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100930 DataType::Type t_type = true_value->GetType();
931 DataType::Type f_type = false_value->GetType();
Aart Bik4f7dd342017-09-12 13:12:57 -0700932 // Here we have a <cmp> b ? true_value : false_value.
933 // Test if both values are same-typed int or long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100934 if (t_type == f_type &&
935 (t_type == DataType::Type::kInt32 || t_type == DataType::Type::kInt64)) {
Aart Bik4f7dd342017-09-12 13:12:57 -0700936 // Try to replace typical integral ABS constructs.
937 if (true_value->IsNeg()) {
938 HInstruction* negated = true_value->InputAt(0);
939 if ((cmp == kCondLT || cmp == kCondLE) &&
940 (a == negated && a == false_value && IsInt64Value(b, 0))) {
941 // Found a < 0 ? -a : a which can be replaced by ABS(a).
942 replace_with = NewIntegralAbs(GetGraph()->GetArena(), false_value, select);
943 }
944 } else if (false_value->IsNeg()) {
945 HInstruction* negated = false_value->InputAt(0);
946 if ((cmp == kCondGT || cmp == kCondGE) &&
947 (a == true_value && a == negated && IsInt64Value(b, 0))) {
948 // Found a > 0 ? a : -a which can be replaced by ABS(a).
949 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
950 }
951 } else if (true_value->IsSub() && false_value->IsSub()) {
952 HInstruction* true_sub1 = true_value->InputAt(0);
953 HInstruction* true_sub2 = true_value->InputAt(1);
954 HInstruction* false_sub1 = false_value->InputAt(0);
955 HInstruction* false_sub2 = false_value->InputAt(1);
956 if ((((cmp == kCondGT || cmp == kCondGE) &&
957 (a == true_sub1 && b == true_sub2 && a == false_sub2 && b == false_sub1)) ||
958 ((cmp == kCondLT || cmp == kCondLE) &&
959 (a == true_sub2 && b == true_sub1 && a == false_sub1 && b == false_sub2))) &&
960 AreLowerPrecisionArgs(t_type, a, b)) {
961 // Found a > b ? a - b : b - a or
962 // a < b ? b - a : a - b
963 // which can be replaced by ABS(a - b) for lower precision operands a, b.
964 replace_with = NewIntegralAbs(GetGraph()->GetArena(), true_value, select);
965 }
966 }
967 }
David Brazdil74eb1b22015-12-14 11:44:01 +0000968 }
969
970 if (replace_with != nullptr) {
971 select->ReplaceWith(replace_with);
972 select->GetBlock()->RemoveInstruction(select);
973 RecordSimplification();
974 }
975}
976
977void InstructionSimplifierVisitor::VisitIf(HIf* instruction) {
978 HInstruction* condition = instruction->InputAt(0);
979 if (condition->IsBooleanNot()) {
980 // Swap successors if input is negated.
981 instruction->ReplaceInput(condition->InputAt(0), 0);
982 instruction->GetBlock()->SwapSuccessors();
David Brazdil0d13fee2015-04-17 14:52:19 +0100983 RecordSimplification();
984 }
985}
986
Mingyao Yang0304e182015-01-30 16:41:29 -0800987void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
988 HInstruction* input = instruction->InputAt(0);
989 // If the array is a NewArray with constant size, replace the array length
990 // with the constant instruction. This helps the bounds check elimination phase.
991 if (input->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +0000992 input = input->AsNewArray()->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -0800993 if (input->IsIntConstant()) {
994 instruction->ReplaceWith(input);
995 }
996 }
997}
998
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000999void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001000 HInstruction* value = instruction->GetValue();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001001 if (value->GetType() != DataType::Type::kReference) {
1002 return;
1003 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001004
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001005 if (CanEnsureNotNullAt(value, instruction)) {
1006 instruction->ClearValueCanBeNull();
1007 }
1008
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001009 if (value->IsArrayGet()) {
1010 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
1011 // If the code is just swapping elements in the array, no need for a type check.
1012 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001013 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001014 }
1015 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001016
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001017 if (value->IsNullConstant()) {
1018 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001019 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +01001020 }
1021
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +01001022 ScopedObjectAccess soa(Thread::Current());
1023 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
1024 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
1025 if (!array_rti.IsValid()) {
1026 return;
1027 }
1028
1029 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
1030 instruction->ClearNeedsTypeCheck();
1031 return;
1032 }
1033
1034 if (array_rti.IsObjectArray()) {
1035 if (array_rti.IsExact()) {
1036 instruction->ClearNeedsTypeCheck();
1037 return;
1038 }
1039 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +01001040 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +00001041}
1042
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001043static bool IsTypeConversionLossless(DataType::Type input_type, DataType::Type result_type) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001044 // The conversion to a larger type is loss-less with the exception of two cases,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001045 // - conversion to the unsigned type Uint16, where we may lose some bits, and
Vladimir Markob52bbde2016-02-12 12:06:05 +00001046 // - conversion from float to long, the only FP to integral conversion with smaller FP type.
1047 // For integral to FP conversions this holds because the FP mantissa is large enough.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001048 // Note: The size check excludes Uint8 as the result type.
1049 DCHECK(!DataType::IsTypeConversionImplicit(input_type, result_type));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001050 return DataType::Size(result_type) > DataType::Size(input_type) &&
1051 result_type != DataType::Type::kUint16 &&
1052 !(result_type == DataType::Type::kInt64 && input_type == DataType::Type::kFloat32);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001053}
1054
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001055void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001056 HInstruction* input = instruction->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001057 DataType::Type input_type = input->GetType();
1058 DataType::Type result_type = instruction->GetResultType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001059 if (DataType::IsTypeConversionImplicit(input_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001060 // Remove the implicit conversion; this includes conversion to the same type.
1061 instruction->ReplaceWith(input);
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001062 instruction->GetBlock()->RemoveInstruction(instruction);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001063 RecordSimplification();
1064 return;
1065 }
1066
1067 if (input->IsTypeConversion()) {
1068 HTypeConversion* input_conversion = input->AsTypeConversion();
1069 HInstruction* original_input = input_conversion->GetInput();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001070 DataType::Type original_type = original_input->GetType();
Vladimir Markob52bbde2016-02-12 12:06:05 +00001071
1072 // When the first conversion is lossless, a direct conversion from the original type
1073 // to the final type yields the same result, even for a lossy second conversion, for
1074 // example float->double->int or int->double->float.
1075 bool is_first_conversion_lossless = IsTypeConversionLossless(original_type, input_type);
1076
1077 // For integral conversions, see if the first conversion loses only bits that the second
1078 // doesn't need, i.e. the final type is no wider than the intermediate. If so, direct
1079 // conversion yields the same result, for example long->int->short or int->char->short.
1080 bool integral_conversions_with_non_widening_second =
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001081 DataType::IsIntegralType(input_type) &&
1082 DataType::IsIntegralType(original_type) &&
1083 DataType::IsIntegralType(result_type) &&
1084 DataType::Size(result_type) <= DataType::Size(input_type);
Vladimir Markob52bbde2016-02-12 12:06:05 +00001085
1086 if (is_first_conversion_lossless || integral_conversions_with_non_widening_second) {
1087 // If the merged conversion is implicit, do the simplification unconditionally.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001088 if (DataType::IsTypeConversionImplicit(original_type, result_type)) {
Vladimir Markob52bbde2016-02-12 12:06:05 +00001089 instruction->ReplaceWith(original_input);
1090 instruction->GetBlock()->RemoveInstruction(instruction);
1091 if (!input_conversion->HasUses()) {
1092 // Don't wait for DCE.
1093 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1094 }
1095 RecordSimplification();
1096 return;
1097 }
1098 // Otherwise simplify only if the first conversion has no other use.
1099 if (input_conversion->HasOnlyOneNonEnvironmentUse()) {
1100 input_conversion->ReplaceWith(original_input);
1101 input_conversion->GetBlock()->RemoveInstruction(input_conversion);
1102 RecordSimplification();
1103 return;
1104 }
1105 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001106 } else if (input->IsAnd() && DataType::IsIntegralType(result_type)) {
1107 DCHECK(DataType::IsIntegralType(input_type));
Vladimir Marko8428bd32016-02-12 16:53:57 +00001108 HAnd* input_and = input->AsAnd();
1109 HConstant* constant = input_and->GetConstantRight();
1110 if (constant != nullptr) {
1111 int64_t value = Int64FromConstant(constant);
1112 DCHECK_NE(value, -1); // "& -1" would have been optimized away in VisitAnd().
1113 size_t trailing_ones = CTZ(~static_cast<uint64_t>(value));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001114 if (trailing_ones >= kBitsPerByte * DataType::Size(result_type)) {
Vladimir Marko8428bd32016-02-12 16:53:57 +00001115 // The `HAnd` is useless, for example in `(byte) (x & 0xff)`, get rid of it.
Vladimir Marko625090f2016-03-14 18:00:05 +00001116 HInstruction* original_input = input_and->GetLeastConstantLeft();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001117 if (DataType::IsTypeConversionImplicit(original_input->GetType(), result_type)) {
Vladimir Marko625090f2016-03-14 18:00:05 +00001118 instruction->ReplaceWith(original_input);
1119 instruction->GetBlock()->RemoveInstruction(instruction);
1120 RecordSimplification();
1121 return;
1122 } else if (input->HasOnlyOneNonEnvironmentUse()) {
1123 input_and->ReplaceWith(original_input);
1124 input_and->GetBlock()->RemoveInstruction(input_and);
1125 RecordSimplification();
1126 return;
1127 }
Vladimir Marko8428bd32016-02-12 16:53:57 +00001128 }
1129 }
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +00001130 }
1131}
1132
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001133void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
1134 HConstant* input_cst = instruction->GetConstantRight();
1135 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001136 bool integral_type = DataType::IsIntegralType(instruction->GetType());
Roland Levillain1a653882016-03-18 18:05:57 +00001137 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001138 // Replace code looking like
1139 // ADD dst, src, 0
1140 // with
1141 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001142 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
1143 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1144 // yields `-0.0`.
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001145 if (integral_type) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001146 instruction->ReplaceWith(input_other);
1147 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001148 RecordSimplification();
Serguei Katkov115b53f2015-08-05 17:03:30 +06001149 return;
1150 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001151 }
1152
1153 HInstruction* left = instruction->GetLeft();
1154 HInstruction* right = instruction->GetRight();
1155 bool left_is_neg = left->IsNeg();
1156 bool right_is_neg = right->IsNeg();
1157
1158 if (left_is_neg && right_is_neg) {
1159 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1160 return;
1161 }
1162 }
1163
1164 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
1165 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
1166 // Replace code looking like
1167 // NEG tmp, b
1168 // ADD dst, a, tmp
1169 // with
1170 // SUB dst, a, b
1171 // We do not perform the optimization if the input negation has environment
1172 // uses or multiple non-environment uses as it could lead to worse code. In
1173 // particular, we do not want the live range of `b` to be extended if we are
1174 // not sure the initial 'NEG' instruction can be removed.
1175 HInstruction* other = left_is_neg ? right : left;
1176 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
1177 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
1178 RecordSimplification();
1179 neg->GetBlock()->RemoveInstruction(neg);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001180 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001181 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001182
Anton Kirilove14dc862016-05-13 17:56:15 +01001183 if (TryReplaceWithRotate(instruction)) {
1184 return;
1185 }
1186
1187 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1188 // so no need to return.
1189 TryHandleAssociativeAndCommutativeOperation(instruction);
1190
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001191 if ((left->IsSub() || right->IsSub()) &&
Anton Kirilove14dc862016-05-13 17:56:15 +01001192 TrySubtractionChainSimplification(instruction)) {
1193 return;
1194 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001195
1196 if (integral_type) {
1197 // Replace code patterns looking like
1198 // SUB dst1, x, y SUB dst1, x, y
1199 // ADD dst2, dst1, y ADD dst2, y, dst1
1200 // with
1201 // SUB dst1, x, y
1202 // ADD instruction is not needed in this case, we may use
1203 // one of inputs of SUB instead.
1204 if (left->IsSub() && left->InputAt(1) == right) {
1205 instruction->ReplaceWith(left->InputAt(0));
1206 RecordSimplification();
1207 instruction->GetBlock()->RemoveInstruction(instruction);
1208 return;
1209 } else if (right->IsSub() && right->InputAt(1) == left) {
1210 instruction->ReplaceWith(right->InputAt(0));
1211 RecordSimplification();
1212 instruction->GetBlock()->RemoveInstruction(instruction);
1213 return;
1214 }
1215 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001216}
1217
1218void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
1219 HConstant* input_cst = instruction->GetConstantRight();
1220 HInstruction* input_other = instruction->GetLeastConstantLeft();
1221
Vladimir Marko452c1b62015-09-25 14:44:17 +01001222 if (input_cst != nullptr) {
1223 int64_t value = Int64FromConstant(input_cst);
1224 if (value == -1) {
1225 // Replace code looking like
1226 // AND dst, src, 0xFFF...FF
1227 // with
1228 // src
1229 instruction->ReplaceWith(input_other);
1230 instruction->GetBlock()->RemoveInstruction(instruction);
1231 RecordSimplification();
1232 return;
1233 }
Vladimir Markoc8fb2112017-10-03 11:37:52 +01001234 if (input_other->IsTypeConversion() &&
1235 input_other->GetType() == DataType::Type::kInt64 &&
1236 DataType::IsIntegralType(input_other->InputAt(0)->GetType()) &&
1237 IsInt<32>(value) &&
1238 input_other->HasOnlyOneNonEnvironmentUse()) {
1239 // The AND can be reordered before the TypeConversion. Replace
1240 // LongConstant cst, <32-bit-constant-sign-extended-to-64-bits>
1241 // TypeConversion<Int64> tmp, src
1242 // AND dst, tmp, cst
1243 // with
1244 // IntConstant cst, <32-bit-constant>
1245 // AND tmp, src, cst
1246 // TypeConversion<Int64> dst, tmp
1247 // This helps 32-bit targets and does not hurt 64-bit targets.
1248 // This also simplifies detection of other patterns, such as Uint8 loads.
1249 HInstruction* new_and_input = input_other->InputAt(0);
1250 // Implicit conversion Int64->Int64 would have been removed previously.
1251 DCHECK_NE(new_and_input->GetType(), DataType::Type::kInt64);
1252 HConstant* new_const = GetGraph()->GetConstant(DataType::Type::kInt32, value);
1253 HAnd* new_and =
1254 new (GetGraph()->GetArena()) HAnd(DataType::Type::kInt32, new_and_input, new_const);
1255 instruction->GetBlock()->InsertInstructionBefore(new_and, instruction);
1256 HTypeConversion* new_conversion =
1257 new (GetGraph()->GetArena()) HTypeConversion(DataType::Type::kInt64, new_and);
1258 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_conversion);
1259 input_other->GetBlock()->RemoveInstruction(input_other);
1260 RecordSimplification();
1261 // Try to process the new And now, do not wait for the next round of simplifications.
1262 instruction = new_and;
1263 input_other = new_and_input;
1264 }
Vladimir Marko452c1b62015-09-25 14:44:17 +01001265 // Eliminate And from UShr+And if the And-mask contains all the bits that
1266 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
1267 // precisely clears the shifted-in sign bits.
1268 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001269 size_t reg_bits = (instruction->GetResultType() == DataType::Type::kInt64) ? 64 : 32;
Vladimir Marko452c1b62015-09-25 14:44:17 +01001270 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
1271 size_t num_tail_bits_set = CTZ(value + 1);
1272 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
1273 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
1274 instruction->ReplaceWith(input_other);
1275 instruction->GetBlock()->RemoveInstruction(instruction);
1276 RecordSimplification();
1277 return;
1278 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
1279 input_other->HasOnlyOneNonEnvironmentUse()) {
1280 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
1281 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
1282 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
1283 input_other->InputAt(0),
1284 input_other->InputAt(1),
1285 input_other->GetDexPc());
1286 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
1287 input_other->GetBlock()->RemoveInstruction(input_other);
1288 RecordSimplification();
1289 return;
1290 }
1291 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001292 }
1293
1294 // We assume that GVN has run before, so we only perform a pointer comparison.
1295 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001296 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001297 if (instruction->GetLeft() == instruction->GetRight()) {
1298 // Replace code looking like
1299 // AND dst, src, src
1300 // with
1301 // src
1302 instruction->ReplaceWith(instruction->GetLeft());
1303 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001304 RecordSimplification();
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001305 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001306 }
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001307
Anton Kirilove14dc862016-05-13 17:56:15 +01001308 if (TryDeMorganNegationFactoring(instruction)) {
1309 return;
1310 }
1311
1312 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1313 // so no need to return.
1314 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001315}
1316
Mark Mendellc4701932015-04-10 13:18:51 -04001317void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
1318 VisitCondition(condition);
1319}
1320
1321void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
1322 VisitCondition(condition);
1323}
1324
1325void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
1326 VisitCondition(condition);
1327}
1328
1329void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
1330 VisitCondition(condition);
1331}
1332
Anton Shaminbdd79352016-02-15 12:48:36 +06001333void InstructionSimplifierVisitor::VisitBelow(HBelow* condition) {
1334 VisitCondition(condition);
1335}
1336
1337void InstructionSimplifierVisitor::VisitBelowOrEqual(HBelowOrEqual* condition) {
1338 VisitCondition(condition);
1339}
1340
1341void InstructionSimplifierVisitor::VisitAbove(HAbove* condition) {
1342 VisitCondition(condition);
1343}
1344
1345void InstructionSimplifierVisitor::VisitAboveOrEqual(HAboveOrEqual* condition) {
1346 VisitCondition(condition);
1347}
Aart Bike9f37602015-10-09 11:15:55 -07001348
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001349// Recognize the following pattern:
1350// obj.getClass() ==/!= Foo.class
1351// And replace it with a constant value if the type of `obj` is statically known.
1352static bool RecognizeAndSimplifyClassCheck(HCondition* condition) {
1353 HInstruction* input_one = condition->InputAt(0);
1354 HInstruction* input_two = condition->InputAt(1);
1355 HLoadClass* load_class = input_one->IsLoadClass()
1356 ? input_one->AsLoadClass()
1357 : input_two->AsLoadClass();
1358 if (load_class == nullptr) {
1359 return false;
1360 }
1361
1362 ReferenceTypeInfo class_rti = load_class->GetLoadedClassRTI();
1363 if (!class_rti.IsValid()) {
1364 // Unresolved class.
1365 return false;
1366 }
1367
1368 HInstanceFieldGet* field_get = (load_class == input_one)
1369 ? input_two->AsInstanceFieldGet()
1370 : input_one->AsInstanceFieldGet();
1371 if (field_get == nullptr) {
1372 return false;
1373 }
1374
1375 HInstruction* receiver = field_get->InputAt(0);
1376 ReferenceTypeInfo receiver_type = receiver->GetReferenceTypeInfo();
1377 if (!receiver_type.IsExact()) {
1378 return false;
1379 }
1380
1381 {
1382 ScopedObjectAccess soa(Thread::Current());
1383 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1384 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
1385 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
1386 if (field_get->GetFieldInfo().GetField() != field) {
1387 return false;
1388 }
1389
1390 // We can replace the compare.
1391 int value = 0;
1392 if (receiver_type.IsEqual(class_rti)) {
1393 value = condition->IsEqual() ? 1 : 0;
1394 } else {
1395 value = condition->IsNotEqual() ? 1 : 0;
1396 }
1397 condition->ReplaceWith(condition->GetBlock()->GetGraph()->GetIntConstant(value));
1398 return true;
1399 }
1400}
1401
Mark Mendellc4701932015-04-10 13:18:51 -04001402void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001403 if (condition->IsEqual() || condition->IsNotEqual()) {
1404 if (RecognizeAndSimplifyClassCheck(condition)) {
1405 return;
1406 }
1407 }
1408
Anton Shaminbdd79352016-02-15 12:48:36 +06001409 // Reverse condition if left is constant. Our code generators prefer constant
1410 // on the right hand side.
1411 if (condition->GetLeft()->IsConstant() && !condition->GetRight()->IsConstant()) {
1412 HBasicBlock* block = condition->GetBlock();
1413 HCondition* replacement = GetOppositeConditionSwapOps(block->GetGraph()->GetArena(), condition);
1414 // If it is a fp we must set the opposite bias.
1415 if (replacement != nullptr) {
1416 if (condition->IsLtBias()) {
1417 replacement->SetBias(ComparisonBias::kGtBias);
1418 } else if (condition->IsGtBias()) {
1419 replacement->SetBias(ComparisonBias::kLtBias);
1420 }
1421 block->ReplaceAndRemoveInstructionWith(condition, replacement);
1422 RecordSimplification();
1423
1424 condition = replacement;
1425 }
1426 }
Mark Mendellc4701932015-04-10 13:18:51 -04001427
Mark Mendellc4701932015-04-10 13:18:51 -04001428 HInstruction* left = condition->GetLeft();
1429 HInstruction* right = condition->GetRight();
Anton Shaminbdd79352016-02-15 12:48:36 +06001430
1431 // Try to fold an HCompare into this HCondition.
1432
Mark Mendellc4701932015-04-10 13:18:51 -04001433 // We can only replace an HCondition which compares a Compare to 0.
1434 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
1435 // condition with a long, float or double comparison as input.
1436 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
1437 // Conversion is not possible.
1438 return;
1439 }
1440
1441 // Is the Compare only used for this purpose?
Vladimir Marko46817b82016-03-29 12:21:58 +01001442 if (!left->GetUses().HasExactlyOneElement()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001443 // Someone else also wants the result of the compare.
1444 return;
1445 }
1446
Vladimir Marko46817b82016-03-29 12:21:58 +01001447 if (!left->GetEnvUses().empty()) {
Mark Mendellc4701932015-04-10 13:18:51 -04001448 // There is a reference to the compare result in an environment. Do we really need it?
1449 if (GetGraph()->IsDebuggable()) {
1450 return;
1451 }
1452
1453 // We have to ensure that there are no deopt points in the sequence.
1454 if (left->HasAnyEnvironmentUseBefore(condition)) {
1455 return;
1456 }
1457 }
1458
1459 // Clean up any environment uses from the HCompare, if any.
1460 left->RemoveEnvironmentUsers();
1461
1462 // We have decided to fold the HCompare into the HCondition. Transfer the information.
1463 condition->SetBias(left->AsCompare()->GetBias());
1464
1465 // Replace the operands of the HCondition.
1466 condition->ReplaceInput(left->InputAt(0), 0);
1467 condition->ReplaceInput(left->InputAt(1), 1);
1468
1469 // Remove the HCompare.
1470 left->GetBlock()->RemoveInstruction(left);
1471
1472 RecordSimplification();
1473}
1474
Andreas Gampe9186ced2016-12-12 14:28:21 -08001475// Return whether x / divisor == x * (1.0f / divisor), for every float x.
1476static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
1477 // True, if the most significant bits of divisor are 0.
1478 return ((divisor & 0x7fffff) == 0);
1479}
1480
1481// Return whether x / divisor == x * (1.0 / divisor), for every double x.
1482static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
1483 // True, if the most significant bits of divisor are 0.
1484 return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
1485}
1486
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001487void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
1488 HConstant* input_cst = instruction->GetConstantRight();
1489 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001490 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001491
1492 if ((input_cst != nullptr) && input_cst->IsOne()) {
1493 // Replace code looking like
1494 // DIV dst, src, 1
1495 // with
1496 // src
1497 instruction->ReplaceWith(input_other);
1498 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001499 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001500 return;
1501 }
1502
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001503 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001504 // Replace code looking like
1505 // DIV dst, src, -1
1506 // with
1507 // NEG dst, src
1508 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001509 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001510 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001511 return;
1512 }
1513
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 if ((input_cst != nullptr) && DataType::IsFloatingPointType(type)) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001515 // Try replacing code looking like
1516 // DIV dst, src, constant
1517 // with
1518 // MUL dst, src, 1 / constant
1519 HConstant* reciprocal = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001520 if (type == DataType::Type::kFloat64) {
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001521 double value = input_cst->AsDoubleConstant()->GetValue();
1522 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
1523 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
1524 }
1525 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001526 DCHECK_EQ(type, DataType::Type::kFloat32);
Nicolas Geoffray0d221842015-04-27 08:53:46 +00001527 float value = input_cst->AsFloatConstant()->GetValue();
1528 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
1529 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
1530 }
1531 }
1532
1533 if (reciprocal != nullptr) {
1534 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
1535 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
1536 RecordSimplification();
1537 return;
1538 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001539 }
1540}
1541
1542void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
1543 HConstant* input_cst = instruction->GetConstantRight();
1544 HInstruction* input_other = instruction->GetLeastConstantLeft();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001545 DataType::Type type = instruction->GetType();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001546 HBasicBlock* block = instruction->GetBlock();
1547 ArenaAllocator* allocator = GetGraph()->GetArena();
1548
1549 if (input_cst == nullptr) {
1550 return;
1551 }
1552
1553 if (input_cst->IsOne()) {
1554 // Replace code looking like
1555 // MUL dst, src, 1
1556 // with
1557 // src
1558 instruction->ReplaceWith(input_other);
1559 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001560 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001561 return;
1562 }
1563
1564 if (input_cst->IsMinusOne() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001565 (DataType::IsFloatingPointType(type) || DataType::IsIntOrLongType(type))) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001566 // Replace code looking like
1567 // MUL dst, src, -1
1568 // with
1569 // NEG dst, src
1570 HNeg* neg = new (allocator) HNeg(type, input_other);
1571 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001572 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001573 return;
1574 }
1575
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001576 if (DataType::IsFloatingPointType(type) &&
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001577 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
1578 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
1579 // Replace code looking like
1580 // FP_MUL dst, src, 2.0
1581 // with
1582 // FP_ADD dst, src, src
1583 // The 'int' and 'long' cases are handled below.
1584 block->ReplaceAndRemoveInstructionWith(instruction,
1585 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +01001586 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001587 return;
1588 }
1589
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 if (DataType::IsIntOrLongType(type)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001591 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +06001592 // Even though constant propagation also takes care of the zero case, other
1593 // optimizations can lead to having a zero multiplication.
1594 if (factor == 0) {
1595 // Replace code looking like
1596 // MUL dst, src, 0
1597 // with
1598 // 0
1599 instruction->ReplaceWith(input_cst);
1600 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001601 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001602 return;
Serguei Katkov53849192015-04-20 14:22:27 +06001603 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001604 // Replace code looking like
1605 // MUL dst, src, pow_of_2
1606 // with
1607 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +00001608 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Roland Levillain22c49222016-03-18 14:04:28 +00001609 HShl* shl = new (allocator) HShl(type, input_other, shift);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001610 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +01001611 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001612 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001613 } else if (IsPowerOfTwo(factor - 1)) {
1614 // Transform code looking like
1615 // MUL dst, src, (2^n + 1)
1616 // into
1617 // SHL tmp, src, n
1618 // ADD dst, src, tmp
1619 HShl* shl = new (allocator) HShl(type,
1620 input_other,
1621 GetGraph()->GetIntConstant(WhichPowerOf2(factor - 1)));
1622 HAdd* add = new (allocator) HAdd(type, input_other, shl);
1623
1624 block->InsertInstructionBefore(shl, instruction);
1625 block->ReplaceAndRemoveInstructionWith(instruction, add);
1626 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001627 return;
Alexandre Rames38db7852015-11-20 15:02:45 +00001628 } else if (IsPowerOfTwo(factor + 1)) {
1629 // Transform code looking like
1630 // MUL dst, src, (2^n - 1)
1631 // into
1632 // SHL tmp, src, n
1633 // SUB dst, tmp, src
1634 HShl* shl = new (allocator) HShl(type,
1635 input_other,
1636 GetGraph()->GetIntConstant(WhichPowerOf2(factor + 1)));
1637 HSub* sub = new (allocator) HSub(type, shl, input_other);
1638
1639 block->InsertInstructionBefore(shl, instruction);
1640 block->ReplaceAndRemoveInstructionWith(instruction, sub);
1641 RecordSimplification();
Anton Kirilove14dc862016-05-13 17:56:15 +01001642 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001643 }
1644 }
Anton Kirilove14dc862016-05-13 17:56:15 +01001645
1646 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1647 // so no need to return.
1648 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001649}
1650
Alexandre Rames188d4312015-04-09 18:30:21 +01001651void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
1652 HInstruction* input = instruction->GetInput();
1653 if (input->IsNeg()) {
1654 // Replace code looking like
1655 // NEG tmp, src
1656 // NEG dst, tmp
1657 // with
1658 // src
1659 HNeg* previous_neg = input->AsNeg();
1660 instruction->ReplaceWith(previous_neg->GetInput());
1661 instruction->GetBlock()->RemoveInstruction(instruction);
1662 // We perform the optimization even if the input negation has environment
1663 // uses since it allows removing the current instruction. But we only delete
1664 // the input negation only if it is does not have any uses left.
1665 if (!previous_neg->HasUses()) {
1666 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
1667 }
1668 RecordSimplification();
1669 return;
1670 }
1671
Serguei Katkov339dfc22015-04-20 12:29:32 +06001672 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001673 !DataType::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +01001674 // Replace code looking like
1675 // SUB tmp, a, b
1676 // NEG dst, tmp
1677 // with
1678 // SUB dst, b, a
1679 // We do not perform the optimization if the input subtraction has
1680 // environment uses or multiple non-environment uses as it could lead to
1681 // worse code. In particular, we do not want the live ranges of `a` and `b`
1682 // to be extended if we are not sure the initial 'SUB' instruction can be
1683 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +06001684 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +01001685 HSub* sub = input->AsSub();
1686 HSub* new_sub =
1687 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
1688 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
1689 if (!sub->HasUses()) {
1690 sub->GetBlock()->RemoveInstruction(sub);
1691 }
1692 RecordSimplification();
1693 }
1694}
1695
1696void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
1697 HInstruction* input = instruction->GetInput();
1698 if (input->IsNot()) {
1699 // Replace code looking like
1700 // NOT tmp, src
1701 // NOT dst, tmp
1702 // with
1703 // src
1704 // We perform the optimization even if the input negation has environment
1705 // uses since it allows removing the current instruction. But we only delete
1706 // the input negation only if it is does not have any uses left.
1707 HNot* previous_not = input->AsNot();
1708 instruction->ReplaceWith(previous_not->GetInput());
1709 instruction->GetBlock()->RemoveInstruction(instruction);
1710 if (!previous_not->HasUses()) {
1711 previous_not->GetBlock()->RemoveInstruction(previous_not);
1712 }
1713 RecordSimplification();
1714 }
1715}
1716
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001717void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
1718 HConstant* input_cst = instruction->GetConstantRight();
1719 HInstruction* input_other = instruction->GetLeastConstantLeft();
1720
Roland Levillain1a653882016-03-18 18:05:57 +00001721 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001722 // Replace code looking like
1723 // OR dst, src, 0
1724 // with
1725 // src
1726 instruction->ReplaceWith(input_other);
1727 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001728 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001729 return;
1730 }
1731
1732 // We assume that GVN has run before, so we only perform a pointer comparison.
1733 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +01001734 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001735 if (instruction->GetLeft() == instruction->GetRight()) {
1736 // Replace code looking like
1737 // OR dst, src, src
1738 // with
1739 // src
1740 instruction->ReplaceWith(instruction->GetLeft());
1741 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001742 RecordSimplification();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001743 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001744 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001745
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001746 if (TryDeMorganNegationFactoring(instruction)) return;
1747
Anton Kirilove14dc862016-05-13 17:56:15 +01001748 if (TryReplaceWithRotate(instruction)) {
1749 return;
1750 }
1751
1752 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1753 // so no need to return.
1754 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001755}
1756
1757void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
1758 VisitShift(instruction);
1759}
1760
1761void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
1762 VisitShift(instruction);
1763}
1764
1765void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
1766 HConstant* input_cst = instruction->GetConstantRight();
1767 HInstruction* input_other = instruction->GetLeastConstantLeft();
1768
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001769 DataType::Type type = instruction->GetType();
1770 if (DataType::IsFloatingPointType(type)) {
Serguei Katkov115b53f2015-08-05 17:03:30 +06001771 return;
1772 }
1773
Roland Levillain1a653882016-03-18 18:05:57 +00001774 if ((input_cst != nullptr) && input_cst->IsArithmeticZero()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001775 // Replace code looking like
1776 // SUB dst, src, 0
1777 // with
1778 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +06001779 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
1780 // `x` is `-0.0`, the former expression yields `0.0`, while the later
1781 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001782 instruction->ReplaceWith(input_other);
1783 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001784 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001785 return;
1786 }
1787
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001788 HBasicBlock* block = instruction->GetBlock();
1789 ArenaAllocator* allocator = GetGraph()->GetArena();
1790
Alexandre Rames188d4312015-04-09 18:30:21 +01001791 HInstruction* left = instruction->GetLeft();
1792 HInstruction* right = instruction->GetRight();
1793 if (left->IsConstant()) {
1794 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001795 // Replace code looking like
1796 // SUB dst, 0, src
1797 // with
1798 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +01001799 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001800 // `x` is `0.0`, the former expression yields `0.0`, while the later
1801 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +01001802 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001803 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +01001804 RecordSimplification();
1805 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001806 }
1807 }
Alexandre Rames188d4312015-04-09 18:30:21 +01001808
1809 if (left->IsNeg() && right->IsNeg()) {
1810 if (TryMoveNegOnInputsAfterBinop(instruction)) {
1811 return;
1812 }
1813 }
1814
1815 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
1816 // Replace code looking like
1817 // NEG tmp, b
1818 // SUB dst, a, tmp
1819 // with
1820 // ADD dst, a, b
1821 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
1822 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
1823 RecordSimplification();
1824 right->GetBlock()->RemoveInstruction(right);
1825 return;
1826 }
1827
1828 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
1829 // Replace code looking like
1830 // NEG tmp, a
1831 // SUB dst, tmp, b
1832 // with
1833 // ADD tmp, a, b
1834 // NEG dst, tmp
1835 // The second version is not intrinsically better, but enables more
1836 // transformations.
1837 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
1838 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
1839 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
1840 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
1841 instruction->ReplaceWith(neg);
1842 instruction->GetBlock()->RemoveInstruction(instruction);
1843 RecordSimplification();
1844 left->GetBlock()->RemoveInstruction(left);
Anton Kirilove14dc862016-05-13 17:56:15 +01001845 return;
1846 }
1847
1848 if (TrySubtractionChainSimplification(instruction)) {
1849 return;
Alexandre Rames188d4312015-04-09 18:30:21 +01001850 }
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001851
1852 if (left->IsAdd()) {
1853 // Replace code patterns looking like
1854 // ADD dst1, x, y ADD dst1, x, y
1855 // SUB dst2, dst1, y SUB dst2, dst1, x
1856 // with
1857 // ADD dst1, x, y
1858 // SUB instruction is not needed in this case, we may use
1859 // one of inputs of ADD instead.
1860 // It is applicable to integral types only.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001861 DCHECK(DataType::IsIntegralType(type));
Maxim Kazantsevd3278bd2016-07-12 15:55:33 +06001862 if (left->InputAt(1) == right) {
1863 instruction->ReplaceWith(left->InputAt(0));
1864 RecordSimplification();
1865 instruction->GetBlock()->RemoveInstruction(instruction);
1866 return;
1867 } else if (left->InputAt(0) == right) {
1868 instruction->ReplaceWith(left->InputAt(1));
1869 RecordSimplification();
1870 instruction->GetBlock()->RemoveInstruction(instruction);
1871 return;
1872 }
1873 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001874}
1875
1876void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
1877 VisitShift(instruction);
1878}
1879
1880void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
1881 HConstant* input_cst = instruction->GetConstantRight();
1882 HInstruction* input_other = instruction->GetLeastConstantLeft();
1883
Roland Levillain1a653882016-03-18 18:05:57 +00001884 if ((input_cst != nullptr) && input_cst->IsZeroBitPattern()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001885 // Replace code looking like
1886 // XOR dst, src, 0
1887 // with
1888 // src
1889 instruction->ReplaceWith(input_other);
1890 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Ramesc5809c32016-05-25 15:01:06 +01001891 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001892 return;
1893 }
1894
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001895 if ((input_cst != nullptr) && input_cst->IsOne()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001896 && input_other->GetType() == DataType::Type::kBool) {
Sebastien Hertz9837caf2016-08-01 11:09:50 +02001897 // Replace code looking like
1898 // XOR dst, src, 1
1899 // with
1900 // BOOLEAN_NOT dst, src
1901 HBooleanNot* boolean_not = new (GetGraph()->GetArena()) HBooleanNot(input_other);
1902 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, boolean_not);
1903 RecordSimplification();
1904 return;
1905 }
1906
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001907 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1908 // Replace code looking like
1909 // XOR dst, src, 0xFFF...FF
1910 // with
1911 // NOT dst, src
1912 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1913 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001914 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001915 return;
1916 }
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001917
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001918 HInstruction* left = instruction->GetLeft();
1919 HInstruction* right = instruction->GetRight();
Alexandre Rames9f980252016-02-05 14:00:28 +00001920 if (((left->IsNot() && right->IsNot()) ||
1921 (left->IsBooleanNot() && right->IsBooleanNot())) &&
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001922 left->HasOnlyOneNonEnvironmentUse() &&
1923 right->HasOnlyOneNonEnvironmentUse()) {
1924 // Replace code looking like
1925 // NOT nota, a
1926 // NOT notb, b
1927 // XOR dst, nota, notb
1928 // with
1929 // XOR dst, a, b
Alexandre Rames9f980252016-02-05 14:00:28 +00001930 instruction->ReplaceInput(left->InputAt(0), 0);
1931 instruction->ReplaceInput(right->InputAt(0), 1);
Alexandre Ramesca0e3a02016-02-03 10:54:07 +00001932 left->GetBlock()->RemoveInstruction(left);
1933 right->GetBlock()->RemoveInstruction(right);
1934 RecordSimplification();
1935 return;
1936 }
1937
Anton Kirilove14dc862016-05-13 17:56:15 +01001938 if (TryReplaceWithRotate(instruction)) {
1939 return;
1940 }
1941
1942 // TryHandleAssociativeAndCommutativeOperation() does not remove its input,
1943 // so no need to return.
1944 TryHandleAssociativeAndCommutativeOperation(instruction);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001945}
1946
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001947void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1948 HInstruction* argument = instruction->InputAt(1);
1949 HInstruction* receiver = instruction->InputAt(0);
1950 if (receiver == argument) {
1951 // Because String.equals is an instance call, the receiver is
1952 // a null check if we don't know it's null. The argument however, will
1953 // be the actual object. So we cannot end up in a situation where both
1954 // are equal but could be null.
1955 DCHECK(CanEnsureNotNullAt(argument, instruction));
1956 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1957 instruction->GetBlock()->RemoveInstruction(instruction);
1958 } else {
1959 StringEqualsOptimizations optimizations(instruction);
1960 if (CanEnsureNotNullAt(argument, instruction)) {
1961 optimizations.SetArgumentNotNull();
1962 }
1963 ScopedObjectAccess soa(Thread::Current());
1964 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1965 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1966 optimizations.SetArgumentIsString();
1967 }
1968 }
1969}
1970
Roland Levillain22c49222016-03-18 14:04:28 +00001971void InstructionSimplifierVisitor::SimplifyRotate(HInvoke* invoke,
1972 bool is_left,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001973 DataType::Type type) {
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001974 DCHECK(invoke->IsInvokeStaticOrDirect());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001975 DCHECK_EQ(invoke->GetInvokeType(), InvokeType::kStatic);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001976 HInstruction* value = invoke->InputAt(0);
1977 HInstruction* distance = invoke->InputAt(1);
1978 // Replace the invoke with an HRor.
1979 if (is_left) {
Roland Levillain937e6cd2016-03-22 11:54:37 +00001980 // Unconditionally set the type of the negated distance to `int`,
1981 // as shift and rotate operations expect a 32-bit (or narrower)
1982 // value for their distance input.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001983 distance = new (GetGraph()->GetArena()) HNeg(DataType::Type::kInt32, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001984 invoke->GetBlock()->InsertInstructionBefore(distance, invoke);
1985 }
Roland Levillain22c49222016-03-18 14:04:28 +00001986 HRor* ror = new (GetGraph()->GetArena()) HRor(type, value, distance);
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001987 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, ror);
1988 // Remove ClinitCheck and LoadClass, if possible.
Vladimir Marko372f10e2016-05-17 16:30:10 +01001989 HInstruction* clinit = invoke->GetInputs().back();
Scott Wakeling40a04bf2015-12-11 09:50:36 +00001990 if (clinit->IsClinitCheck() && !clinit->HasUses()) {
1991 clinit->GetBlock()->RemoveInstruction(clinit);
1992 HInstruction* ldclass = clinit->InputAt(0);
1993 if (ldclass->IsLoadClass() && !ldclass->HasUses()) {
1994 ldclass->GetBlock()->RemoveInstruction(ldclass);
1995 }
1996 }
1997}
1998
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001999static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
2000 if (potential_length->IsArrayLength()) {
2001 return potential_length->InputAt(0) == potential_array;
2002 }
2003
2004 if (potential_array->IsNewArray()) {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00002005 return potential_array->AsNewArray()->GetLength() == potential_length;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002006 }
2007
2008 return false;
2009}
2010
2011void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
2012 HInstruction* source = instruction->InputAt(0);
2013 HInstruction* destination = instruction->InputAt(2);
2014 HInstruction* count = instruction->InputAt(4);
2015 SystemArrayCopyOptimizations optimizations(instruction);
2016 if (CanEnsureNotNullAt(source, instruction)) {
2017 optimizations.SetSourceIsNotNull();
2018 }
2019 if (CanEnsureNotNullAt(destination, instruction)) {
2020 optimizations.SetDestinationIsNotNull();
2021 }
2022 if (destination == source) {
2023 optimizations.SetDestinationIsSource();
2024 }
2025
2026 if (IsArrayLengthOf(count, source)) {
2027 optimizations.SetCountIsSourceLength();
2028 }
2029
2030 if (IsArrayLengthOf(count, destination)) {
2031 optimizations.SetCountIsDestinationLength();
2032 }
2033
2034 {
2035 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002036 DataType::Type source_component_type = DataType::Type::kVoid;
2037 DataType::Type destination_component_type = DataType::Type::kVoid;
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002038 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
2039 if (destination_rti.IsValid()) {
2040 if (destination_rti.IsObjectArray()) {
2041 if (destination_rti.IsExact()) {
2042 optimizations.SetDoesNotNeedTypeCheck();
2043 }
2044 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002045 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002046 if (destination_rti.IsPrimitiveArrayClass()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002047 destination_component_type = DataTypeFromPrimitive(
2048 destination_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002049 optimizations.SetDestinationIsPrimitiveArray();
2050 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
2051 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002052 }
2053 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002054 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
2055 if (source_rti.IsValid()) {
2056 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
2057 optimizations.SetDoesNotNeedTypeCheck();
2058 }
2059 if (source_rti.IsPrimitiveArrayClass()) {
2060 optimizations.SetSourceIsPrimitiveArray();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002061 source_component_type = DataTypeFromPrimitive(
2062 source_rti.GetTypeHandle()->GetComponentType()->GetPrimitiveType());
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002063 } else if (source_rti.IsNonPrimitiveArrayClass()) {
2064 optimizations.SetSourceIsNonPrimitiveArray();
2065 }
2066 }
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002067 // For primitive arrays, use their optimized ArtMethod implementations.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002068 if ((source_component_type != DataType::Type::kVoid) &&
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002069 (source_component_type == destination_component_type)) {
2070 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2071 PointerSize image_size = class_linker->GetImagePointerSize();
2072 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
2073 mirror::Class* system = invoke->GetResolvedMethod()->GetDeclaringClass();
2074 ArtMethod* method = nullptr;
2075 switch (source_component_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002076 case DataType::Type::kBool:
Vladimir Markoba118822017-06-12 15:41:56 +01002077 method = system->FindClassMethod("arraycopy", "([ZI[ZII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002078 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002079 case DataType::Type::kInt8:
Vladimir Markoba118822017-06-12 15:41:56 +01002080 method = system->FindClassMethod("arraycopy", "([BI[BII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002081 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002082 case DataType::Type::kUint16:
Vladimir Markoba118822017-06-12 15:41:56 +01002083 method = system->FindClassMethod("arraycopy", "([CI[CII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002084 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002085 case DataType::Type::kInt16:
Vladimir Markoba118822017-06-12 15:41:56 +01002086 method = system->FindClassMethod("arraycopy", "([SI[SII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002087 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002088 case DataType::Type::kInt32:
Vladimir Markoba118822017-06-12 15:41:56 +01002089 method = system->FindClassMethod("arraycopy", "([II[III)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002090 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002091 case DataType::Type::kFloat32:
Vladimir Markoba118822017-06-12 15:41:56 +01002092 method = system->FindClassMethod("arraycopy", "([FI[FII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002093 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002094 case DataType::Type::kInt64:
Vladimir Markoba118822017-06-12 15:41:56 +01002095 method = system->FindClassMethod("arraycopy", "([JI[JII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002096 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002097 case DataType::Type::kFloat64:
Vladimir Markoba118822017-06-12 15:41:56 +01002098 method = system->FindClassMethod("arraycopy", "([DI[DII)V", image_size);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002099 break;
2100 default:
2101 LOG(FATAL) << "Unreachable";
2102 }
2103 DCHECK(method != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01002104 DCHECK(method->IsStatic());
2105 DCHECK(method->GetDeclaringClass() == system);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002106 invoke->SetResolvedMethod(method);
2107 // Sharpen the new invoke. Note that we do not update the dex method index of
2108 // the invoke, as we would need to look it up in the current dex file, and it
2109 // is unlikely that it exists. The most usual situation for such typed
2110 // arraycopy methods is a direct pointer to the boot image.
Vladimir Marko65979462017-05-19 17:25:12 +01002111 HSharpening::SharpenInvokeStaticOrDirect(invoke, codegen_, compiler_driver_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00002112 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002113 }
2114}
2115
Roland Levillaina5c4a402016-03-15 15:02:50 +00002116void InstructionSimplifierVisitor::SimplifyCompare(HInvoke* invoke,
2117 bool is_signum,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002118 DataType::Type type) {
Aart Bika19616e2016-02-01 18:57:58 -08002119 DCHECK(invoke->IsInvokeStaticOrDirect());
2120 uint32_t dex_pc = invoke->GetDexPc();
2121 HInstruction* left = invoke->InputAt(0);
2122 HInstruction* right;
Aart Bika19616e2016-02-01 18:57:58 -08002123 if (!is_signum) {
2124 right = invoke->InputAt(1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002125 } else if (type == DataType::Type::kInt64) {
Aart Bika19616e2016-02-01 18:57:58 -08002126 right = GetGraph()->GetLongConstant(0);
2127 } else {
2128 right = GetGraph()->GetIntConstant(0);
2129 }
2130 HCompare* compare = new (GetGraph()->GetArena())
2131 HCompare(type, left, right, ComparisonBias::kNoBias, dex_pc);
2132 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, compare);
2133}
2134
Aart Bik75a38b22016-02-17 10:41:50 -08002135void InstructionSimplifierVisitor::SimplifyIsNaN(HInvoke* invoke) {
2136 DCHECK(invoke->IsInvokeStaticOrDirect());
2137 uint32_t dex_pc = invoke->GetDexPc();
2138 // IsNaN(x) is the same as x != x.
2139 HInstruction* x = invoke->InputAt(0);
2140 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
Aart Bik8ffc1fa2016-02-17 15:13:56 -08002141 condition->SetBias(ComparisonBias::kLtBias);
Aart Bik75a38b22016-02-17 10:41:50 -08002142 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, condition);
2143}
2144
Aart Bik2a6aad92016-02-25 11:32:32 -08002145void InstructionSimplifierVisitor::SimplifyFP2Int(HInvoke* invoke) {
2146 DCHECK(invoke->IsInvokeStaticOrDirect());
2147 uint32_t dex_pc = invoke->GetDexPc();
2148 HInstruction* x = invoke->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002149 DataType::Type type = x->GetType();
Aart Bik2a6aad92016-02-25 11:32:32 -08002150 // Set proper bit pattern for NaN and replace intrinsic with raw version.
2151 HInstruction* nan;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002152 if (type == DataType::Type::kFloat64) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002153 nan = GetGraph()->GetLongConstant(0x7ff8000000000000L);
2154 invoke->SetIntrinsic(Intrinsics::kDoubleDoubleToRawLongBits,
2155 kNeedsEnvironmentOrCache,
2156 kNoSideEffects,
2157 kNoThrow);
2158 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002159 DCHECK_EQ(type, DataType::Type::kFloat32);
Aart Bik2a6aad92016-02-25 11:32:32 -08002160 nan = GetGraph()->GetIntConstant(0x7fc00000);
2161 invoke->SetIntrinsic(Intrinsics::kFloatFloatToRawIntBits,
2162 kNeedsEnvironmentOrCache,
2163 kNoSideEffects,
2164 kNoThrow);
2165 }
2166 // Test IsNaN(x), which is the same as x != x.
2167 HCondition* condition = new (GetGraph()->GetArena()) HNotEqual(x, x, dex_pc);
2168 condition->SetBias(ComparisonBias::kLtBias);
2169 invoke->GetBlock()->InsertInstructionBefore(condition, invoke->GetNext());
2170 // Select between the two.
2171 HInstruction* select = new (GetGraph()->GetArena()) HSelect(condition, nan, invoke, dex_pc);
2172 invoke->GetBlock()->InsertInstructionBefore(select, condition->GetNext());
2173 invoke->ReplaceWithExceptInReplacementAtIndex(select, 0); // false at index 0
2174}
2175
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002176void InstructionSimplifierVisitor::SimplifyStringCharAt(HInvoke* invoke) {
2177 HInstruction* str = invoke->InputAt(0);
2178 HInstruction* index = invoke->InputAt(1);
2179 uint32_t dex_pc = invoke->GetDexPc();
2180 ArenaAllocator* arena = GetGraph()->GetArena();
2181 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2182 // so create the HArrayLength, HBoundsCheck and HArrayGet.
2183 HArrayLength* length = new (arena) HArrayLength(str, dex_pc, /* is_string_length */ true);
2184 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
Nicolas Geoffray431121f2017-01-09 14:02:45 +00002185 HBoundsCheck* bounds_check = new (arena) HBoundsCheck(
2186 index, length, dex_pc, invoke->GetDexMethodIndex());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002187 invoke->GetBlock()->InsertInstructionBefore(bounds_check, invoke);
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002188 HArrayGet* array_get = new (arena) HArrayGet(str,
2189 bounds_check,
2190 DataType::Type::kUint16,
2191 SideEffects::None(), // Strings are immutable.
2192 dex_pc,
2193 /* is_string_char_at */ true);
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002194 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, array_get);
2195 bounds_check->CopyEnvironmentFrom(invoke->GetEnvironment());
2196 GetGraph()->SetHasBoundsChecks(true);
2197}
2198
Vladimir Markodce016e2016-04-28 13:10:02 +01002199void InstructionSimplifierVisitor::SimplifyStringIsEmptyOrLength(HInvoke* invoke) {
2200 HInstruction* str = invoke->InputAt(0);
2201 uint32_t dex_pc = invoke->GetDexPc();
2202 // We treat String as an array to allow DCE and BCE to seamlessly work on strings,
2203 // so create the HArrayLength.
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002204 HArrayLength* length =
2205 new (GetGraph()->GetArena()) HArrayLength(str, dex_pc, /* is_string_length */ true);
Vladimir Markodce016e2016-04-28 13:10:02 +01002206 HInstruction* replacement;
2207 if (invoke->GetIntrinsic() == Intrinsics::kStringIsEmpty) {
2208 // For String.isEmpty(), create the `HEqual` representing the `length == 0`.
2209 invoke->GetBlock()->InsertInstructionBefore(length, invoke);
2210 HIntConstant* zero = GetGraph()->GetIntConstant(0);
2211 HEqual* equal = new (GetGraph()->GetArena()) HEqual(length, zero, dex_pc);
2212 replacement = equal;
2213 } else {
2214 DCHECK_EQ(invoke->GetIntrinsic(), Intrinsics::kStringLength);
2215 replacement = length;
2216 }
2217 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, replacement);
2218}
2219
Aart Bikff7d89c2016-11-07 08:49:28 -08002220// This method should only be used on intrinsics whose sole way of throwing an
2221// exception is raising a NPE when the nth argument is null. If that argument
2222// is provably non-null, we can clear the flag.
2223void InstructionSimplifierVisitor::SimplifyNPEOnArgN(HInvoke* invoke, size_t n) {
2224 HInstruction* arg = invoke->InputAt(n);
Aart Bik71bf7b42016-11-16 10:17:46 -08002225 if (invoke->CanThrow() && !arg->CanBeNull()) {
Aart Bikff7d89c2016-11-07 08:49:28 -08002226 invoke->SetCanThrow(false);
2227 }
2228}
2229
Aart Bik71bf7b42016-11-16 10:17:46 -08002230// Methods that return "this" can replace the returned value with the receiver.
2231void InstructionSimplifierVisitor::SimplifyReturnThis(HInvoke* invoke) {
2232 if (invoke->HasUses()) {
2233 HInstruction* receiver = invoke->InputAt(0);
2234 invoke->ReplaceWith(receiver);
2235 RecordSimplification();
2236 }
2237}
2238
2239// Helper method for StringBuffer escape analysis.
2240static bool NoEscapeForStringBufferReference(HInstruction* reference, HInstruction* user) {
2241 if (user->IsInvokeStaticOrDirect()) {
2242 // Any constructor on StringBuffer is okay.
Aart Bikab2270f2016-12-15 09:36:31 -08002243 return user->AsInvokeStaticOrDirect()->GetResolvedMethod() != nullptr &&
2244 user->AsInvokeStaticOrDirect()->GetResolvedMethod()->IsConstructor() &&
Aart Bik71bf7b42016-11-16 10:17:46 -08002245 user->InputAt(0) == reference;
2246 } else if (user->IsInvokeVirtual()) {
2247 switch (user->AsInvokeVirtual()->GetIntrinsic()) {
2248 case Intrinsics::kStringBufferLength:
2249 case Intrinsics::kStringBufferToString:
2250 DCHECK_EQ(user->InputAt(0), reference);
2251 return true;
2252 case Intrinsics::kStringBufferAppend:
2253 // Returns "this", so only okay if no further uses.
2254 DCHECK_EQ(user->InputAt(0), reference);
2255 DCHECK_NE(user->InputAt(1), reference);
2256 return !user->HasUses();
2257 default:
2258 break;
2259 }
2260 }
2261 return false;
2262}
2263
2264// Certain allocation intrinsics are not removed by dead code elimination
2265// because of potentially throwing an OOM exception or other side effects.
2266// This method removes such intrinsics when special circumstances allow.
2267void InstructionSimplifierVisitor::SimplifyAllocationIntrinsic(HInvoke* invoke) {
2268 if (!invoke->HasUses()) {
2269 // Instruction has no uses. If unsynchronized, we can remove right away, safely ignoring
2270 // the potential OOM of course. Otherwise, we must ensure the receiver object of this
2271 // call does not escape since only thread-local synchronization may be removed.
2272 bool is_synchronized = invoke->GetIntrinsic() == Intrinsics::kStringBufferToString;
2273 HInstruction* receiver = invoke->InputAt(0);
2274 if (!is_synchronized || DoesNotEscape(receiver, NoEscapeForStringBufferReference)) {
2275 invoke->GetBlock()->RemoveInstruction(invoke);
2276 RecordSimplification();
2277 }
2278 }
2279}
2280
Aart Bik11932592016-03-08 12:42:25 -08002281void InstructionSimplifierVisitor::SimplifyMemBarrier(HInvoke* invoke, MemBarrierKind barrier_kind) {
2282 uint32_t dex_pc = invoke->GetDexPc();
2283 HMemoryBarrier* mem_barrier = new (GetGraph()->GetArena()) HMemoryBarrier(barrier_kind, dex_pc);
2284 invoke->GetBlock()->ReplaceAndRemoveInstructionWith(invoke, mem_barrier);
2285}
2286
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01002287void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
Aart Bik2a6aad92016-02-25 11:32:32 -08002288 switch (instruction->GetIntrinsic()) {
2289 case Intrinsics::kStringEquals:
2290 SimplifyStringEquals(instruction);
2291 break;
2292 case Intrinsics::kSystemArrayCopy:
2293 SimplifySystemArrayCopy(instruction);
2294 break;
2295 case Intrinsics::kIntegerRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002296 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002297 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002298 case Intrinsics::kLongRotateRight:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002299 SimplifyRotate(instruction, /* is_left */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002300 break;
2301 case Intrinsics::kIntegerRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002302 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt32);
Roland Levillain22c49222016-03-18 14:04:28 +00002303 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002304 case Intrinsics::kLongRotateLeft:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002305 SimplifyRotate(instruction, /* is_left */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002306 break;
2307 case Intrinsics::kIntegerCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002308 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002309 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002310 case Intrinsics::kLongCompare:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002311 SimplifyCompare(instruction, /* is_signum */ false, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002312 break;
2313 case Intrinsics::kIntegerSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002314 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt32);
Roland Levillaina5c4a402016-03-15 15:02:50 +00002315 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002316 case Intrinsics::kLongSignum:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002317 SimplifyCompare(instruction, /* is_signum */ true, DataType::Type::kInt64);
Aart Bik2a6aad92016-02-25 11:32:32 -08002318 break;
2319 case Intrinsics::kFloatIsNaN:
2320 case Intrinsics::kDoubleIsNaN:
2321 SimplifyIsNaN(instruction);
2322 break;
2323 case Intrinsics::kFloatFloatToIntBits:
2324 case Intrinsics::kDoubleDoubleToLongBits:
2325 SimplifyFP2Int(instruction);
2326 break;
Vladimir Marko87f3fcb2016-04-28 15:52:11 +01002327 case Intrinsics::kStringCharAt:
2328 SimplifyStringCharAt(instruction);
2329 break;
Vladimir Markodce016e2016-04-28 13:10:02 +01002330 case Intrinsics::kStringIsEmpty:
2331 case Intrinsics::kStringLength:
2332 SimplifyStringIsEmptyOrLength(instruction);
2333 break;
Aart Bikff7d89c2016-11-07 08:49:28 -08002334 case Intrinsics::kStringStringIndexOf:
2335 case Intrinsics::kStringStringIndexOfAfter:
2336 SimplifyNPEOnArgN(instruction, 1); // 0th has own NullCheck
2337 break;
Aart Bik71bf7b42016-11-16 10:17:46 -08002338 case Intrinsics::kStringBufferAppend:
2339 case Intrinsics::kStringBuilderAppend:
2340 SimplifyReturnThis(instruction);
2341 break;
2342 case Intrinsics::kStringBufferToString:
2343 case Intrinsics::kStringBuilderToString:
2344 SimplifyAllocationIntrinsic(instruction);
2345 break;
Aart Bik11932592016-03-08 12:42:25 -08002346 case Intrinsics::kUnsafeLoadFence:
2347 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2348 break;
2349 case Intrinsics::kUnsafeStoreFence:
2350 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2351 break;
2352 case Intrinsics::kUnsafeFullFence:
2353 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2354 break;
Orion Hodson4a4610a2017-09-28 16:57:55 +01002355 case Intrinsics::kVarHandleFullFence:
2356 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyAny);
2357 break;
2358 case Intrinsics::kVarHandleAcquireFence:
2359 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2360 break;
2361 case Intrinsics::kVarHandleReleaseFence:
2362 SimplifyMemBarrier(instruction, MemBarrierKind::kAnyStore);
2363 break;
2364 case Intrinsics::kVarHandleLoadLoadFence:
2365 SimplifyMemBarrier(instruction, MemBarrierKind::kLoadAny);
2366 break;
2367 case Intrinsics::kVarHandleStoreStoreFence:
2368 SimplifyMemBarrier(instruction, MemBarrierKind::kStoreStore);
2369 break;
Aart Bik2a6aad92016-02-25 11:32:32 -08002370 default:
2371 break;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002372 }
2373}
2374
Aart Bikbb245d12015-10-19 11:05:03 -07002375void InstructionSimplifierVisitor::VisitDeoptimize(HDeoptimize* deoptimize) {
2376 HInstruction* cond = deoptimize->InputAt(0);
2377 if (cond->IsConstant()) {
Roland Levillain1a653882016-03-18 18:05:57 +00002378 if (cond->AsIntConstant()->IsFalse()) {
Aart Bikbb245d12015-10-19 11:05:03 -07002379 // Never deopt: instruction can be removed.
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00002380 if (deoptimize->GuardsAnInput()) {
2381 deoptimize->ReplaceWith(deoptimize->GuardedInput());
2382 }
Aart Bikbb245d12015-10-19 11:05:03 -07002383 deoptimize->GetBlock()->RemoveInstruction(deoptimize);
2384 } else {
2385 // Always deopt.
2386 }
2387 }
2388}
2389
Anton Kirilove14dc862016-05-13 17:56:15 +01002390// Replace code looking like
2391// OP y, x, const1
2392// OP z, y, const2
2393// with
2394// OP z, x, const3
2395// where OP is both an associative and a commutative operation.
2396bool InstructionSimplifierVisitor::TryHandleAssociativeAndCommutativeOperation(
2397 HBinaryOperation* instruction) {
2398 DCHECK(instruction->IsCommutative());
2399
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002400 if (!DataType::IsIntegralType(instruction->GetType())) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002401 return false;
2402 }
2403
2404 HInstruction* left = instruction->GetLeft();
2405 HInstruction* right = instruction->GetRight();
2406 // Variable names as described above.
2407 HConstant* const2;
2408 HBinaryOperation* y;
2409
2410 if (instruction->InstructionTypeEquals(left) && right->IsConstant()) {
2411 const2 = right->AsConstant();
2412 y = left->AsBinaryOperation();
2413 } else if (left->IsConstant() && instruction->InstructionTypeEquals(right)) {
2414 const2 = left->AsConstant();
2415 y = right->AsBinaryOperation();
2416 } else {
2417 // The node does not match the pattern.
2418 return false;
2419 }
2420
2421 // If `y` has more than one use, we do not perform the optimization
2422 // because it might increase code size (e.g. if the new constant is
2423 // no longer encodable as an immediate operand in the target ISA).
2424 if (!y->HasOnlyOneNonEnvironmentUse()) {
2425 return false;
2426 }
2427
2428 // GetConstantRight() can return both left and right constants
2429 // for commutative operations.
2430 HConstant* const1 = y->GetConstantRight();
2431 if (const1 == nullptr) {
2432 return false;
2433 }
2434
2435 instruction->ReplaceInput(const1, 0);
2436 instruction->ReplaceInput(const2, 1);
2437 HConstant* const3 = instruction->TryStaticEvaluation();
2438 DCHECK(const3 != nullptr);
2439 instruction->ReplaceInput(y->GetLeastConstantLeft(), 0);
2440 instruction->ReplaceInput(const3, 1);
2441 RecordSimplification();
2442 return true;
2443}
2444
2445static HBinaryOperation* AsAddOrSub(HInstruction* binop) {
2446 return (binop->IsAdd() || binop->IsSub()) ? binop->AsBinaryOperation() : nullptr;
2447}
2448
2449// Helper function that performs addition statically, considering the result type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002450static int64_t ComputeAddition(DataType::Type type, int64_t x, int64_t y) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002451 // Use the Compute() method for consistency with TryStaticEvaluation().
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002452 if (type == DataType::Type::kInt32) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002453 return HAdd::Compute<int32_t>(x, y);
2454 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002455 DCHECK_EQ(type, DataType::Type::kInt64);
Anton Kirilove14dc862016-05-13 17:56:15 +01002456 return HAdd::Compute<int64_t>(x, y);
2457 }
2458}
2459
2460// Helper function that handles the child classes of HConstant
2461// and returns an integer with the appropriate sign.
2462static int64_t GetValue(HConstant* constant, bool is_negated) {
2463 int64_t ret = Int64FromConstant(constant);
2464 return is_negated ? -ret : ret;
2465}
2466
2467// Replace code looking like
2468// OP1 y, x, const1
2469// OP2 z, y, const2
2470// with
2471// OP3 z, x, const3
2472// where OPx is either ADD or SUB, and at least one of OP{1,2} is SUB.
2473bool InstructionSimplifierVisitor::TrySubtractionChainSimplification(
2474 HBinaryOperation* instruction) {
2475 DCHECK(instruction->IsAdd() || instruction->IsSub()) << instruction->DebugName();
2476
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002477 DataType::Type type = instruction->GetType();
2478 if (!DataType::IsIntegralType(type)) {
Anton Kirilove14dc862016-05-13 17:56:15 +01002479 return false;
2480 }
2481
2482 HInstruction* left = instruction->GetLeft();
2483 HInstruction* right = instruction->GetRight();
2484 // Variable names as described above.
2485 HConstant* const2 = right->IsConstant() ? right->AsConstant() : left->AsConstant();
2486 if (const2 == nullptr) {
2487 return false;
2488 }
2489
2490 HBinaryOperation* y = (AsAddOrSub(left) != nullptr)
2491 ? left->AsBinaryOperation()
2492 : AsAddOrSub(right);
2493 // If y has more than one use, we do not perform the optimization because
2494 // it might increase code size (e.g. if the new constant is no longer
2495 // encodable as an immediate operand in the target ISA).
2496 if ((y == nullptr) || !y->HasOnlyOneNonEnvironmentUse()) {
2497 return false;
2498 }
2499
2500 left = y->GetLeft();
2501 HConstant* const1 = left->IsConstant() ? left->AsConstant() : y->GetRight()->AsConstant();
2502 if (const1 == nullptr) {
2503 return false;
2504 }
2505
2506 HInstruction* x = (const1 == left) ? y->GetRight() : left;
2507 // If both inputs are constants, let the constant folding pass deal with it.
2508 if (x->IsConstant()) {
2509 return false;
2510 }
2511
2512 bool is_const2_negated = (const2 == right) && instruction->IsSub();
2513 int64_t const2_val = GetValue(const2, is_const2_negated);
2514 bool is_y_negated = (y == right) && instruction->IsSub();
2515 right = y->GetRight();
2516 bool is_const1_negated = is_y_negated ^ ((const1 == right) && y->IsSub());
2517 int64_t const1_val = GetValue(const1, is_const1_negated);
2518 bool is_x_negated = is_y_negated ^ ((x == right) && y->IsSub());
2519 int64_t const3_val = ComputeAddition(type, const1_val, const2_val);
2520 HBasicBlock* block = instruction->GetBlock();
2521 HConstant* const3 = block->GetGraph()->GetConstant(type, const3_val);
2522 ArenaAllocator* arena = instruction->GetArena();
2523 HInstruction* z;
2524
2525 if (is_x_negated) {
2526 z = new (arena) HSub(type, const3, x, instruction->GetDexPc());
2527 } else {
2528 z = new (arena) HAdd(type, x, const3, instruction->GetDexPc());
2529 }
2530
2531 block->ReplaceAndRemoveInstructionWith(instruction, z);
2532 RecordSimplification();
2533 return true;
2534}
2535
Lena Djokicbc5460b2017-07-20 16:07:36 +02002536void InstructionSimplifierVisitor::VisitVecMul(HVecMul* instruction) {
2537 if (TryCombineVecMultiplyAccumulate(instruction)) {
2538 RecordSimplification();
2539 }
2540}
2541
Nicolas Geoffray3c049742014-09-24 18:10:46 +01002542} // namespace art