blob: 98a5841f8094b5ee94e56df46e9148fe75ab277c [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
Calin Juravleacf735c2015-02-12 15:25:22 +000019#include "mirror/class-inl.h"
20#include "scoped_thread_state_change.h"
21
Nicolas Geoffray3c049742014-09-24 18:10:46 +010022namespace art {
23
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000024class InstructionSimplifierVisitor : public HGraphVisitor {
25 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000026 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Alexandre Rames188d4312015-04-09 18:30:21 +010027 : HGraphVisitor(graph),
28 stats_(stats) {}
29
30 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000031
32 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010033 void RecordSimplification() {
34 simplification_occurred_ = true;
35 simplifications_at_current_position_++;
36 if (stats_) {
37 stats_->RecordStat(kInstructionSimplifications);
38 }
39 }
40
41 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000042 void VisitShift(HBinaryOperation* shift);
43
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000044 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
45 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010046 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
47 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010048 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
49 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000050 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000051 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000052 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080053 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000054 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000055 void VisitAdd(HAdd* instruction) OVERRIDE;
56 void VisitAnd(HAnd* instruction) OVERRIDE;
57 void VisitDiv(HDiv* instruction) OVERRIDE;
58 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010059 void VisitNeg(HNeg* instruction) OVERRIDE;
60 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000061 void VisitOr(HOr* instruction) OVERRIDE;
62 void VisitShl(HShl* instruction) OVERRIDE;
63 void VisitShr(HShr* instruction) OVERRIDE;
64 void VisitSub(HSub* instruction) OVERRIDE;
65 void VisitUShr(HUShr* instruction) OVERRIDE;
66 void VisitXor(HXor* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010067 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +010068 bool IsDominatedByInputNullCheck(HInstruction* instr);
Calin Juravleacf735c2015-02-12 15:25:22 +000069
70 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010071 bool simplification_occurred_ = false;
72 int simplifications_at_current_position_ = 0;
73 // We ensure we do not loop infinitely. The value is a finger in the air guess
74 // that should allow enough simplification.
75 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000076};
77
Nicolas Geoffray3c049742014-09-24 18:10:46 +010078void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +000079 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +010080 visitor.Run();
81}
82
83void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +010084 // Iterate in reverse post order to open up more simplifications to users
85 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +010086 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
87 // The simplification of an instruction to another instruction may yield
88 // possibilities for other simplifications. So although we perform a reverse
89 // post order visit, we sometimes need to revisit an instruction index.
90 simplification_occurred_ = false;
91 VisitBasicBlock(it.Current());
92 if (simplification_occurred_ &&
93 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
94 // New simplifications may be applicable to the instruction at the
95 // current index, so don't advance the iterator.
96 continue;
97 }
Alexandre Rames188d4312015-04-09 18:30:21 +010098 simplifications_at_current_position_ = 0;
99 it.Advance();
100 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100101}
102
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000103namespace {
104
105bool AreAllBitsSet(HConstant* constant) {
106 return Int64FromConstant(constant) == -1;
107}
108
109} // namespace
110
Alexandre Rames188d4312015-04-09 18:30:21 +0100111// Returns true if the code was simplified to use only one negation operation
112// after the binary operation instead of one on each of the inputs.
113bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
114 DCHECK(binop->IsAdd() || binop->IsSub());
115 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
116 HNeg* left_neg = binop->GetLeft()->AsNeg();
117 HNeg* right_neg = binop->GetRight()->AsNeg();
118 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
119 !right_neg->HasOnlyOneNonEnvironmentUse()) {
120 return false;
121 }
122 // Replace code looking like
123 // NEG tmp1, a
124 // NEG tmp2, b
125 // ADD dst, tmp1, tmp2
126 // with
127 // ADD tmp, a, b
128 // NEG dst, tmp
129 binop->ReplaceInput(left_neg->GetInput(), 0);
130 binop->ReplaceInput(right_neg->GetInput(), 1);
131 left_neg->GetBlock()->RemoveInstruction(left_neg);
132 right_neg->GetBlock()->RemoveInstruction(right_neg);
133 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
134 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
135 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
136 RecordSimplification();
137 return true;
138}
139
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000140void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
141 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
142 HConstant* input_cst = instruction->GetConstantRight();
143 HInstruction* input_other = instruction->GetLeastConstantLeft();
144
Mark Mendellba56d062015-05-05 21:34:03 -0400145 if (input_cst != nullptr) {
146 if (input_cst->IsZero()) {
147 // Replace code looking like
148 // SHL dst, src, 0
149 // with
150 // src
151 instruction->ReplaceWith(input_other);
152 instruction->GetBlock()->RemoveInstruction(instruction);
153 } else if (instruction->IsShl() && input_cst->IsOne()) {
154 // Replace Shl looking like
155 // SHL dst, src, 1
156 // with
157 // ADD dst, src, src
158 HAdd *add = new(GetGraph()->GetArena()) HAdd(instruction->GetType(),
159 input_other,
160 input_other);
161 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
162 RecordSimplification();
163 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000164 }
165}
166
Calin Juravle10e244f2015-01-26 18:54:32 +0000167void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
168 HInstruction* obj = null_check->InputAt(0);
169 if (!obj->CanBeNull()) {
170 null_check->ReplaceWith(obj);
171 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000172 if (stats_ != nullptr) {
173 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
174 }
175 }
176}
177
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100178bool InstructionSimplifierVisitor::IsDominatedByInputNullCheck(HInstruction* instr) {
179 HInstruction* input = instr->InputAt(0);
180 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
181 HInstruction* use = it.Current()->GetUser();
182 if (use->IsNullCheck() && use->StrictlyDominates(instr)) {
183 return true;
184 }
185 }
186 return false;
187}
188
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100189// Returns whether doing a type test between the class of `object` against `klass` has
190// a statically known outcome. The result of the test is stored in `outcome`.
191static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
192 if (!klass->IsResolved()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000193 // If the class couldn't be resolve it's not safe to compare against it. It's
194 // default type would be Top which might be wider that the actual class type
195 // and thus producing wrong results.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100196 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000197 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100198
199 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
200 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravleacf735c2015-02-12 15:25:22 +0000201 ScopedObjectAccess soa(Thread::Current());
202 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100203 *outcome = true;
204 return true;
205 } else if (obj_rti.IsExact()) {
206 // The test failed at compile time so will also fail at runtime.
207 *outcome = false;
208 return true;
209 } else if (!class_rti.IsInterface() && !obj_rti.IsSupertypeOf(class_rti)) {
210 // Different type hierarchy. The test will fail.
211 *outcome = false;
212 return true;
213 }
214 return false;
215}
216
217void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
218 HInstruction* object = check_cast->InputAt(0);
219 if (!object->CanBeNull() || IsDominatedByInputNullCheck(check_cast)) {
220 check_cast->ClearMustDoNullCheck();
221 }
222
223 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000224 check_cast->GetBlock()->RemoveInstruction(check_cast);
225 if (stats_ != nullptr) {
226 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
227 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100228 return;
229 }
230
231 bool outcome;
232 if (TypeCheckHasKnownOutcome(check_cast->InputAt(1)->AsLoadClass(), object, &outcome)) {
233 if (outcome) {
234 check_cast->GetBlock()->RemoveInstruction(check_cast);
235 if (stats_ != nullptr) {
236 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
237 }
238 } else {
239 // Don't do anything for exceptional cases for now. Ideally we should remove
240 // all instructions and blocks this instruction dominates.
241 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000242 }
243}
244
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100245void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100246 HInstruction* object = instruction->InputAt(0);
247 bool can_be_null = true;
248 if (!object->CanBeNull() || IsDominatedByInputNullCheck(instruction)) {
249 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100250 instruction->ClearMustDoNullCheck();
251 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100252
253 HGraph* graph = GetGraph();
254 if (object->IsNullConstant()) {
255 instruction->ReplaceWith(graph->GetIntConstant(0));
256 instruction->GetBlock()->RemoveInstruction(instruction);
257 RecordSimplification();
258 return;
259 }
260
261 bool outcome;
262 if (TypeCheckHasKnownOutcome(instruction->InputAt(1)->AsLoadClass(), object, &outcome)) {
263 if (outcome && can_be_null) {
264 // Type test will succeed, we just need a null test.
265 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
266 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
267 instruction->ReplaceWith(test);
268 } else {
269 // We've statically determined the result of the instanceof.
270 instruction->ReplaceWith(graph->GetIntConstant(outcome));
271 }
272 RecordSimplification();
273 instruction->GetBlock()->RemoveInstruction(instruction);
274 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100275}
276
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100277void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
278 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
279 && !instruction->GetValue()->CanBeNull()) {
280 instruction->ClearValueCanBeNull();
281 }
282}
283
284void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
285 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
286 && !instruction->GetValue()->CanBeNull()) {
287 instruction->ClearValueCanBeNull();
288 }
289}
290
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000291void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100292 HBasicBlock* block = check->GetBlock();
293 // Currently always keep the suspend check at entry.
294 if (block->IsEntryBlock()) return;
295
296 // Currently always keep suspend checks at loop entry.
297 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
298 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
299 return;
300 }
301
302 // Remove the suspend check that was added at build time for the baseline
303 // compiler.
304 block->RemoveInstruction(check);
305}
306
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000307void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100308 HInstruction* input_const = equal->GetConstantRight();
309 if (input_const != nullptr) {
310 HInstruction* input_value = equal->GetLeastConstantLeft();
311 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
312 HBasicBlock* block = equal->GetBlock();
313 if (input_const->AsIntConstant()->IsOne()) {
314 // Replace (bool_value == true) with bool_value
315 equal->ReplaceWith(input_value);
316 block->RemoveInstruction(equal);
317 RecordSimplification();
318 } else {
319 // Replace (bool_value == false) with !bool_value
320 DCHECK(input_const->AsIntConstant()->IsZero());
321 block->ReplaceAndRemoveInstructionWith(
322 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
323 RecordSimplification();
324 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100325 }
326 }
327}
328
David Brazdil0d13fee2015-04-17 14:52:19 +0100329void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
330 HInstruction* input_const = not_equal->GetConstantRight();
331 if (input_const != nullptr) {
332 HInstruction* input_value = not_equal->GetLeastConstantLeft();
333 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
334 HBasicBlock* block = not_equal->GetBlock();
335 if (input_const->AsIntConstant()->IsOne()) {
336 // Replace (bool_value != true) with !bool_value
337 block->ReplaceAndRemoveInstructionWith(
338 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
339 RecordSimplification();
340 } else {
341 // Replace (bool_value != false) with bool_value
342 DCHECK(input_const->AsIntConstant()->IsZero());
343 not_equal->ReplaceWith(input_value);
344 block->RemoveInstruction(not_equal);
345 RecordSimplification();
346 }
347 }
348 }
349}
350
351void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
352 HInstruction* parent = bool_not->InputAt(0);
353 if (parent->IsBooleanNot()) {
354 HInstruction* value = parent->InputAt(0);
355 // Replace (!(!bool_value)) with bool_value
356 bool_not->ReplaceWith(value);
357 bool_not->GetBlock()->RemoveInstruction(bool_not);
358 // It is possible that `parent` is dead at this point but we leave
359 // its removal to DCE for simplicity.
360 RecordSimplification();
361 }
362}
363
Mingyao Yang0304e182015-01-30 16:41:29 -0800364void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
365 HInstruction* input = instruction->InputAt(0);
366 // If the array is a NewArray with constant size, replace the array length
367 // with the constant instruction. This helps the bounds check elimination phase.
368 if (input->IsNewArray()) {
369 input = input->InputAt(0);
370 if (input->IsIntConstant()) {
371 instruction->ReplaceWith(input);
372 }
373 }
374}
375
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000376void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000377 HInstruction* value = instruction->GetValue();
378 if (value->GetType() != Primitive::kPrimNot) return;
379
380 if (value->IsArrayGet()) {
381 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
382 // If the code is just swapping elements in the array, no need for a type check.
383 instruction->ClearNeedsTypeCheck();
384 }
385 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100386
387 if (!value->CanBeNull()) {
388 instruction->ClearValueCanBeNull();
389 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000390}
391
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000392void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
393 if (instruction->GetResultType() == instruction->GetInputType()) {
394 // Remove the instruction if it's converting to the same type.
395 instruction->ReplaceWith(instruction->GetInput());
396 instruction->GetBlock()->RemoveInstruction(instruction);
397 }
398}
399
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000400void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
401 HConstant* input_cst = instruction->GetConstantRight();
402 HInstruction* input_other = instruction->GetLeastConstantLeft();
403 if ((input_cst != nullptr) && input_cst->IsZero()) {
404 // Replace code looking like
405 // ADD dst, src, 0
406 // with
407 // src
408 instruction->ReplaceWith(input_other);
409 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames188d4312015-04-09 18:30:21 +0100410 return;
411 }
412
413 HInstruction* left = instruction->GetLeft();
414 HInstruction* right = instruction->GetRight();
415 bool left_is_neg = left->IsNeg();
416 bool right_is_neg = right->IsNeg();
417
418 if (left_is_neg && right_is_neg) {
419 if (TryMoveNegOnInputsAfterBinop(instruction)) {
420 return;
421 }
422 }
423
424 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
425 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
426 // Replace code looking like
427 // NEG tmp, b
428 // ADD dst, a, tmp
429 // with
430 // SUB dst, a, b
431 // We do not perform the optimization if the input negation has environment
432 // uses or multiple non-environment uses as it could lead to worse code. In
433 // particular, we do not want the live range of `b` to be extended if we are
434 // not sure the initial 'NEG' instruction can be removed.
435 HInstruction* other = left_is_neg ? right : left;
436 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
437 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
438 RecordSimplification();
439 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000440 }
441}
442
443void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
444 HConstant* input_cst = instruction->GetConstantRight();
445 HInstruction* input_other = instruction->GetLeastConstantLeft();
446
447 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
448 // Replace code looking like
449 // AND dst, src, 0xFFF...FF
450 // with
451 // src
452 instruction->ReplaceWith(input_other);
453 instruction->GetBlock()->RemoveInstruction(instruction);
454 return;
455 }
456
457 // We assume that GVN has run before, so we only perform a pointer comparison.
458 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100459 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000460 if (instruction->GetLeft() == instruction->GetRight()) {
461 // Replace code looking like
462 // AND dst, src, src
463 // with
464 // src
465 instruction->ReplaceWith(instruction->GetLeft());
466 instruction->GetBlock()->RemoveInstruction(instruction);
467 }
468}
469
470void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
471 HConstant* input_cst = instruction->GetConstantRight();
472 HInstruction* input_other = instruction->GetLeastConstantLeft();
473 Primitive::Type type = instruction->GetType();
474
475 if ((input_cst != nullptr) && input_cst->IsOne()) {
476 // Replace code looking like
477 // DIV dst, src, 1
478 // with
479 // src
480 instruction->ReplaceWith(input_other);
481 instruction->GetBlock()->RemoveInstruction(instruction);
482 return;
483 }
484
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000485 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000486 // Replace code looking like
487 // DIV dst, src, -1
488 // with
489 // NEG dst, src
490 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000491 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100492 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000493 return;
494 }
495
496 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
497 // Try replacing code looking like
498 // DIV dst, src, constant
499 // with
500 // MUL dst, src, 1 / constant
501 HConstant* reciprocal = nullptr;
502 if (type == Primitive::Primitive::kPrimDouble) {
503 double value = input_cst->AsDoubleConstant()->GetValue();
504 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
505 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
506 }
507 } else {
508 DCHECK_EQ(type, Primitive::kPrimFloat);
509 float value = input_cst->AsFloatConstant()->GetValue();
510 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
511 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
512 }
513 }
514
515 if (reciprocal != nullptr) {
516 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
517 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
518 RecordSimplification();
519 return;
520 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000521 }
522}
523
524void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
525 HConstant* input_cst = instruction->GetConstantRight();
526 HInstruction* input_other = instruction->GetLeastConstantLeft();
527 Primitive::Type type = instruction->GetType();
528 HBasicBlock* block = instruction->GetBlock();
529 ArenaAllocator* allocator = GetGraph()->GetArena();
530
531 if (input_cst == nullptr) {
532 return;
533 }
534
535 if (input_cst->IsOne()) {
536 // Replace code looking like
537 // MUL dst, src, 1
538 // with
539 // src
540 instruction->ReplaceWith(input_other);
541 instruction->GetBlock()->RemoveInstruction(instruction);
542 return;
543 }
544
545 if (input_cst->IsMinusOne() &&
546 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
547 // Replace code looking like
548 // MUL dst, src, -1
549 // with
550 // NEG dst, src
551 HNeg* neg = new (allocator) HNeg(type, input_other);
552 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100553 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000554 return;
555 }
556
557 if (Primitive::IsFloatingPointType(type) &&
558 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
559 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
560 // Replace code looking like
561 // FP_MUL dst, src, 2.0
562 // with
563 // FP_ADD dst, src, src
564 // The 'int' and 'long' cases are handled below.
565 block->ReplaceAndRemoveInstructionWith(instruction,
566 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100567 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000568 return;
569 }
570
571 if (Primitive::IsIntOrLongType(type)) {
572 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600573 // Even though constant propagation also takes care of the zero case, other
574 // optimizations can lead to having a zero multiplication.
575 if (factor == 0) {
576 // Replace code looking like
577 // MUL dst, src, 0
578 // with
579 // 0
580 instruction->ReplaceWith(input_cst);
581 instruction->GetBlock()->RemoveInstruction(instruction);
582 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000583 // Replace code looking like
584 // MUL dst, src, pow_of_2
585 // with
586 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000587 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000588 HShl* shl = new(allocator) HShl(type, input_other, shift);
589 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100590 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000591 }
592 }
593}
594
Alexandre Rames188d4312015-04-09 18:30:21 +0100595void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
596 HInstruction* input = instruction->GetInput();
597 if (input->IsNeg()) {
598 // Replace code looking like
599 // NEG tmp, src
600 // NEG dst, tmp
601 // with
602 // src
603 HNeg* previous_neg = input->AsNeg();
604 instruction->ReplaceWith(previous_neg->GetInput());
605 instruction->GetBlock()->RemoveInstruction(instruction);
606 // We perform the optimization even if the input negation has environment
607 // uses since it allows removing the current instruction. But we only delete
608 // the input negation only if it is does not have any uses left.
609 if (!previous_neg->HasUses()) {
610 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
611 }
612 RecordSimplification();
613 return;
614 }
615
Serguei Katkov339dfc22015-04-20 12:29:32 +0600616 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
617 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100618 // Replace code looking like
619 // SUB tmp, a, b
620 // NEG dst, tmp
621 // with
622 // SUB dst, b, a
623 // We do not perform the optimization if the input subtraction has
624 // environment uses or multiple non-environment uses as it could lead to
625 // worse code. In particular, we do not want the live ranges of `a` and `b`
626 // to be extended if we are not sure the initial 'SUB' instruction can be
627 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600628 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100629 HSub* sub = input->AsSub();
630 HSub* new_sub =
631 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
632 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
633 if (!sub->HasUses()) {
634 sub->GetBlock()->RemoveInstruction(sub);
635 }
636 RecordSimplification();
637 }
638}
639
640void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
641 HInstruction* input = instruction->GetInput();
642 if (input->IsNot()) {
643 // Replace code looking like
644 // NOT tmp, src
645 // NOT dst, tmp
646 // with
647 // src
648 // We perform the optimization even if the input negation has environment
649 // uses since it allows removing the current instruction. But we only delete
650 // the input negation only if it is does not have any uses left.
651 HNot* previous_not = input->AsNot();
652 instruction->ReplaceWith(previous_not->GetInput());
653 instruction->GetBlock()->RemoveInstruction(instruction);
654 if (!previous_not->HasUses()) {
655 previous_not->GetBlock()->RemoveInstruction(previous_not);
656 }
657 RecordSimplification();
658 }
659}
660
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000661void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
662 HConstant* input_cst = instruction->GetConstantRight();
663 HInstruction* input_other = instruction->GetLeastConstantLeft();
664
665 if ((input_cst != nullptr) && input_cst->IsZero()) {
666 // Replace code looking like
667 // OR dst, src, 0
668 // with
669 // src
670 instruction->ReplaceWith(input_other);
671 instruction->GetBlock()->RemoveInstruction(instruction);
672 return;
673 }
674
675 // We assume that GVN has run before, so we only perform a pointer comparison.
676 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100677 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000678 if (instruction->GetLeft() == instruction->GetRight()) {
679 // Replace code looking like
680 // OR dst, src, src
681 // with
682 // src
683 instruction->ReplaceWith(instruction->GetLeft());
684 instruction->GetBlock()->RemoveInstruction(instruction);
685 }
686}
687
688void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
689 VisitShift(instruction);
690}
691
692void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
693 VisitShift(instruction);
694}
695
696void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
697 HConstant* input_cst = instruction->GetConstantRight();
698 HInstruction* input_other = instruction->GetLeastConstantLeft();
699
700 if ((input_cst != nullptr) && input_cst->IsZero()) {
701 // Replace code looking like
702 // SUB dst, src, 0
703 // with
704 // src
705 instruction->ReplaceWith(input_other);
706 instruction->GetBlock()->RemoveInstruction(instruction);
707 return;
708 }
709
710 Primitive::Type type = instruction->GetType();
711 if (!Primitive::IsIntegralType(type)) {
712 return;
713 }
714
715 HBasicBlock* block = instruction->GetBlock();
716 ArenaAllocator* allocator = GetGraph()->GetArena();
717
Alexandre Rames188d4312015-04-09 18:30:21 +0100718 HInstruction* left = instruction->GetLeft();
719 HInstruction* right = instruction->GetRight();
720 if (left->IsConstant()) {
721 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000722 // Replace code looking like
723 // SUB dst, 0, src
724 // with
725 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100726 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000727 // `x` is `0.0`, the former expression yields `0.0`, while the later
728 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100729 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000730 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100731 RecordSimplification();
732 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000733 }
734 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100735
736 if (left->IsNeg() && right->IsNeg()) {
737 if (TryMoveNegOnInputsAfterBinop(instruction)) {
738 return;
739 }
740 }
741
742 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
743 // Replace code looking like
744 // NEG tmp, b
745 // SUB dst, a, tmp
746 // with
747 // ADD dst, a, b
748 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
749 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
750 RecordSimplification();
751 right->GetBlock()->RemoveInstruction(right);
752 return;
753 }
754
755 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
756 // Replace code looking like
757 // NEG tmp, a
758 // SUB dst, tmp, b
759 // with
760 // ADD tmp, a, b
761 // NEG dst, tmp
762 // The second version is not intrinsically better, but enables more
763 // transformations.
764 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
765 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
766 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
767 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
768 instruction->ReplaceWith(neg);
769 instruction->GetBlock()->RemoveInstruction(instruction);
770 RecordSimplification();
771 left->GetBlock()->RemoveInstruction(left);
772 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000773}
774
775void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
776 VisitShift(instruction);
777}
778
779void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
780 HConstant* input_cst = instruction->GetConstantRight();
781 HInstruction* input_other = instruction->GetLeastConstantLeft();
782
783 if ((input_cst != nullptr) && input_cst->IsZero()) {
784 // Replace code looking like
785 // XOR dst, src, 0
786 // with
787 // src
788 instruction->ReplaceWith(input_other);
789 instruction->GetBlock()->RemoveInstruction(instruction);
790 return;
791 }
792
793 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
794 // Replace code looking like
795 // XOR dst, src, 0xFFF...FF
796 // with
797 // NOT dst, src
798 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
799 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +0100800 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000801 return;
802 }
803}
804
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100805} // namespace art