instruction_simplifier.cc revision 1e9ec053008fca7eb713815716c69375c37b399c
1/*
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
19#include "mirror/class-inl.h"
20#include "scoped_thread_state_change.h"
21
22namespace art {
23
24class InstructionSimplifierVisitor : public HGraphVisitor {
25 public:
26  InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
27      : HGraphVisitor(graph),
28        stats_(stats) {}
29
30  void Run();
31
32 private:
33  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);
42  void VisitShift(HBinaryOperation* shift);
43
44  void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
45  void VisitEqual(HEqual* equal) OVERRIDE;
46  void VisitNotEqual(HNotEqual* equal) OVERRIDE;
47  void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
48  void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
49  void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
50  void VisitArraySet(HArraySet* equal) OVERRIDE;
51  void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
52  void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
53  void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
54  void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
55  void VisitAdd(HAdd* instruction) OVERRIDE;
56  void VisitAnd(HAnd* instruction) OVERRIDE;
57  void VisitDiv(HDiv* instruction) OVERRIDE;
58  void VisitMul(HMul* instruction) OVERRIDE;
59  void VisitNeg(HNeg* instruction) OVERRIDE;
60  void VisitNot(HNot* instruction) OVERRIDE;
61  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;
67  void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
68  bool IsDominatedByInputNullCheck(HInstruction* instr);
69
70  OptimizingCompilerStats* stats_;
71  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;
76};
77
78void InstructionSimplifier::Run() {
79  InstructionSimplifierVisitor visitor(graph_, stats_);
80  visitor.Run();
81}
82
83void InstructionSimplifierVisitor::Run() {
84  // Iterate in reverse post order to open up more simplifications to users
85  // of instructions that got simplified.
86  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    }
98    simplifications_at_current_position_ = 0;
99    it.Advance();
100  }
101}
102
103namespace {
104
105bool AreAllBitsSet(HConstant* constant) {
106  return Int64FromConstant(constant) == -1;
107}
108
109}  // namespace
110
111// 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
140void 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
145  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    }
164  }
165}
166
167void 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);
172    if (stats_ != nullptr) {
173      stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
174    }
175  }
176}
177
178bool 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
189// 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()) {
193    // 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.
196    return false;
197  }
198
199  ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
200  ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
201  ScopedObjectAccess soa(Thread::Current());
202  if (class_rti.IsSupertypeOf(obj_rti)) {
203    *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()
210             && !obj_rti.IsInterface()
211             && !obj_rti.IsSupertypeOf(class_rti)) {
212    // Different type hierarchy. The test will fail.
213    *outcome = false;
214    return true;
215  }
216  return false;
217}
218
219void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
220  HInstruction* object = check_cast->InputAt(0);
221  if (!object->CanBeNull() || IsDominatedByInputNullCheck(check_cast)) {
222    check_cast->ClearMustDoNullCheck();
223  }
224
225  if (object->IsNullConstant()) {
226    check_cast->GetBlock()->RemoveInstruction(check_cast);
227    if (stats_ != nullptr) {
228      stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
229    }
230    return;
231  }
232
233  bool outcome;
234  if (TypeCheckHasKnownOutcome(check_cast->InputAt(1)->AsLoadClass(), object, &outcome)) {
235    if (outcome) {
236      check_cast->GetBlock()->RemoveInstruction(check_cast);
237      if (stats_ != nullptr) {
238        stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
239      }
240    } else {
241      // Don't do anything for exceptional cases for now. Ideally we should remove
242      // all instructions and blocks this instruction dominates.
243    }
244  }
245}
246
247void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
248  HInstruction* object = instruction->InputAt(0);
249  bool can_be_null = true;
250  if (!object->CanBeNull() || IsDominatedByInputNullCheck(instruction)) {
251    can_be_null = false;
252    instruction->ClearMustDoNullCheck();
253  }
254
255  HGraph* graph = GetGraph();
256  if (object->IsNullConstant()) {
257    instruction->ReplaceWith(graph->GetIntConstant(0));
258    instruction->GetBlock()->RemoveInstruction(instruction);
259    RecordSimplification();
260    return;
261  }
262
263  bool outcome;
264  if (TypeCheckHasKnownOutcome(instruction->InputAt(1)->AsLoadClass(), object, &outcome)) {
265    if (outcome && can_be_null) {
266      // Type test will succeed, we just need a null test.
267      HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
268      instruction->GetBlock()->InsertInstructionBefore(test, instruction);
269      instruction->ReplaceWith(test);
270    } else {
271      // We've statically determined the result of the instanceof.
272      instruction->ReplaceWith(graph->GetIntConstant(outcome));
273    }
274    RecordSimplification();
275    instruction->GetBlock()->RemoveInstruction(instruction);
276  }
277}
278
279void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
280  if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
281      && !instruction->GetValue()->CanBeNull()) {
282    instruction->ClearValueCanBeNull();
283  }
284}
285
286void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
287  if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
288      && !instruction->GetValue()->CanBeNull()) {
289    instruction->ClearValueCanBeNull();
290  }
291}
292
293void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
294  HBasicBlock* block = check->GetBlock();
295  // Currently always keep the suspend check at entry.
296  if (block->IsEntryBlock()) return;
297
298  // Currently always keep suspend checks at loop entry.
299  if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
300    DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
301    return;
302  }
303
304  // Remove the suspend check that was added at build time for the baseline
305  // compiler.
306  block->RemoveInstruction(check);
307}
308
309void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
310  HInstruction* input_const = equal->GetConstantRight();
311  if (input_const != nullptr) {
312    HInstruction* input_value = equal->GetLeastConstantLeft();
313    if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
314      HBasicBlock* block = equal->GetBlock();
315      // We are comparing the boolean to a constant which is of type int and can
316      // be any constant.
317      if (input_const->AsIntConstant()->IsOne()) {
318        // Replace (bool_value == true) with bool_value
319        equal->ReplaceWith(input_value);
320        block->RemoveInstruction(equal);
321        RecordSimplification();
322      } else if (input_const->AsIntConstant()->IsZero()) {
323        // Replace (bool_value == false) with !bool_value
324        block->ReplaceAndRemoveInstructionWith(
325            equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
326        RecordSimplification();
327      } else {
328        // Replace (bool_value == integer_not_zero_nor_one_constant) with false
329        equal->ReplaceWith(GetGraph()->GetIntConstant(0));
330        block->RemoveInstruction(equal);
331        RecordSimplification();
332      }
333    }
334  }
335}
336
337void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
338  HInstruction* input_const = not_equal->GetConstantRight();
339  if (input_const != nullptr) {
340    HInstruction* input_value = not_equal->GetLeastConstantLeft();
341    if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
342      HBasicBlock* block = not_equal->GetBlock();
343      // We are comparing the boolean to a constant which is of type int and can
344      // be any constant.
345      if (input_const->AsIntConstant()->IsOne()) {
346        // Replace (bool_value != true) with !bool_value
347        block->ReplaceAndRemoveInstructionWith(
348            not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
349        RecordSimplification();
350      } else if (input_const->AsIntConstant()->IsZero()) {
351        // Replace (bool_value != false) with bool_value
352        not_equal->ReplaceWith(input_value);
353        block->RemoveInstruction(not_equal);
354        RecordSimplification();
355      } else {
356        // Replace (bool_value != integer_not_zero_nor_one_constant) with true
357        not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
358        block->RemoveInstruction(not_equal);
359        RecordSimplification();
360      }
361    }
362  }
363}
364
365void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
366  HInstruction* parent = bool_not->InputAt(0);
367  if (parent->IsBooleanNot()) {
368    HInstruction* value = parent->InputAt(0);
369    // Replace (!(!bool_value)) with bool_value
370    bool_not->ReplaceWith(value);
371    bool_not->GetBlock()->RemoveInstruction(bool_not);
372    // It is possible that `parent` is dead at this point but we leave
373    // its removal to DCE for simplicity.
374    RecordSimplification();
375  }
376}
377
378void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
379  HInstruction* input = instruction->InputAt(0);
380  // If the array is a NewArray with constant size, replace the array length
381  // with the constant instruction. This helps the bounds check elimination phase.
382  if (input->IsNewArray()) {
383    input = input->InputAt(0);
384    if (input->IsIntConstant()) {
385      instruction->ReplaceWith(input);
386    }
387  }
388}
389
390void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
391  HInstruction* value = instruction->GetValue();
392  if (value->GetType() != Primitive::kPrimNot) return;
393
394  if (value->IsArrayGet()) {
395    if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
396      // If the code is just swapping elements in the array, no need for a type check.
397      instruction->ClearNeedsTypeCheck();
398    }
399  }
400
401  if (!value->CanBeNull()) {
402    instruction->ClearValueCanBeNull();
403  }
404}
405
406void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
407  if (instruction->GetResultType() == instruction->GetInputType()) {
408    // Remove the instruction if it's converting to the same type.
409    instruction->ReplaceWith(instruction->GetInput());
410    instruction->GetBlock()->RemoveInstruction(instruction);
411  }
412}
413
414void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
415  HConstant* input_cst = instruction->GetConstantRight();
416  HInstruction* input_other = instruction->GetLeastConstantLeft();
417  if ((input_cst != nullptr) && input_cst->IsZero()) {
418    // Replace code looking like
419    //    ADD dst, src, 0
420    // with
421    //    src
422    instruction->ReplaceWith(input_other);
423    instruction->GetBlock()->RemoveInstruction(instruction);
424    return;
425  }
426
427  HInstruction* left = instruction->GetLeft();
428  HInstruction* right = instruction->GetRight();
429  bool left_is_neg = left->IsNeg();
430  bool right_is_neg = right->IsNeg();
431
432  if (left_is_neg && right_is_neg) {
433    if (TryMoveNegOnInputsAfterBinop(instruction)) {
434      return;
435    }
436  }
437
438  HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
439  if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
440    // Replace code looking like
441    //    NEG tmp, b
442    //    ADD dst, a, tmp
443    // with
444    //    SUB dst, a, b
445    // We do not perform the optimization if the input negation has environment
446    // uses or multiple non-environment uses as it could lead to worse code. In
447    // particular, we do not want the live range of `b` to be extended if we are
448    // not sure the initial 'NEG' instruction can be removed.
449    HInstruction* other = left_is_neg ? right : left;
450    HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
451    instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
452    RecordSimplification();
453    neg->GetBlock()->RemoveInstruction(neg);
454  }
455}
456
457void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
458  HConstant* input_cst = instruction->GetConstantRight();
459  HInstruction* input_other = instruction->GetLeastConstantLeft();
460
461  if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
462    // Replace code looking like
463    //    AND dst, src, 0xFFF...FF
464    // with
465    //    src
466    instruction->ReplaceWith(input_other);
467    instruction->GetBlock()->RemoveInstruction(instruction);
468    return;
469  }
470
471  // We assume that GVN has run before, so we only perform a pointer comparison.
472  // If for some reason the values are equal but the pointers are different, we
473  // are still correct and only miss an optimization opportunity.
474  if (instruction->GetLeft() == instruction->GetRight()) {
475    // Replace code looking like
476    //    AND dst, src, src
477    // with
478    //    src
479    instruction->ReplaceWith(instruction->GetLeft());
480    instruction->GetBlock()->RemoveInstruction(instruction);
481  }
482}
483
484void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
485  HConstant* input_cst = instruction->GetConstantRight();
486  HInstruction* input_other = instruction->GetLeastConstantLeft();
487  Primitive::Type type = instruction->GetType();
488
489  if ((input_cst != nullptr) && input_cst->IsOne()) {
490    // Replace code looking like
491    //    DIV dst, src, 1
492    // with
493    //    src
494    instruction->ReplaceWith(input_other);
495    instruction->GetBlock()->RemoveInstruction(instruction);
496    return;
497  }
498
499  if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
500    // Replace code looking like
501    //    DIV dst, src, -1
502    // with
503    //    NEG dst, src
504    instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
505        instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
506    RecordSimplification();
507    return;
508  }
509
510  if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
511    // Try replacing code looking like
512    //    DIV dst, src, constant
513    // with
514    //    MUL dst, src, 1 / constant
515    HConstant* reciprocal = nullptr;
516    if (type == Primitive::Primitive::kPrimDouble) {
517      double value = input_cst->AsDoubleConstant()->GetValue();
518      if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
519        reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
520      }
521    } else {
522      DCHECK_EQ(type, Primitive::kPrimFloat);
523      float value = input_cst->AsFloatConstant()->GetValue();
524      if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
525        reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
526      }
527    }
528
529    if (reciprocal != nullptr) {
530      instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
531          instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
532      RecordSimplification();
533      return;
534    }
535  }
536}
537
538void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
539  HConstant* input_cst = instruction->GetConstantRight();
540  HInstruction* input_other = instruction->GetLeastConstantLeft();
541  Primitive::Type type = instruction->GetType();
542  HBasicBlock* block = instruction->GetBlock();
543  ArenaAllocator* allocator = GetGraph()->GetArena();
544
545  if (input_cst == nullptr) {
546    return;
547  }
548
549  if (input_cst->IsOne()) {
550    // Replace code looking like
551    //    MUL dst, src, 1
552    // with
553    //    src
554    instruction->ReplaceWith(input_other);
555    instruction->GetBlock()->RemoveInstruction(instruction);
556    return;
557  }
558
559  if (input_cst->IsMinusOne() &&
560      (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
561    // Replace code looking like
562    //    MUL dst, src, -1
563    // with
564    //    NEG dst, src
565    HNeg* neg = new (allocator) HNeg(type, input_other);
566    block->ReplaceAndRemoveInstructionWith(instruction, neg);
567    RecordSimplification();
568    return;
569  }
570
571  if (Primitive::IsFloatingPointType(type) &&
572      ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
573       (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
574    // Replace code looking like
575    //    FP_MUL dst, src, 2.0
576    // with
577    //    FP_ADD dst, src, src
578    // The 'int' and 'long' cases are handled below.
579    block->ReplaceAndRemoveInstructionWith(instruction,
580                                           new (allocator) HAdd(type, input_other, input_other));
581    RecordSimplification();
582    return;
583  }
584
585  if (Primitive::IsIntOrLongType(type)) {
586    int64_t factor = Int64FromConstant(input_cst);
587    // Even though constant propagation also takes care of the zero case, other
588    // optimizations can lead to having a zero multiplication.
589    if (factor == 0) {
590      // Replace code looking like
591      //    MUL dst, src, 0
592      // with
593      //    0
594      instruction->ReplaceWith(input_cst);
595      instruction->GetBlock()->RemoveInstruction(instruction);
596    } else if (IsPowerOfTwo(factor)) {
597      // Replace code looking like
598      //    MUL dst, src, pow_of_2
599      // with
600      //    SHL dst, src, log2(pow_of_2)
601      HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
602      HShl* shl = new(allocator) HShl(type, input_other, shift);
603      block->ReplaceAndRemoveInstructionWith(instruction, shl);
604      RecordSimplification();
605    }
606  }
607}
608
609void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
610  HInstruction* input = instruction->GetInput();
611  if (input->IsNeg()) {
612    // Replace code looking like
613    //    NEG tmp, src
614    //    NEG dst, tmp
615    // with
616    //    src
617    HNeg* previous_neg = input->AsNeg();
618    instruction->ReplaceWith(previous_neg->GetInput());
619    instruction->GetBlock()->RemoveInstruction(instruction);
620    // We perform the optimization even if the input negation has environment
621    // uses since it allows removing the current instruction. But we only delete
622    // the input negation only if it is does not have any uses left.
623    if (!previous_neg->HasUses()) {
624      previous_neg->GetBlock()->RemoveInstruction(previous_neg);
625    }
626    RecordSimplification();
627    return;
628  }
629
630  if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
631      !Primitive::IsFloatingPointType(input->GetType())) {
632    // Replace code looking like
633    //    SUB tmp, a, b
634    //    NEG dst, tmp
635    // with
636    //    SUB dst, b, a
637    // We do not perform the optimization if the input subtraction has
638    // environment uses or multiple non-environment uses as it could lead to
639    // worse code. In particular, we do not want the live ranges of `a` and `b`
640    // to be extended if we are not sure the initial 'SUB' instruction can be
641    // removed.
642    // We do not perform optimization for fp because we could lose the sign of zero.
643    HSub* sub = input->AsSub();
644    HSub* new_sub =
645        new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
646    instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
647    if (!sub->HasUses()) {
648      sub->GetBlock()->RemoveInstruction(sub);
649    }
650    RecordSimplification();
651  }
652}
653
654void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
655  HInstruction* input = instruction->GetInput();
656  if (input->IsNot()) {
657    // Replace code looking like
658    //    NOT tmp, src
659    //    NOT dst, tmp
660    // with
661    //    src
662    // We perform the optimization even if the input negation has environment
663    // uses since it allows removing the current instruction. But we only delete
664    // the input negation only if it is does not have any uses left.
665    HNot* previous_not = input->AsNot();
666    instruction->ReplaceWith(previous_not->GetInput());
667    instruction->GetBlock()->RemoveInstruction(instruction);
668    if (!previous_not->HasUses()) {
669      previous_not->GetBlock()->RemoveInstruction(previous_not);
670    }
671    RecordSimplification();
672  }
673}
674
675void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
676  HConstant* input_cst = instruction->GetConstantRight();
677  HInstruction* input_other = instruction->GetLeastConstantLeft();
678
679  if ((input_cst != nullptr) && input_cst->IsZero()) {
680    // Replace code looking like
681    //    OR dst, src, 0
682    // with
683    //    src
684    instruction->ReplaceWith(input_other);
685    instruction->GetBlock()->RemoveInstruction(instruction);
686    return;
687  }
688
689  // We assume that GVN has run before, so we only perform a pointer comparison.
690  // If for some reason the values are equal but the pointers are different, we
691  // are still correct and only miss an optimization opportunity.
692  if (instruction->GetLeft() == instruction->GetRight()) {
693    // Replace code looking like
694    //    OR dst, src, src
695    // with
696    //    src
697    instruction->ReplaceWith(instruction->GetLeft());
698    instruction->GetBlock()->RemoveInstruction(instruction);
699  }
700}
701
702void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
703  VisitShift(instruction);
704}
705
706void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
707  VisitShift(instruction);
708}
709
710void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
711  HConstant* input_cst = instruction->GetConstantRight();
712  HInstruction* input_other = instruction->GetLeastConstantLeft();
713
714  if ((input_cst != nullptr) && input_cst->IsZero()) {
715    // Replace code looking like
716    //    SUB dst, src, 0
717    // with
718    //    src
719    instruction->ReplaceWith(input_other);
720    instruction->GetBlock()->RemoveInstruction(instruction);
721    return;
722  }
723
724  Primitive::Type type = instruction->GetType();
725  if (!Primitive::IsIntegralType(type)) {
726    return;
727  }
728
729  HBasicBlock* block = instruction->GetBlock();
730  ArenaAllocator* allocator = GetGraph()->GetArena();
731
732  HInstruction* left = instruction->GetLeft();
733  HInstruction* right = instruction->GetRight();
734  if (left->IsConstant()) {
735    if (Int64FromConstant(left->AsConstant()) == 0) {
736      // Replace code looking like
737      //    SUB dst, 0, src
738      // with
739      //    NEG dst, src
740      // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
741      // `x` is `0.0`, the former expression yields `0.0`, while the later
742      // yields `-0.0`.
743      HNeg* neg = new (allocator) HNeg(type, right);
744      block->ReplaceAndRemoveInstructionWith(instruction, neg);
745      RecordSimplification();
746      return;
747    }
748  }
749
750  if (left->IsNeg() && right->IsNeg()) {
751    if (TryMoveNegOnInputsAfterBinop(instruction)) {
752      return;
753    }
754  }
755
756  if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
757    // Replace code looking like
758    //    NEG tmp, b
759    //    SUB dst, a, tmp
760    // with
761    //    ADD dst, a, b
762    HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
763    instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
764    RecordSimplification();
765    right->GetBlock()->RemoveInstruction(right);
766    return;
767  }
768
769  if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
770    // Replace code looking like
771    //    NEG tmp, a
772    //    SUB dst, tmp, b
773    // with
774    //    ADD tmp, a, b
775    //    NEG dst, tmp
776    // The second version is not intrinsically better, but enables more
777    // transformations.
778    HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
779    instruction->GetBlock()->InsertInstructionBefore(add, instruction);
780    HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
781    instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
782    instruction->ReplaceWith(neg);
783    instruction->GetBlock()->RemoveInstruction(instruction);
784    RecordSimplification();
785    left->GetBlock()->RemoveInstruction(left);
786  }
787}
788
789void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
790  VisitShift(instruction);
791}
792
793void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
794  HConstant* input_cst = instruction->GetConstantRight();
795  HInstruction* input_other = instruction->GetLeastConstantLeft();
796
797  if ((input_cst != nullptr) && input_cst->IsZero()) {
798    // Replace code looking like
799    //    XOR dst, src, 0
800    // with
801    //    src
802    instruction->ReplaceWith(input_other);
803    instruction->GetBlock()->RemoveInstruction(instruction);
804    return;
805  }
806
807  if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
808    // Replace code looking like
809    //    XOR dst, src, 0xFFF...FF
810    // with
811    //    NOT dst, src
812    HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
813    instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
814    RecordSimplification();
815    return;
816  }
817}
818
819}  // namespace art
820