blob: 337cf5b525a293b3304e4756f70658df6985fd36 [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;
Mark Mendellc4701932015-04-10 13:18:51 -040057 void VisitCondition(HCondition* instruction) OVERRIDE;
58 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
59 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
60 void VisitLessThan(HLessThan* condition) OVERRIDE;
61 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000062 void VisitDiv(HDiv* instruction) OVERRIDE;
63 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010064 void VisitNeg(HNeg* instruction) OVERRIDE;
65 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000066 void VisitOr(HOr* instruction) OVERRIDE;
67 void VisitShl(HShl* instruction) OVERRIDE;
68 void VisitShr(HShr* instruction) OVERRIDE;
69 void VisitSub(HSub* instruction) OVERRIDE;
70 void VisitUShr(HUShr* instruction) OVERRIDE;
71 void VisitXor(HXor* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010072 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +010073 bool IsDominatedByInputNullCheck(HInstruction* instr);
Calin Juravleacf735c2015-02-12 15:25:22 +000074
75 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010076 bool simplification_occurred_ = false;
77 int simplifications_at_current_position_ = 0;
78 // We ensure we do not loop infinitely. The value is a finger in the air guess
79 // that should allow enough simplification.
80 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000081};
82
Nicolas Geoffray3c049742014-09-24 18:10:46 +010083void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +000084 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +010085 visitor.Run();
86}
87
88void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +010089 // Iterate in reverse post order to open up more simplifications to users
90 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +010091 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
92 // The simplification of an instruction to another instruction may yield
93 // possibilities for other simplifications. So although we perform a reverse
94 // post order visit, we sometimes need to revisit an instruction index.
95 simplification_occurred_ = false;
96 VisitBasicBlock(it.Current());
97 if (simplification_occurred_ &&
98 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
99 // New simplifications may be applicable to the instruction at the
100 // current index, so don't advance the iterator.
101 continue;
102 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100103 simplifications_at_current_position_ = 0;
104 it.Advance();
105 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100106}
107
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000108namespace {
109
110bool AreAllBitsSet(HConstant* constant) {
111 return Int64FromConstant(constant) == -1;
112}
113
114} // namespace
115
Alexandre Rames188d4312015-04-09 18:30:21 +0100116// Returns true if the code was simplified to use only one negation operation
117// after the binary operation instead of one on each of the inputs.
118bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
119 DCHECK(binop->IsAdd() || binop->IsSub());
120 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
121 HNeg* left_neg = binop->GetLeft()->AsNeg();
122 HNeg* right_neg = binop->GetRight()->AsNeg();
123 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
124 !right_neg->HasOnlyOneNonEnvironmentUse()) {
125 return false;
126 }
127 // Replace code looking like
128 // NEG tmp1, a
129 // NEG tmp2, b
130 // ADD dst, tmp1, tmp2
131 // with
132 // ADD tmp, a, b
133 // NEG dst, tmp
134 binop->ReplaceInput(left_neg->GetInput(), 0);
135 binop->ReplaceInput(right_neg->GetInput(), 1);
136 left_neg->GetBlock()->RemoveInstruction(left_neg);
137 right_neg->GetBlock()->RemoveInstruction(right_neg);
138 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
139 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
140 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
141 RecordSimplification();
142 return true;
143}
144
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000145void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
146 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
147 HConstant* input_cst = instruction->GetConstantRight();
148 HInstruction* input_other = instruction->GetLeastConstantLeft();
149
Mark Mendellba56d062015-05-05 21:34:03 -0400150 if (input_cst != nullptr) {
151 if (input_cst->IsZero()) {
152 // Replace code looking like
153 // SHL dst, src, 0
154 // with
155 // src
156 instruction->ReplaceWith(input_other);
157 instruction->GetBlock()->RemoveInstruction(instruction);
158 } else if (instruction->IsShl() && input_cst->IsOne()) {
159 // Replace Shl looking like
160 // SHL dst, src, 1
161 // with
162 // ADD dst, src, src
163 HAdd *add = new(GetGraph()->GetArena()) HAdd(instruction->GetType(),
164 input_other,
165 input_other);
166 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
167 RecordSimplification();
168 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000169 }
170}
171
Calin Juravle10e244f2015-01-26 18:54:32 +0000172void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
173 HInstruction* obj = null_check->InputAt(0);
174 if (!obj->CanBeNull()) {
175 null_check->ReplaceWith(obj);
176 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000177 if (stats_ != nullptr) {
178 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
179 }
180 }
181}
182
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100183bool InstructionSimplifierVisitor::IsDominatedByInputNullCheck(HInstruction* instr) {
184 HInstruction* input = instr->InputAt(0);
185 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
186 HInstruction* use = it.Current()->GetUser();
187 if (use->IsNullCheck() && use->StrictlyDominates(instr)) {
188 return true;
189 }
190 }
191 return false;
192}
193
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100194// Returns whether doing a type test between the class of `object` against `klass` has
195// a statically known outcome. The result of the test is stored in `outcome`.
196static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
197 if (!klass->IsResolved()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000198 // If the class couldn't be resolve it's not safe to compare against it. It's
199 // default type would be Top which might be wider that the actual class type
200 // and thus producing wrong results.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100201 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000202 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100203
204 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
205 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravleacf735c2015-02-12 15:25:22 +0000206 ScopedObjectAccess soa(Thread::Current());
207 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100208 *outcome = true;
209 return true;
210 } else if (obj_rti.IsExact()) {
211 // The test failed at compile time so will also fail at runtime.
212 *outcome = false;
213 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100214 } else if (!class_rti.IsInterface()
215 && !obj_rti.IsInterface()
216 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100217 // Different type hierarchy. The test will fail.
218 *outcome = false;
219 return true;
220 }
221 return false;
222}
223
224void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
225 HInstruction* object = check_cast->InputAt(0);
226 if (!object->CanBeNull() || IsDominatedByInputNullCheck(check_cast)) {
227 check_cast->ClearMustDoNullCheck();
228 }
229
230 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000231 check_cast->GetBlock()->RemoveInstruction(check_cast);
232 if (stats_ != nullptr) {
233 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
234 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100235 return;
236 }
237
238 bool outcome;
239 if (TypeCheckHasKnownOutcome(check_cast->InputAt(1)->AsLoadClass(), object, &outcome)) {
240 if (outcome) {
241 check_cast->GetBlock()->RemoveInstruction(check_cast);
242 if (stats_ != nullptr) {
243 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
244 }
245 } else {
246 // Don't do anything for exceptional cases for now. Ideally we should remove
247 // all instructions and blocks this instruction dominates.
248 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000249 }
250}
251
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100252void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100253 HInstruction* object = instruction->InputAt(0);
254 bool can_be_null = true;
255 if (!object->CanBeNull() || IsDominatedByInputNullCheck(instruction)) {
256 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100257 instruction->ClearMustDoNullCheck();
258 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100259
260 HGraph* graph = GetGraph();
261 if (object->IsNullConstant()) {
262 instruction->ReplaceWith(graph->GetIntConstant(0));
263 instruction->GetBlock()->RemoveInstruction(instruction);
264 RecordSimplification();
265 return;
266 }
267
268 bool outcome;
269 if (TypeCheckHasKnownOutcome(instruction->InputAt(1)->AsLoadClass(), object, &outcome)) {
270 if (outcome && can_be_null) {
271 // Type test will succeed, we just need a null test.
272 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
273 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
274 instruction->ReplaceWith(test);
275 } else {
276 // We've statically determined the result of the instanceof.
277 instruction->ReplaceWith(graph->GetIntConstant(outcome));
278 }
279 RecordSimplification();
280 instruction->GetBlock()->RemoveInstruction(instruction);
281 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100282}
283
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100284void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
285 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
286 && !instruction->GetValue()->CanBeNull()) {
287 instruction->ClearValueCanBeNull();
288 }
289}
290
291void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
292 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
293 && !instruction->GetValue()->CanBeNull()) {
294 instruction->ClearValueCanBeNull();
295 }
296}
297
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000298void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100299 HBasicBlock* block = check->GetBlock();
300 // Currently always keep the suspend check at entry.
301 if (block->IsEntryBlock()) return;
302
303 // Currently always keep suspend checks at loop entry.
304 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
305 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
306 return;
307 }
308
309 // Remove the suspend check that was added at build time for the baseline
310 // compiler.
311 block->RemoveInstruction(check);
312}
313
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000314void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100315 HInstruction* input_const = equal->GetConstantRight();
316 if (input_const != nullptr) {
317 HInstruction* input_value = equal->GetLeastConstantLeft();
318 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
319 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100320 // We are comparing the boolean to a constant which is of type int and can
321 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100322 if (input_const->AsIntConstant()->IsOne()) {
323 // Replace (bool_value == true) with bool_value
324 equal->ReplaceWith(input_value);
325 block->RemoveInstruction(equal);
326 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100327 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100328 // Replace (bool_value == false) with !bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100329 block->ReplaceAndRemoveInstructionWith(
330 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
331 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100332 } else {
333 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
334 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
335 block->RemoveInstruction(equal);
336 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100337 }
Mark Mendellc4701932015-04-10 13:18:51 -0400338 } else {
339 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100340 }
Mark Mendellc4701932015-04-10 13:18:51 -0400341 } else {
342 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100343 }
344}
345
David Brazdil0d13fee2015-04-17 14:52:19 +0100346void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
347 HInstruction* input_const = not_equal->GetConstantRight();
348 if (input_const != nullptr) {
349 HInstruction* input_value = not_equal->GetLeastConstantLeft();
350 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
351 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100352 // We are comparing the boolean to a constant which is of type int and can
353 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100354 if (input_const->AsIntConstant()->IsOne()) {
355 // Replace (bool_value != true) with !bool_value
356 block->ReplaceAndRemoveInstructionWith(
357 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
358 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100359 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100360 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100361 not_equal->ReplaceWith(input_value);
362 block->RemoveInstruction(not_equal);
363 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100364 } else {
365 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
366 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
367 block->RemoveInstruction(not_equal);
368 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100369 }
Mark Mendellc4701932015-04-10 13:18:51 -0400370 } else {
371 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100372 }
Mark Mendellc4701932015-04-10 13:18:51 -0400373 } else {
374 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100375 }
376}
377
378void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
379 HInstruction* parent = bool_not->InputAt(0);
380 if (parent->IsBooleanNot()) {
381 HInstruction* value = parent->InputAt(0);
382 // Replace (!(!bool_value)) with bool_value
383 bool_not->ReplaceWith(value);
384 bool_not->GetBlock()->RemoveInstruction(bool_not);
385 // It is possible that `parent` is dead at this point but we leave
386 // its removal to DCE for simplicity.
387 RecordSimplification();
388 }
389}
390
Mingyao Yang0304e182015-01-30 16:41:29 -0800391void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
392 HInstruction* input = instruction->InputAt(0);
393 // If the array is a NewArray with constant size, replace the array length
394 // with the constant instruction. This helps the bounds check elimination phase.
395 if (input->IsNewArray()) {
396 input = input->InputAt(0);
397 if (input->IsIntConstant()) {
398 instruction->ReplaceWith(input);
399 }
400 }
401}
402
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000403void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000404 HInstruction* value = instruction->GetValue();
405 if (value->GetType() != Primitive::kPrimNot) return;
406
407 if (value->IsArrayGet()) {
408 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
409 // If the code is just swapping elements in the array, no need for a type check.
410 instruction->ClearNeedsTypeCheck();
411 }
412 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100413
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100414 if (value->IsNullConstant()) {
415 instruction->ClearNeedsTypeCheck();
416 }
417
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100418 if (!value->CanBeNull()) {
419 instruction->ClearValueCanBeNull();
420 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000421}
422
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000423void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
424 if (instruction->GetResultType() == instruction->GetInputType()) {
425 // Remove the instruction if it's converting to the same type.
426 instruction->ReplaceWith(instruction->GetInput());
427 instruction->GetBlock()->RemoveInstruction(instruction);
428 }
429}
430
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000431void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
432 HConstant* input_cst = instruction->GetConstantRight();
433 HInstruction* input_other = instruction->GetLeastConstantLeft();
434 if ((input_cst != nullptr) && input_cst->IsZero()) {
435 // Replace code looking like
436 // ADD dst, src, 0
437 // with
438 // src
439 instruction->ReplaceWith(input_other);
440 instruction->GetBlock()->RemoveInstruction(instruction);
Alexandre Rames188d4312015-04-09 18:30:21 +0100441 return;
442 }
443
444 HInstruction* left = instruction->GetLeft();
445 HInstruction* right = instruction->GetRight();
446 bool left_is_neg = left->IsNeg();
447 bool right_is_neg = right->IsNeg();
448
449 if (left_is_neg && right_is_neg) {
450 if (TryMoveNegOnInputsAfterBinop(instruction)) {
451 return;
452 }
453 }
454
455 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
456 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
457 // Replace code looking like
458 // NEG tmp, b
459 // ADD dst, a, tmp
460 // with
461 // SUB dst, a, b
462 // We do not perform the optimization if the input negation has environment
463 // uses or multiple non-environment uses as it could lead to worse code. In
464 // particular, we do not want the live range of `b` to be extended if we are
465 // not sure the initial 'NEG' instruction can be removed.
466 HInstruction* other = left_is_neg ? right : left;
467 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
468 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
469 RecordSimplification();
470 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000471 }
472}
473
474void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
475 HConstant* input_cst = instruction->GetConstantRight();
476 HInstruction* input_other = instruction->GetLeastConstantLeft();
477
478 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
479 // Replace code looking like
480 // AND dst, src, 0xFFF...FF
481 // with
482 // src
483 instruction->ReplaceWith(input_other);
484 instruction->GetBlock()->RemoveInstruction(instruction);
485 return;
486 }
487
488 // We assume that GVN has run before, so we only perform a pointer comparison.
489 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100490 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000491 if (instruction->GetLeft() == instruction->GetRight()) {
492 // Replace code looking like
493 // AND dst, src, src
494 // with
495 // src
496 instruction->ReplaceWith(instruction->GetLeft());
497 instruction->GetBlock()->RemoveInstruction(instruction);
498 }
499}
500
Mark Mendellc4701932015-04-10 13:18:51 -0400501void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
502 VisitCondition(condition);
503}
504
505void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
506 VisitCondition(condition);
507}
508
509void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
510 VisitCondition(condition);
511}
512
513void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
514 VisitCondition(condition);
515}
516
517void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
518 // Try to fold an HCompare into this HCondition.
519
520 // This simplification is currently only supported on x86 and x86_64.
521 // TODO: Implement it for ARM, ARM64 and MIPS64.
522 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
523 if (instruction_set != kX86 && instruction_set != kX86_64) {
524 return;
525 }
526
527 HInstruction* left = condition->GetLeft();
528 HInstruction* right = condition->GetRight();
529 // We can only replace an HCondition which compares a Compare to 0.
530 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
531 // condition with a long, float or double comparison as input.
532 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
533 // Conversion is not possible.
534 return;
535 }
536
537 // Is the Compare only used for this purpose?
538 if (!left->GetUses().HasOnlyOneUse()) {
539 // Someone else also wants the result of the compare.
540 return;
541 }
542
543 if (!left->GetEnvUses().IsEmpty()) {
544 // There is a reference to the compare result in an environment. Do we really need it?
545 if (GetGraph()->IsDebuggable()) {
546 return;
547 }
548
549 // We have to ensure that there are no deopt points in the sequence.
550 if (left->HasAnyEnvironmentUseBefore(condition)) {
551 return;
552 }
553 }
554
555 // Clean up any environment uses from the HCompare, if any.
556 left->RemoveEnvironmentUsers();
557
558 // We have decided to fold the HCompare into the HCondition. Transfer the information.
559 condition->SetBias(left->AsCompare()->GetBias());
560
561 // Replace the operands of the HCondition.
562 condition->ReplaceInput(left->InputAt(0), 0);
563 condition->ReplaceInput(left->InputAt(1), 1);
564
565 // Remove the HCompare.
566 left->GetBlock()->RemoveInstruction(left);
567
568 RecordSimplification();
569}
570
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000571void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
572 HConstant* input_cst = instruction->GetConstantRight();
573 HInstruction* input_other = instruction->GetLeastConstantLeft();
574 Primitive::Type type = instruction->GetType();
575
576 if ((input_cst != nullptr) && input_cst->IsOne()) {
577 // Replace code looking like
578 // DIV dst, src, 1
579 // with
580 // src
581 instruction->ReplaceWith(input_other);
582 instruction->GetBlock()->RemoveInstruction(instruction);
583 return;
584 }
585
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000586 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000587 // Replace code looking like
588 // DIV dst, src, -1
589 // with
590 // NEG dst, src
591 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000592 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100593 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000594 return;
595 }
596
597 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
598 // Try replacing code looking like
599 // DIV dst, src, constant
600 // with
601 // MUL dst, src, 1 / constant
602 HConstant* reciprocal = nullptr;
603 if (type == Primitive::Primitive::kPrimDouble) {
604 double value = input_cst->AsDoubleConstant()->GetValue();
605 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
606 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
607 }
608 } else {
609 DCHECK_EQ(type, Primitive::kPrimFloat);
610 float value = input_cst->AsFloatConstant()->GetValue();
611 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
612 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
613 }
614 }
615
616 if (reciprocal != nullptr) {
617 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
618 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
619 RecordSimplification();
620 return;
621 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000622 }
623}
624
625void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
626 HConstant* input_cst = instruction->GetConstantRight();
627 HInstruction* input_other = instruction->GetLeastConstantLeft();
628 Primitive::Type type = instruction->GetType();
629 HBasicBlock* block = instruction->GetBlock();
630 ArenaAllocator* allocator = GetGraph()->GetArena();
631
632 if (input_cst == nullptr) {
633 return;
634 }
635
636 if (input_cst->IsOne()) {
637 // Replace code looking like
638 // MUL dst, src, 1
639 // with
640 // src
641 instruction->ReplaceWith(input_other);
642 instruction->GetBlock()->RemoveInstruction(instruction);
643 return;
644 }
645
646 if (input_cst->IsMinusOne() &&
647 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
648 // Replace code looking like
649 // MUL dst, src, -1
650 // with
651 // NEG dst, src
652 HNeg* neg = new (allocator) HNeg(type, input_other);
653 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100654 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000655 return;
656 }
657
658 if (Primitive::IsFloatingPointType(type) &&
659 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
660 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
661 // Replace code looking like
662 // FP_MUL dst, src, 2.0
663 // with
664 // FP_ADD dst, src, src
665 // The 'int' and 'long' cases are handled below.
666 block->ReplaceAndRemoveInstructionWith(instruction,
667 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100668 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000669 return;
670 }
671
672 if (Primitive::IsIntOrLongType(type)) {
673 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600674 // Even though constant propagation also takes care of the zero case, other
675 // optimizations can lead to having a zero multiplication.
676 if (factor == 0) {
677 // Replace code looking like
678 // MUL dst, src, 0
679 // with
680 // 0
681 instruction->ReplaceWith(input_cst);
682 instruction->GetBlock()->RemoveInstruction(instruction);
683 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000684 // Replace code looking like
685 // MUL dst, src, pow_of_2
686 // with
687 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000688 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000689 HShl* shl = new(allocator) HShl(type, input_other, shift);
690 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100691 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000692 }
693 }
694}
695
Alexandre Rames188d4312015-04-09 18:30:21 +0100696void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
697 HInstruction* input = instruction->GetInput();
698 if (input->IsNeg()) {
699 // Replace code looking like
700 // NEG tmp, src
701 // NEG dst, tmp
702 // with
703 // src
704 HNeg* previous_neg = input->AsNeg();
705 instruction->ReplaceWith(previous_neg->GetInput());
706 instruction->GetBlock()->RemoveInstruction(instruction);
707 // We perform the optimization even if the input negation has environment
708 // uses since it allows removing the current instruction. But we only delete
709 // the input negation only if it is does not have any uses left.
710 if (!previous_neg->HasUses()) {
711 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
712 }
713 RecordSimplification();
714 return;
715 }
716
Serguei Katkov339dfc22015-04-20 12:29:32 +0600717 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
718 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100719 // Replace code looking like
720 // SUB tmp, a, b
721 // NEG dst, tmp
722 // with
723 // SUB dst, b, a
724 // We do not perform the optimization if the input subtraction has
725 // environment uses or multiple non-environment uses as it could lead to
726 // worse code. In particular, we do not want the live ranges of `a` and `b`
727 // to be extended if we are not sure the initial 'SUB' instruction can be
728 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600729 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100730 HSub* sub = input->AsSub();
731 HSub* new_sub =
732 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
733 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
734 if (!sub->HasUses()) {
735 sub->GetBlock()->RemoveInstruction(sub);
736 }
737 RecordSimplification();
738 }
739}
740
741void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
742 HInstruction* input = instruction->GetInput();
743 if (input->IsNot()) {
744 // Replace code looking like
745 // NOT tmp, src
746 // NOT dst, tmp
747 // with
748 // src
749 // We perform the optimization even if the input negation has environment
750 // uses since it allows removing the current instruction. But we only delete
751 // the input negation only if it is does not have any uses left.
752 HNot* previous_not = input->AsNot();
753 instruction->ReplaceWith(previous_not->GetInput());
754 instruction->GetBlock()->RemoveInstruction(instruction);
755 if (!previous_not->HasUses()) {
756 previous_not->GetBlock()->RemoveInstruction(previous_not);
757 }
758 RecordSimplification();
759 }
760}
761
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000762void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
763 HConstant* input_cst = instruction->GetConstantRight();
764 HInstruction* input_other = instruction->GetLeastConstantLeft();
765
766 if ((input_cst != nullptr) && input_cst->IsZero()) {
767 // Replace code looking like
768 // OR dst, src, 0
769 // with
770 // src
771 instruction->ReplaceWith(input_other);
772 instruction->GetBlock()->RemoveInstruction(instruction);
773 return;
774 }
775
776 // We assume that GVN has run before, so we only perform a pointer comparison.
777 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100778 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000779 if (instruction->GetLeft() == instruction->GetRight()) {
780 // Replace code looking like
781 // OR dst, src, src
782 // with
783 // src
784 instruction->ReplaceWith(instruction->GetLeft());
785 instruction->GetBlock()->RemoveInstruction(instruction);
786 }
787}
788
789void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
790 VisitShift(instruction);
791}
792
793void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
794 VisitShift(instruction);
795}
796
797void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
798 HConstant* input_cst = instruction->GetConstantRight();
799 HInstruction* input_other = instruction->GetLeastConstantLeft();
800
801 if ((input_cst != nullptr) && input_cst->IsZero()) {
802 // Replace code looking like
803 // SUB dst, src, 0
804 // with
805 // src
806 instruction->ReplaceWith(input_other);
807 instruction->GetBlock()->RemoveInstruction(instruction);
808 return;
809 }
810
811 Primitive::Type type = instruction->GetType();
812 if (!Primitive::IsIntegralType(type)) {
813 return;
814 }
815
816 HBasicBlock* block = instruction->GetBlock();
817 ArenaAllocator* allocator = GetGraph()->GetArena();
818
Alexandre Rames188d4312015-04-09 18:30:21 +0100819 HInstruction* left = instruction->GetLeft();
820 HInstruction* right = instruction->GetRight();
821 if (left->IsConstant()) {
822 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000823 // Replace code looking like
824 // SUB dst, 0, src
825 // with
826 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100827 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000828 // `x` is `0.0`, the former expression yields `0.0`, while the later
829 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100830 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000831 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100832 RecordSimplification();
833 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000834 }
835 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100836
837 if (left->IsNeg() && right->IsNeg()) {
838 if (TryMoveNegOnInputsAfterBinop(instruction)) {
839 return;
840 }
841 }
842
843 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
844 // Replace code looking like
845 // NEG tmp, b
846 // SUB dst, a, tmp
847 // with
848 // ADD dst, a, b
849 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
850 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
851 RecordSimplification();
852 right->GetBlock()->RemoveInstruction(right);
853 return;
854 }
855
856 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
857 // Replace code looking like
858 // NEG tmp, a
859 // SUB dst, tmp, b
860 // with
861 // ADD tmp, a, b
862 // NEG dst, tmp
863 // The second version is not intrinsically better, but enables more
864 // transformations.
865 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
866 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
867 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
868 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
869 instruction->ReplaceWith(neg);
870 instruction->GetBlock()->RemoveInstruction(instruction);
871 RecordSimplification();
872 left->GetBlock()->RemoveInstruction(left);
873 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000874}
875
876void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
877 VisitShift(instruction);
878}
879
880void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
881 HConstant* input_cst = instruction->GetConstantRight();
882 HInstruction* input_other = instruction->GetLeastConstantLeft();
883
884 if ((input_cst != nullptr) && input_cst->IsZero()) {
885 // Replace code looking like
886 // XOR dst, src, 0
887 // with
888 // src
889 instruction->ReplaceWith(input_other);
890 instruction->GetBlock()->RemoveInstruction(instruction);
891 return;
892 }
893
894 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
895 // Replace code looking like
896 // XOR dst, src, 0xFFF...FF
897 // with
898 // NOT dst, src
899 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
900 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +0100901 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000902 return;
903 }
904}
905
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100906} // namespace art