blob: 678924de6dd25f7d8822689d8c50250fbd8d47f6 [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;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100209 } else if (!class_rti.IsInterface()
210 && !obj_rti.IsInterface()
211 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100212 // 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()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000226 check_cast->GetBlock()->RemoveInstruction(check_cast);
227 if (stats_ != nullptr) {
228 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
229 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100230 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 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000244 }
245}
246
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100247void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100248 HInstruction* object = instruction->InputAt(0);
249 bool can_be_null = true;
250 if (!object->CanBeNull() || IsDominatedByInputNullCheck(instruction)) {
251 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100252 instruction->ClearMustDoNullCheck();
253 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100254
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 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100277}
278
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100279void 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
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000293void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100294 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
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000309void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100310 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();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100315 // We are comparing the boolean to a constant which is of type int and can
316 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100317 if (input_const->AsIntConstant()->IsOne()) {
318 // Replace (bool_value == true) with bool_value
319 equal->ReplaceWith(input_value);
320 block->RemoveInstruction(equal);
321 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100322 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100323 // Replace (bool_value == false) with !bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100324 block->ReplaceAndRemoveInstructionWith(
325 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
326 RecordSimplification();
327 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100328 }
329 }
330}
331
David Brazdil0d13fee2015-04-17 14:52:19 +0100332void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
333 HInstruction* input_const = not_equal->GetConstantRight();
334 if (input_const != nullptr) {
335 HInstruction* input_value = not_equal->GetLeastConstantLeft();
336 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
337 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100338 // We are comparing the boolean to a constant which is of type int and can
339 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100340 if (input_const->AsIntConstant()->IsOne()) {
341 // Replace (bool_value != true) with !bool_value
342 block->ReplaceAndRemoveInstructionWith(
343 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
344 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100345 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100346 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100347 not_equal->ReplaceWith(input_value);
348 block->RemoveInstruction(not_equal);
349 RecordSimplification();
350 }
351 }
352 }
353}
354
355void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
356 HInstruction* parent = bool_not->InputAt(0);
357 if (parent->IsBooleanNot()) {
358 HInstruction* value = parent->InputAt(0);
359 // Replace (!(!bool_value)) with bool_value
360 bool_not->ReplaceWith(value);
361 bool_not->GetBlock()->RemoveInstruction(bool_not);
362 // It is possible that `parent` is dead at this point but we leave
363 // its removal to DCE for simplicity.
364 RecordSimplification();
365 }
366}
367
Mingyao Yang0304e182015-01-30 16:41:29 -0800368void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
369 HInstruction* input = instruction->InputAt(0);
370 // If the array is a NewArray with constant size, replace the array length
371 // with the constant instruction. This helps the bounds check elimination phase.
372 if (input->IsNewArray()) {
373 input = input->InputAt(0);
374 if (input->IsIntConstant()) {
375 instruction->ReplaceWith(input);
376 }
377 }
378}
379
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000380void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000381 HInstruction* value = instruction->GetValue();
382 if (value->GetType() != Primitive::kPrimNot) return;
383
384 if (value->IsArrayGet()) {
385 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
386 // If the code is just swapping elements in the array, no need for a type check.
387 instruction->ClearNeedsTypeCheck();
388 }
389 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100390
391 if (!value->CanBeNull()) {
392 instruction->ClearValueCanBeNull();
393 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000394}
395
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000396void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
397 if (instruction->GetResultType() == instruction->GetInputType()) {
398 // Remove the instruction if it's converting to the same type.
399 instruction->ReplaceWith(instruction->GetInput());
400 instruction->GetBlock()->RemoveInstruction(instruction);
401 }
402}
403
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000404void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
405 HConstant* input_cst = instruction->GetConstantRight();
406 HInstruction* input_other = instruction->GetLeastConstantLeft();
407 if ((input_cst != nullptr) && input_cst->IsZero()) {
408 // Replace code looking like
409 // ADD dst, src, 0
410 // with
411 // src
412 instruction->ReplaceWith(input_other);
413 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames188d4312015-04-09 18:30:21 +0100414 return;
415 }
416
417 HInstruction* left = instruction->GetLeft();
418 HInstruction* right = instruction->GetRight();
419 bool left_is_neg = left->IsNeg();
420 bool right_is_neg = right->IsNeg();
421
422 if (left_is_neg && right_is_neg) {
423 if (TryMoveNegOnInputsAfterBinop(instruction)) {
424 return;
425 }
426 }
427
428 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
429 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
430 // Replace code looking like
431 // NEG tmp, b
432 // ADD dst, a, tmp
433 // with
434 // SUB dst, a, b
435 // We do not perform the optimization if the input negation has environment
436 // uses or multiple non-environment uses as it could lead to worse code. In
437 // particular, we do not want the live range of `b` to be extended if we are
438 // not sure the initial 'NEG' instruction can be removed.
439 HInstruction* other = left_is_neg ? right : left;
440 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
441 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
442 RecordSimplification();
443 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000444 }
445}
446
447void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
448 HConstant* input_cst = instruction->GetConstantRight();
449 HInstruction* input_other = instruction->GetLeastConstantLeft();
450
451 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
452 // Replace code looking like
453 // AND dst, src, 0xFFF...FF
454 // with
455 // src
456 instruction->ReplaceWith(input_other);
457 instruction->GetBlock()->RemoveInstruction(instruction);
458 return;
459 }
460
461 // We assume that GVN has run before, so we only perform a pointer comparison.
462 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100463 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000464 if (instruction->GetLeft() == instruction->GetRight()) {
465 // Replace code looking like
466 // AND dst, src, src
467 // with
468 // src
469 instruction->ReplaceWith(instruction->GetLeft());
470 instruction->GetBlock()->RemoveInstruction(instruction);
471 }
472}
473
474void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
475 HConstant* input_cst = instruction->GetConstantRight();
476 HInstruction* input_other = instruction->GetLeastConstantLeft();
477 Primitive::Type type = instruction->GetType();
478
479 if ((input_cst != nullptr) && input_cst->IsOne()) {
480 // Replace code looking like
481 // DIV dst, src, 1
482 // with
483 // src
484 instruction->ReplaceWith(input_other);
485 instruction->GetBlock()->RemoveInstruction(instruction);
486 return;
487 }
488
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000489 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000490 // Replace code looking like
491 // DIV dst, src, -1
492 // with
493 // NEG dst, src
494 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000495 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100496 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000497 return;
498 }
499
500 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
501 // Try replacing code looking like
502 // DIV dst, src, constant
503 // with
504 // MUL dst, src, 1 / constant
505 HConstant* reciprocal = nullptr;
506 if (type == Primitive::Primitive::kPrimDouble) {
507 double value = input_cst->AsDoubleConstant()->GetValue();
508 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
509 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
510 }
511 } else {
512 DCHECK_EQ(type, Primitive::kPrimFloat);
513 float value = input_cst->AsFloatConstant()->GetValue();
514 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
515 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
516 }
517 }
518
519 if (reciprocal != nullptr) {
520 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
521 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
522 RecordSimplification();
523 return;
524 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000525 }
526}
527
528void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
529 HConstant* input_cst = instruction->GetConstantRight();
530 HInstruction* input_other = instruction->GetLeastConstantLeft();
531 Primitive::Type type = instruction->GetType();
532 HBasicBlock* block = instruction->GetBlock();
533 ArenaAllocator* allocator = GetGraph()->GetArena();
534
535 if (input_cst == nullptr) {
536 return;
537 }
538
539 if (input_cst->IsOne()) {
540 // Replace code looking like
541 // MUL dst, src, 1
542 // with
543 // src
544 instruction->ReplaceWith(input_other);
545 instruction->GetBlock()->RemoveInstruction(instruction);
546 return;
547 }
548
549 if (input_cst->IsMinusOne() &&
550 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
551 // Replace code looking like
552 // MUL dst, src, -1
553 // with
554 // NEG dst, src
555 HNeg* neg = new (allocator) HNeg(type, input_other);
556 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100557 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000558 return;
559 }
560
561 if (Primitive::IsFloatingPointType(type) &&
562 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
563 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
564 // Replace code looking like
565 // FP_MUL dst, src, 2.0
566 // with
567 // FP_ADD dst, src, src
568 // The 'int' and 'long' cases are handled below.
569 block->ReplaceAndRemoveInstructionWith(instruction,
570 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100571 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000572 return;
573 }
574
575 if (Primitive::IsIntOrLongType(type)) {
576 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600577 // Even though constant propagation also takes care of the zero case, other
578 // optimizations can lead to having a zero multiplication.
579 if (factor == 0) {
580 // Replace code looking like
581 // MUL dst, src, 0
582 // with
583 // 0
584 instruction->ReplaceWith(input_cst);
585 instruction->GetBlock()->RemoveInstruction(instruction);
586 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000587 // Replace code looking like
588 // MUL dst, src, pow_of_2
589 // with
590 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000591 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000592 HShl* shl = new(allocator) HShl(type, input_other, shift);
593 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100594 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000595 }
596 }
597}
598
Alexandre Rames188d4312015-04-09 18:30:21 +0100599void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
600 HInstruction* input = instruction->GetInput();
601 if (input->IsNeg()) {
602 // Replace code looking like
603 // NEG tmp, src
604 // NEG dst, tmp
605 // with
606 // src
607 HNeg* previous_neg = input->AsNeg();
608 instruction->ReplaceWith(previous_neg->GetInput());
609 instruction->GetBlock()->RemoveInstruction(instruction);
610 // We perform the optimization even if the input negation has environment
611 // uses since it allows removing the current instruction. But we only delete
612 // the input negation only if it is does not have any uses left.
613 if (!previous_neg->HasUses()) {
614 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
615 }
616 RecordSimplification();
617 return;
618 }
619
Serguei Katkov339dfc22015-04-20 12:29:32 +0600620 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
621 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100622 // Replace code looking like
623 // SUB tmp, a, b
624 // NEG dst, tmp
625 // with
626 // SUB dst, b, a
627 // We do not perform the optimization if the input subtraction has
628 // environment uses or multiple non-environment uses as it could lead to
629 // worse code. In particular, we do not want the live ranges of `a` and `b`
630 // to be extended if we are not sure the initial 'SUB' instruction can be
631 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600632 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100633 HSub* sub = input->AsSub();
634 HSub* new_sub =
635 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
636 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
637 if (!sub->HasUses()) {
638 sub->GetBlock()->RemoveInstruction(sub);
639 }
640 RecordSimplification();
641 }
642}
643
644void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
645 HInstruction* input = instruction->GetInput();
646 if (input->IsNot()) {
647 // Replace code looking like
648 // NOT tmp, src
649 // NOT dst, tmp
650 // with
651 // src
652 // We perform the optimization even if the input negation has environment
653 // uses since it allows removing the current instruction. But we only delete
654 // the input negation only if it is does not have any uses left.
655 HNot* previous_not = input->AsNot();
656 instruction->ReplaceWith(previous_not->GetInput());
657 instruction->GetBlock()->RemoveInstruction(instruction);
658 if (!previous_not->HasUses()) {
659 previous_not->GetBlock()->RemoveInstruction(previous_not);
660 }
661 RecordSimplification();
662 }
663}
664
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000665void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
666 HConstant* input_cst = instruction->GetConstantRight();
667 HInstruction* input_other = instruction->GetLeastConstantLeft();
668
669 if ((input_cst != nullptr) && input_cst->IsZero()) {
670 // Replace code looking like
671 // OR dst, src, 0
672 // with
673 // src
674 instruction->ReplaceWith(input_other);
675 instruction->GetBlock()->RemoveInstruction(instruction);
676 return;
677 }
678
679 // We assume that GVN has run before, so we only perform a pointer comparison.
680 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100681 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000682 if (instruction->GetLeft() == instruction->GetRight()) {
683 // Replace code looking like
684 // OR dst, src, src
685 // with
686 // src
687 instruction->ReplaceWith(instruction->GetLeft());
688 instruction->GetBlock()->RemoveInstruction(instruction);
689 }
690}
691
692void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
693 VisitShift(instruction);
694}
695
696void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
697 VisitShift(instruction);
698}
699
700void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
701 HConstant* input_cst = instruction->GetConstantRight();
702 HInstruction* input_other = instruction->GetLeastConstantLeft();
703
704 if ((input_cst != nullptr) && input_cst->IsZero()) {
705 // Replace code looking like
706 // SUB dst, src, 0
707 // with
708 // src
709 instruction->ReplaceWith(input_other);
710 instruction->GetBlock()->RemoveInstruction(instruction);
711 return;
712 }
713
714 Primitive::Type type = instruction->GetType();
715 if (!Primitive::IsIntegralType(type)) {
716 return;
717 }
718
719 HBasicBlock* block = instruction->GetBlock();
720 ArenaAllocator* allocator = GetGraph()->GetArena();
721
Alexandre Rames188d4312015-04-09 18:30:21 +0100722 HInstruction* left = instruction->GetLeft();
723 HInstruction* right = instruction->GetRight();
724 if (left->IsConstant()) {
725 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000726 // Replace code looking like
727 // SUB dst, 0, src
728 // with
729 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100730 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000731 // `x` is `0.0`, the former expression yields `0.0`, while the later
732 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100733 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000734 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100735 RecordSimplification();
736 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000737 }
738 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100739
740 if (left->IsNeg() && right->IsNeg()) {
741 if (TryMoveNegOnInputsAfterBinop(instruction)) {
742 return;
743 }
744 }
745
746 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
747 // Replace code looking like
748 // NEG tmp, b
749 // SUB dst, a, tmp
750 // with
751 // ADD dst, a, b
752 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
753 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
754 RecordSimplification();
755 right->GetBlock()->RemoveInstruction(right);
756 return;
757 }
758
759 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
760 // Replace code looking like
761 // NEG tmp, a
762 // SUB dst, tmp, b
763 // with
764 // ADD tmp, a, b
765 // NEG dst, tmp
766 // The second version is not intrinsically better, but enables more
767 // transformations.
768 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
769 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
770 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
771 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
772 instruction->ReplaceWith(neg);
773 instruction->GetBlock()->RemoveInstruction(instruction);
774 RecordSimplification();
775 left->GetBlock()->RemoveInstruction(left);
776 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000777}
778
779void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
780 VisitShift(instruction);
781}
782
783void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
784 HConstant* input_cst = instruction->GetConstantRight();
785 HInstruction* input_other = instruction->GetLeastConstantLeft();
786
787 if ((input_cst != nullptr) && input_cst->IsZero()) {
788 // Replace code looking like
789 // XOR dst, src, 0
790 // with
791 // src
792 instruction->ReplaceWith(input_other);
793 instruction->GetBlock()->RemoveInstruction(instruction);
794 return;
795 }
796
797 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
798 // Replace code looking like
799 // XOR dst, src, 0xFFF...FF
800 // with
801 // NOT dst, src
802 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
803 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +0100804 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000805 return;
806 }
807}
808
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100809} // namespace art